Skip to content

Commit f87eff4

Browse files
authored
Minor bug fixes and Performance Optimization (#57)
* Improve global function compatibility with generic type checking * Fix union upper generic bound not properly working and eagerly locking to the first type a generic tempalte encounter * Add support for native return type nullability checks and related tests * Improve Cache manager temp file handling * Fix edge cases in Cache Manager * Experimental optimization * Enhance isStaticSourcePath method to improve path validation for static source code repositories * Refactor bootstrap logic to enhance parallel processing detection and add new test cases for package path inclusion * Fix bug on getting root folder where it did not get the proper value of this library is installed as vendor dependency * use experimental manual tokinization instead of nikic parser in special type resolver * Optimize Stream Wrapper * Enhance CacheManager and SpecialTypeResolver with memoization and improved documentation * Normalize path checks to be case-insensitive for improved compatibility * Refactor getProjectRoot method to improve clarity and remove unnecessary checks * Normalize project root path resolution to handle real paths correctly * Refactor getProjectRoot method to improve path normalization and add documentationn and fix errors on windows ci
1 parent f8ae9dd commit f87eff4

18 files changed

Lines changed: 1380 additions & 206 deletions

‎src/Contract/ContractParser.php‎

Lines changed: 121 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,72 @@ final class ContractParser
6060
*/
6161
private static array $classLevelDocCache = [];
6262

63+
/**
64+
* Fast O(1) lookup matrix for scalar refinements compatible with PHP native built-in types.
65+
*
66+
* @var array<string, array<string, bool>>
67+
*/
68+
private const BUILTIN_REFINEMENTS = [
69+
'int' => [
70+
'positive-int' => true,
71+
'negative-int' => true,
72+
'non-positive-int' => true,
73+
'non-negative-int' => true,
74+
'non-zero-int' => true,
75+
'unsigned-int' => true,
76+
],
77+
'integer' => [
78+
'positive-int' => true,
79+
'negative-int' => true,
80+
'non-positive-int' => true,
81+
'non-negative-int' => true,
82+
'non-zero-int' => true,
83+
'unsigned-int' => true,
84+
],
85+
'string' => [
86+
'non-empty-string' => true,
87+
'numeric-string' => true,
88+
'lowercase-string' => true,
89+
'non-empty-lowercase-string' => true,
90+
'uppercase-string' => true,
91+
'non-empty-uppercase-string' => true,
92+
'class-string' => true,
93+
'interface-string' => true,
94+
'trait-string' => true,
95+
'enum-string' => true,
96+
'callable-string' => true,
97+
'literal-string' => true,
98+
'truthy-string' => true,
99+
'non-falsy-string' => true,
100+
],
101+
'float' => [
102+
'positive-float' => true,
103+
'negative-float' => true,
104+
'non-positive-float' => true,
105+
'non-negative-float' => true,
106+
'non-zero-float' => true,
107+
'double' => true,
108+
],
109+
'double' => [
110+
'positive-float' => true,
111+
'negative-float' => true,
112+
'non-positive-float' => true,
113+
'non-negative-float' => true,
114+
'non-zero-float' => true,
115+
'double' => true,
116+
],
117+
'bool' => [
118+
'true' => true,
119+
'false' => true,
120+
'boolean' => true,
121+
],
122+
'boolean' => [
123+
'true' => true,
124+
'false' => true,
125+
'boolean' => true,
126+
],
127+
];
128+
63129
/**
64130
* Resets the contract, property, and class-level docblock caches.
65131
*/
@@ -586,6 +652,14 @@ private static function parseFunction(\ReflectionFunction $ref): array
586652
if ($returnTag !== null) {
587653
$substitutedReturn = self::substituteAliases($returnTag->type, $aliases);
588654
$returnType = SpecialTypeResolver::resolve($substitutedReturn, $ref);
655+
656+
if (
657+
Config::isRespectNativeNullabilityEnabled()
658+
&& self::returnTypeExplicitlyAllowsNull($ref)
659+
&& ! self::typeContainsNull($returnType)
660+
) {
661+
$returnType = new NullableTypeNode($returnType);
662+
}
589663
}
590664

591665
return [
@@ -757,6 +831,14 @@ private static function parseMethodHierarchyDocs(
757831
if ($returnTag !== null) {
758832
$substitutedReturn = self::substituteAliases($returnTag->type, $aliases);
759833
$returnType = SpecialTypeResolver::resolve($substitutedReturn, $hierRef);
834+
835+
if (
836+
Config::isRespectNativeNullabilityEnabled()
837+
&& self::returnTypeExplicitlyAllowsNull($ref)
838+
&& ! self::typeContainsNull($returnType)
839+
) {
840+
$returnType = new NullableTypeNode($returnType);
841+
}
760842
}
761843
}
762844
}
@@ -877,13 +959,19 @@ private static function applyConstructorPromotionFallback(
877959
*/
878960
private static function isRefinementOfBuiltin(string $refinement, string $builtin): bool
879961
{
880-
return match ($builtin) {
881-
'int', 'integer' => \in_array($refinement, ['positive-int', 'negative-int', 'non-positive-int', 'non-negative-int', 'non-zero-int', 'unsigned-int'], true) || str_starts_with($refinement, 'int<'),
882-
'string' => \in_array($refinement, ['non-empty-string', 'numeric-string', 'lowercase-string', 'non-empty-lowercase-string', 'uppercase-string', 'non-empty-uppercase-string', 'class-string', 'interface-string', 'trait-string', 'enum-string', 'callable-string', 'literal-string', 'truthy-string', 'non-falsy-string'], true) || str_starts_with($refinement, 'class-string<'),
883-
'float', 'double' => \in_array($refinement, ['positive-float', 'negative-float', 'non-positive-float', 'non-negative-float', 'non-zero-float', 'double'], true),
884-
'bool', 'boolean' => \in_array($refinement, ['true', 'false', 'boolean'], true),
885-
default => false,
886-
};
962+
if (isset(self::BUILTIN_REFINEMENTS[$builtin][$refinement])) {
963+
return true;
964+
}
965+
966+
if (($builtin === 'int' || $builtin === 'integer') && str_starts_with($refinement, 'int<')) {
967+
return true;
968+
}
969+
970+
if ($builtin === 'string' && str_starts_with($refinement, 'class-string<')) {
971+
return true;
972+
}
973+
974+
return false;
887975
}
888976

889977
/**
@@ -912,6 +1000,32 @@ private static function parameterExplicitlyAllowsNull(\ReflectionParameter $p):
9121000
return false;
9131001
}
9141002

1003+
/**
1004+
* Checks if a reflection function or method explicitly declares a nullable native return type (excluding mixed, void, and never).
1005+
*/
1006+
private static function returnTypeExplicitlyAllowsNull(\ReflectionFunctionAbstract $ref): bool
1007+
{
1008+
if (! $ref->hasReturnType()) {
1009+
return false;
1010+
}
1011+
1012+
$type = $ref->getReturnType();
1013+
if ($type instanceof \ReflectionNamedType) {
1014+
$name = strtolower($type->getName());
1015+
if ($name === 'mixed' || $name === 'void' || $name === 'never') {
1016+
return false;
1017+
}
1018+
1019+
return $type->allowsNull();
1020+
}
1021+
1022+
if ($type instanceof \ReflectionUnionType) {
1023+
return $type->allowsNull();
1024+
}
1025+
1026+
return false;
1027+
}
1028+
9151029
/**
9161030
* Checks if a TypeNode already represents or contains null.
9171031
*/

‎src/Internal/CacheManager.php‎

Lines changed: 35 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,19 @@ final class CacheManager
2121
*/
2222
private static ?string $resolvedCacheDir = null;
2323

24+
/**
25+
* Memoized verification state of the cache directory.
26+
*/
27+
private static ?bool $secureDirVerified = null;
28+
2429
public static function reset(): void
2530
{
2631
self::$resolvedCacheDir = null;
32+
self::$secureDirVerified = null;
2733
}
2834

2935
/**
30-
* Returns the absolute path to the cache directory, isolating by system user and parallel test worker if using temp dir.
36+
* Returns the absolute path to the cache directory, isolating by system user if using temp dir.
3137
*/
3238
public static function getCacheDir(): string
3339
{
@@ -55,20 +61,7 @@ public static function getCacheDir(): string
5561
$user = (string) getmyuid();
5662
}
5763

58-
$testToken = getenv('TEST_TOKEN');
59-
$uniqueToken = getenv('UNIQUE_TEST_TOKEN');
60-
$pestWorkerId = getenv('PEST_PARALLEL_WORKER_ID');
61-
62-
$workerToken = '0';
63-
if (\is_string($testToken) && $testToken !== '') {
64-
$workerToken = $testToken;
65-
} elseif (\is_string($uniqueToken) && $uniqueToken !== '') {
66-
$workerToken = $uniqueToken;
67-
} elseif (\is_string($pestWorkerId) && $pestWorkerId !== '') {
68-
$workerToken = $pestWorkerId;
69-
}
70-
71-
$userHash = hash('xxh128', 'typephp_' . $user . '_w' . $workerToken);
64+
$userHash = hash('xxh128', 'typephp_' . $user);
7265

7366
return self::$resolvedCacheDir = sys_get_temp_dir() . '/typephp-cache-' . $userHash;
7467
}
@@ -93,50 +86,65 @@ public static function getCachedFilePath(string $resolvedPath): string
9386
}
9487

9588
/**
96-
* Ensures the cache directory exists securely with strict 0700 ownership.
89+
* Ensures the cache directory exists securely.
90+
* Enforces strict UID/0700 checks on system temp dirs, while allowing
91+
* standard application permissions on custom user-configured directories.
9792
*/
9893
public static function ensureSecureCacheDir(): bool
9994
{
95+
if (self::$secureDirVerified !== null) {
96+
return self::$secureDirVerified;
97+
}
98+
10099
$cacheDir = self::getCacheDir();
101100

102101
if (is_link($cacheDir)) {
103-
return false;
102+
return self::$secureDirVerified = false;
104103
}
105104

105+
$config = Config::get();
106+
$isCustomDir = \is_string($config['cache_dir'] ?? null) && $config['cache_dir'] !== '';
107+
106108
if (! is_dir($cacheDir)) {
107-
if (! @mkdir($cacheDir, 0700, recursive: true) && ! is_dir($cacheDir)) {
108-
return false;
109+
$mode = $isCustomDir ? 0775 : 0700;
110+
if (! @mkdir($cacheDir, $mode, recursive: true) && ! is_dir($cacheDir)) {
111+
return self::$secureDirVerified = false;
112+
}
113+
if (! $isCustomDir) {
114+
@chmod($cacheDir, 0700);
109115
}
110-
@chmod($cacheDir, 0700);
111116
}
112117

113-
if (\function_exists('posix_geteuid')) {
118+
if (! $isCustomDir && \function_exists('posix_geteuid')) {
114119
$owner = @fileowner($cacheDir);
115120
if ($owner !== false && $owner !== posix_geteuid()) {
116-
return false;
121+
return self::$secureDirVerified = false;
117122
}
118123
}
119124

120-
return true;
125+
return self::$secureDirVerified = is_writable($cacheDir);
121126
}
122127

123128
/**
124-
* Safely writes cached content atomically to avoid symlink traversal attacks.
129+
* Safely writes cached content atomically to avoid corruption or partial reads.
125130
*/
126131
public static function writeCachedFileSafely(string $cachedFile, string $transformed): bool
127132
{
128133
if (! self::ensureSecureCacheDir()) {
129134
return false;
130135
}
131136

137+
$config = Config::get();
138+
$isCustomDir = \is_string($config['cache_dir'] ?? null) && $config['cache_dir'] !== '';
139+
132140
$cacheDir = \dirname($cachedFile);
133141
$tmpFile = $cacheDir . '/.tmp_' . bin2hex(random_bytes(8));
134142

135-
if (@file_put_contents($tmpFile, $transformed, LOCK_EX) === false) {
143+
if (@file_put_contents($tmpFile, $transformed) === false) {
136144
return false;
137145
}
138146

139-
@chmod($tmpFile, 0600);
147+
@chmod($tmpFile, $isCustomDir ? 0664 : 0600);
140148

141149
if (! @rename($tmpFile, $cachedFile)) {
142150
@unlink($tmpFile);
@@ -148,8 +156,7 @@ public static function writeCachedFileSafely(string $cachedFile, string $transfo
148156
}
149157

150158
/**
151-
* Clears all cached transformed files from the cache directory,
152-
* including all parallel worker directories (_w1, _w2, etc.).
159+
* Clears all cached transformed files from the cache directory.
153160
*/
154161
public static function clear(): int
155162
{
@@ -193,7 +200,6 @@ public static function clear(): int
193200
}
194201
}
195202

196-
// Also clean up any lingering temporary swap files
197203
$tmpFiles = glob($dir . '/.tmp_*');
198204
if ($tmpFiles !== false) {
199205
foreach ($tmpFiles as $tFile) {

0 commit comments

Comments
 (0)