From 7ac2b3640b212fa27ef8299c5324ed97395fe401 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 26 Aug 2026 16:53:19 +0800 Subject: [PATCH 1/5] experimental optimization --- src/Internal/CacheManager.php | 18 ++++- src/Internal/Config.php | 2 + src/Internal/PathMatcher.php | 15 ++++ src/Internal/StreamWrapper.php | 123 ++++++++++++++++----------------- 4 files changed, 93 insertions(+), 65 deletions(-) diff --git a/src/Internal/CacheManager.php b/src/Internal/CacheManager.php index 9a48cb17..21735b34 100644 --- a/src/Internal/CacheManager.php +++ b/src/Internal/CacheManager.php @@ -16,16 +16,30 @@ final class CacheManager */ public const VERSION_PREFIX = 'v0.1_'; + /** + * Cached absolute cache directory path. + */ + private static ?string $resolvedCacheDir = null; + + public static function reset(): void + { + self::$resolvedCacheDir = null; + } + /** * Returns the absolute path to the cache directory, isolating by system user if using temp dir. */ public static function getCacheDir(): string { + if (self::$resolvedCacheDir !== null) { + return self::$resolvedCacheDir; + } + $config = Config::get(); $dir = $config['cache_dir'] ?? null; if (\is_string($dir) && $dir !== '') { - return $dir; + return self::$resolvedCacheDir = $dir; } $username = getenv('USERNAME'); @@ -43,7 +57,7 @@ public static function getCacheDir(): string $userHash = hash('xxh128', 'typephp_' . $user); - return sys_get_temp_dir() . '/typephp-cache-' . $userHash; + return self::$resolvedCacheDir = sys_get_temp_dir() . '/typephp-cache-' . $userHash; } /** diff --git a/src/Internal/Config.php b/src/Internal/Config.php index 87f2ee8a..e04bbcb0 100644 --- a/src/Internal/Config.php +++ b/src/Internal/Config.php @@ -266,6 +266,7 @@ public static function set(array $config): void StreamWrapper::reset(); StubManager::reset(); SpecialTypeResolver::reset(); + CacheManager::reset(); } /** @@ -325,6 +326,7 @@ public static function reset(): void StreamWrapper::reset(); StubManager::reset(); SpecialTypeResolver::reset(); + CacheManager::reset(); } /** diff --git a/src/Internal/PathMatcher.php b/src/Internal/PathMatcher.php index bc377631..fb437b28 100644 --- a/src/Internal/PathMatcher.php +++ b/src/Internal/PathMatcher.php @@ -54,6 +54,7 @@ public static function reset(): void self::$includePrefixCache = []; self::$cachedCacheDir = null; self::$cachedLibSrcDir = null; + CacheManager::reset(); } /** @@ -236,6 +237,8 @@ public static function mayPathBeIncluded(string $normalizedPath): bool $config = Config::get(); /** @var array $includes */ $includes = \is_array($config['include'] ?? null) ? $config['include'] : ['**']; + /** @var array $excludes */ + $excludes = \is_array($config['exclude'] ?? null) ? $config['exclude'] : []; if (str_contains($canon, '/vendor/') || str_starts_with($canon, 'vendor/')) { if (! self::hasIncludeMatchingPrefix('vendor/', $includes)) { @@ -255,6 +258,18 @@ public static function mayPathBeIncluded(string $normalizedPath): bool } } + if (str_contains($canon, '/tests/') || str_starts_with($canon, 'tests/')) { + if (! self::hasIncludeMatchingPrefix('tests/', $includes)) { + return false; + } + } + + if (str_contains($canon, '/Migration/') || str_contains($canon, '/migration/')) { + if (self::hasIncludeMatchingPrefix('Migration', $excludes) || self::hasIncludeMatchingPrefix('migration', $excludes)) { + return false; + } + } + return true; } diff --git a/src/Internal/StreamWrapper.php b/src/Internal/StreamWrapper.php index 77e708d8..474c4276 100644 --- a/src/Internal/StreamWrapper.php +++ b/src/Internal/StreamWrapper.php @@ -12,14 +12,15 @@ use TypePHP\Resolver\SpecialTypeResolver; /** - * Custom stream wrapper intercepting 'file://' inclusions to perform on-the-fly AST transformations. + * Intercepts PHP 'file://' protocol operations to perform on-the-fly AST transformations + * on included application source files while bypassing non-application paths and read-only inspections. * * @internal */ final class StreamWrapper implements StreamWrapperInterface { /** - * Bitmask constant passed by PHP's Zend Engine when a stream is opened by include/require. + * Bitmask constant passed by PHP's Zend Engine when a stream is opened by include or require. */ public const STREAM_OPEN_FOR_INCLUDE = 128; @@ -52,7 +53,7 @@ final class StreamWrapper implements StreamWrapperInterface private static array $statCache = []; /** - * In-memory cache for static-path negative misses only (e.g. vendor). + * In-memory cache for static-path negative misses only (e.g. vendor directories). * Never stores negative misses for dynamic paths (var/cache, storage). * * @var array @@ -67,7 +68,7 @@ final class StreamWrapper implements StreamWrapperInterface private static array $appFileDecisionCache = []; /** - * Fast-lookup table for read-only source view functions. + * Native PHP functions that read raw source code for viewing, highlighting, or tokenizing. * * @var array */ @@ -81,7 +82,7 @@ final class StreamWrapper implements StreamWrapperInterface ]; /** - * Resets all internal caches. + * Resets all internal in-memory caches and path matchers. */ public static function reset(): void { @@ -109,11 +110,17 @@ public static function register(array $config = []): void } } + /** + * Returns whether the stream wrapper is currently registered. + */ public static function isRegistered(): bool { return self::$isRegistered; } + /** + * Restores PHP's native 'file://' stream wrapper handler. + */ public static function unregister(): void { if (self::$isRegistered) { @@ -123,8 +130,8 @@ public static function unregister(): void } /** - * Transforms PHP source code by parsing AST, extracting metadata, applying ContractVisitor, and formatting output. - * Preserves exact line numbers to guarantee zero line-drift in debug stack traces. + * Transforms PHP source code by parsing AST, extracting metadata, applying ContractVisitor, + * and formatting output while preserving exact line numbers to prevent line-drift in debug stack traces. */ public static function transformSource(string $source, string $filePath = ''): string { @@ -188,54 +195,44 @@ public static function transformSource(string $source, string $filePath = ''): s } /** - * Opens a file stream, intercepting matching application files for AST transformation. - * Evaluates string fast-paths before checking file existence or unregistering the wrapper. + * Opens a file stream using a multi-stage validation pipeline: + * 1. Rejects non-include operations, non-read modes, and non-PHP files directly. + * 2. Runs high-speed string prefix pre-filtering to bypass excluded vendor, cache, and storage paths. + * 3. Detects native source-viewing functions (error screen highlighters and tokenizers) to serve raw source code. + * 4. Executes a single unregister/register block for application files to load cached or memory-transformed bytecode. */ public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool { - if ($mode !== 'r' && $mode !== 'rb' && $mode !== 'rt') { - return $this->openDirectHandle($path, $mode); - } - $isInclude = ($options & self::STREAM_OPEN_FOR_INCLUDE) !== 0; - if (! $isInclude) { - return $this->openDirectHandle($path, $mode); - } - if (! str_ends_with(strtolower($path), '.php')) { + if (! $isInclude || ($mode !== 'r' && $mode !== 'rb' && $mode !== 'rt') || ! str_ends_with(strtolower($path), '.php') || ! Config::isEnabled()) { return $this->openDirectHandle($path, $mode); } - if (! Config::isEnabled()) { + $normalizedRaw = str_replace('\\', '/', $path); + if (! PathMatcher::mayPathBeIncluded($normalizedRaw)) { return $this->openDirectHandle($path, $mode); } - $normalizedRaw = str_replace('\\', '/', $path); - if (! PathMatcher::mayPathBeIncluded($normalizedRaw)) { + if (self::isReadOnlyCall()) { return $this->openDirectHandle($path, $mode); } self::unregister(); + $exists = (bool) self::silent(fn () => file_exists($path)); $resolvedPath = $exists ? self::silent(fn () => realpath($path)) : false; - self::register(); - if (! $exists || $resolvedPath === false) { - return $this->openDirectHandle($path, $mode); - } - - $normalizedResolved = str_replace('\\', '/', $resolvedPath); - - if (! self::isApplicationFile($path, $resolvedPath)) { - return $this->openDirectHandle($normalizedResolved, $mode); - } + if (! $exists || $resolvedPath === false || ! self::isApplicationFile($path, $resolvedPath)) { + $target = ($resolvedPath !== false) ? $resolvedPath : $path; + /** @var resource|false $handle */ + $handle = self::silent(fn () => fopen($target, $mode)); + $this->handle = $handle !== false ? $handle : null; + self::register(); - if (self::isReadOnlyCall()) { - return $this->openDirectHandle($normalizedResolved, $mode); + return $this->handle !== null; } - self::unregister(); - $success = self::$cacheEnabled ? $this->openCachedStream($resolvedPath, $mode) : $this->openMemoryStream($resolvedPath); @@ -246,8 +243,8 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ } /** - * Determines if the stream_open call is for reading raw file contents/snippets - * (e.g. error screen renderers) rather than PHP engine execution. + * Very Important: Determines whether the stream is being opened by a native PHP source-viewing function + * (e.g. highlight_file, show_source, file_get_contents, token_get_all) by inspecting shallow backtrace frames. */ private static function isReadOnlyCall(): bool { @@ -260,7 +257,7 @@ private static function isReadOnlyCall(): bool } /** - * Opens a raw file handle directly without stream interception. + * Opens an underlying filesystem handle directly with error handler suppression. */ private function openDirectHandle(string $targetFile, string $mode): bool { @@ -360,7 +357,7 @@ public function stream_stat(): array|false } /** - * Extracts the underlying native file descriptor for C-level functions like proc_open() or stream_select(). + * Extracts the underlying native file descriptor for C-level functions like proc_open or stream_select. * * @return resource|false */ @@ -392,13 +389,10 @@ public function stream_close(): void } /** - * High-speed stat resolution with dual-tier memoization caching: - * - * 1. Positive hit cache ($statCache): Caches stat arrays for existing files and directories. - * 2. Static negative cache ($staticNegativeStatCache): Caches false lookups strictly for static - * read-only paths (e.g. vendor directories), eliminating thousands of duplicate C-level stat calls. - * 3. Dynamic writable bypass: Never caches false for dynamic directories (var/cache, storage), - * ensuring framework cache warmers and runtime directory creation remain fully functional. + * Resolves file status with dual-tier memoization caching: + * 1. Positive hit cache ($statCache): Stores stat arrays for confirmed files. + * 2. Static negative cache ($staticNegativeStatCache): Caches false lookups strictly for static vendor paths. + * 3. Dynamic writable bypass: Bypasses negative caching for dynamic directories (var/cache, storage). * * @return array|false */ @@ -416,18 +410,18 @@ public function url_stat(string $path, int $flags): array|false self::unregister(); /** @var array|false $result */ - $result = self::silent(fn () => stat($path)); + $result = self::silent(fn () => ($flags & STREAM_URL_STAT_LINK) ? @lstat($path) : @stat($path)); self::register(); if ($result !== false) { - self::$statCache[$normalized] = $result; - } else { - if (! PathMatcher::isDynamicWritablePath($normalized)) { - self::$staticNegativeStatCache[$normalized] = true; - } + return self::$statCache[$normalized] = $result; } - return $result; + if (! PathMatcher::isDynamicWritablePath($normalized)) { + self::$staticNegativeStatCache[$normalized] = true; + } + + return false; } public function stream_metadata(string $path, int $option, mixed $value): bool @@ -442,11 +436,11 @@ public function stream_metadata(string $path, int $option, mixed $value): bool $valueArray = \is_array($value) ? $value : []; $time = $valueArray[0] ?? time(); $atime = $valueArray[1] ?? $time; - $result = (bool) self::silent(fn () => touch($path, (int) $time, (int) $atime)); + $result = (bool) self::silent(fn () => @touch($path, (int) $time, (int) $atime)); } elseif ($option === STREAM_META_ACCESS) { /** @var int $mode */ $mode = \is_int($value) ? $value : 0777; - $result = (bool) self::silent(fn () => chmod($path, $mode)); + $result = (bool) self::silent(fn () => @chmod($path, $mode)); } self::register(); @@ -457,7 +451,7 @@ public function dir_opendir(string $path, int $options): bool { self::unregister(); /** @var resource|false $dh */ - $dh = self::silent(fn () => opendir($path)); + $dh = self::silent(fn () => @opendir($path)); $this->dirHandle = $dh !== false ? $dh : null; self::register(); @@ -500,7 +494,7 @@ public function mkdir(string $path, int $mode, int $options): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn () => mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0)); + $result = (bool) self::silent(fn () => @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0)); self::register(); return $result; @@ -512,7 +506,7 @@ public function rmdir(string $path, int $options): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn () => rmdir($path)); + $result = (bool) self::silent(fn () => @rmdir($path)); self::register(); return $result; @@ -524,7 +518,7 @@ public function unlink(string $path): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn () => unlink($path)); + $result = (bool) self::silent(fn () => @unlink($path)); self::register(); return $result; @@ -542,7 +536,7 @@ public function rename(string $pathFrom, string $pathTo): bool ); self::unregister(); - $result = (bool) self::silent(fn () => rename($pathFrom, $pathTo)); + $result = (bool) self::silent(fn () => @rename($pathFrom, $pathTo)); self::register(); return $result; @@ -559,7 +553,7 @@ public function rename(string $pathFrom, string $pathTo): bool */ private static function silent(callable $callback): mixed { - set_error_handler(fn () => true); + set_error_handler(static fn () => true); try { return $callback(); @@ -569,7 +563,7 @@ private static function silent(callable $callback): mixed } /** - * Determines whether a target PHP file path should be intercepted with $O(1)$ caching. + * Determines whether a target PHP file path matches configured inclusion criteria and is not excluded. */ private static function isApplicationFile(string $path, string|false $resolvedPath): bool { @@ -606,6 +600,9 @@ private static function isApplicationFile(string $path, string|false $resolvedPa return self::$appFileDecisionCache[$normalizedPath] = $isIncluded; } + /** + * Transforms and loads source code in-memory via a RAM stream handle. + */ private function openMemoryStream(string $resolvedPath): bool { $source = file_get_contents($resolvedPath); @@ -626,7 +623,7 @@ private function openMemoryStream(string $resolvedPath): bool } /** - * Transforms and caches source code on disk before opening a file handle. + * Transforms, persists, and loads cached source code from disk. */ private function openCachedStream(string $resolvedPath, string $mode): bool { @@ -723,4 +720,4 @@ private static function extractAndSeedFileMetadata(array $stmts, string $filePat SpecialTypeResolver::seedFileMetadata($filePath, $namespace, $imports, $classTraitUseDocs); } -} +} \ No newline at end of file From 38d66391166327b743822ba215c2b615181e36b5 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 26 Aug 2026 20:30:48 +0800 Subject: [PATCH 2/5] Refactor code style for consistency; update lambda function syntax and add missing newlines in various files --- src/Contract/ContractParser.php | 2 +- src/Internal/StreamWrapper.php | 28 +++---- src/Resolver/SpecialTypeResolver.php | 12 +-- src/Resolver/TemplateManager.php | 23 +++++- .../Boundaries/FibersConcurrencyTest.php | 43 +++++++---- .../GenericSubclassCovarianceTest.php | 77 +++++++++++++++++++ 6 files changed, 147 insertions(+), 38 deletions(-) create mode 100644 tests/TypeChecking/Generics/GenericSubclassCovarianceTest.php diff --git a/src/Contract/ContractParser.php b/src/Contract/ContractParser.php index 534fe03f..73194086 100644 --- a/src/Contract/ContractParser.php +++ b/src/Contract/ContractParser.php @@ -951,4 +951,4 @@ public static function substituteAliases(TypeNode $node, array $aliases): TypeNo return $node; } -} \ No newline at end of file +} diff --git a/src/Internal/StreamWrapper.php b/src/Internal/StreamWrapper.php index 474c4276..37ac13d2 100644 --- a/src/Internal/StreamWrapper.php +++ b/src/Internal/StreamWrapper.php @@ -220,13 +220,13 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ self::unregister(); - $exists = (bool) self::silent(fn () => file_exists($path)); - $resolvedPath = $exists ? self::silent(fn () => realpath($path)) : false; + $exists = (bool) self::silent(fn() => file_exists($path)); + $resolvedPath = $exists ? self::silent(fn() => realpath($path)) : false; if (! $exists || $resolvedPath === false || ! self::isApplicationFile($path, $resolvedPath)) { $target = ($resolvedPath !== false) ? $resolvedPath : $path; /** @var resource|false $handle */ - $handle = self::silent(fn () => fopen($target, $mode)); + $handle = self::silent(fn() => fopen($target, $mode)); $this->handle = $handle !== false ? $handle : null; self::register(); @@ -263,7 +263,7 @@ private function openDirectHandle(string $targetFile, string $mode): bool { self::unregister(); /** @var resource|false $handle */ - $handle = self::silent(fn () => fopen($targetFile, $mode)); + $handle = self::silent(fn() => fopen($targetFile, $mode)); $this->handle = $handle !== false ? $handle : null; self::register(); @@ -410,7 +410,7 @@ public function url_stat(string $path, int $flags): array|false self::unregister(); /** @var array|false $result */ - $result = self::silent(fn () => ($flags & STREAM_URL_STAT_LINK) ? @lstat($path) : @stat($path)); + $result = self::silent(fn() => (($flags & STREAM_URL_STAT_LINK) !== 0) ? @lstat($path) : @stat($path)); self::register(); if ($result !== false) { @@ -436,11 +436,11 @@ public function stream_metadata(string $path, int $option, mixed $value): bool $valueArray = \is_array($value) ? $value : []; $time = $valueArray[0] ?? time(); $atime = $valueArray[1] ?? $time; - $result = (bool) self::silent(fn () => @touch($path, (int) $time, (int) $atime)); + $result = (bool) self::silent(fn() => @touch($path, (int) $time, (int) $atime)); } elseif ($option === STREAM_META_ACCESS) { /** @var int $mode */ $mode = \is_int($value) ? $value : 0777; - $result = (bool) self::silent(fn () => @chmod($path, $mode)); + $result = (bool) self::silent(fn() => @chmod($path, $mode)); } self::register(); @@ -451,7 +451,7 @@ public function dir_opendir(string $path, int $options): bool { self::unregister(); /** @var resource|false $dh */ - $dh = self::silent(fn () => @opendir($path)); + $dh = self::silent(fn() => @opendir($path)); $this->dirHandle = $dh !== false ? $dh : null; self::register(); @@ -494,7 +494,7 @@ public function mkdir(string $path, int $mode, int $options): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn () => @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0)); + $result = (bool) self::silent(fn() => @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0)); self::register(); return $result; @@ -506,7 +506,7 @@ public function rmdir(string $path, int $options): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn () => @rmdir($path)); + $result = (bool) self::silent(fn() => @rmdir($path)); self::register(); return $result; @@ -518,7 +518,7 @@ public function unlink(string $path): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn () => @unlink($path)); + $result = (bool) self::silent(fn() => @unlink($path)); self::register(); return $result; @@ -536,7 +536,7 @@ public function rename(string $pathFrom, string $pathTo): bool ); self::unregister(); - $result = (bool) self::silent(fn () => @rename($pathFrom, $pathTo)); + $result = (bool) self::silent(fn() => @rename($pathFrom, $pathTo)); self::register(); return $result; @@ -553,7 +553,7 @@ public function rename(string $pathFrom, string $pathTo): bool */ private static function silent(callable $callback): mixed { - set_error_handler(static fn () => true); + set_error_handler(static fn() => true); try { return $callback(); @@ -720,4 +720,4 @@ private static function extractAndSeedFileMetadata(array $stmts, string $filePat SpecialTypeResolver::seedFileMetadata($filePath, $namespace, $imports, $classTraitUseDocs); } -} \ No newline at end of file +} diff --git a/src/Resolver/SpecialTypeResolver.php b/src/Resolver/SpecialTypeResolver.php index 41dccc7d..817c0f6f 100644 --- a/src/Resolver/SpecialTypeResolver.php +++ b/src/Resolver/SpecialTypeResolver.php @@ -188,7 +188,7 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct if ($node instanceof GenericTypeNode) { $genericType = self::resolve($node->type, $context, $thisObj); - $innerTypes = array_map(fn($t) => self::resolve($t, $context, $thisObj), $node->genericTypes); + $innerTypes = array_map(fn ($t) => self::resolve($t, $context, $thisObj), $node->genericTypes); return new GenericTypeNode( $genericType instanceof IdentifierTypeNode ? $genericType : $node->type, @@ -242,11 +242,11 @@ public static function resolve(TypeNode $node, \ReflectionClass|\ReflectionFunct } if ($node instanceof UnionTypeNode) { - return new UnionTypeNode(array_map(fn($t) => self::resolve($t, $context, $thisObj), $node->types)); + return new UnionTypeNode(array_map(fn ($t) => self::resolve($t, $context, $thisObj), $node->types)); } if ($node instanceof IntersectionTypeNode) { - return new IntersectionTypeNode(array_map(fn($t) => self::resolve($t, $context, $thisObj), $node->types)); + return new IntersectionTypeNode(array_map(fn ($t) => self::resolve($t, $context, $thisObj), $node->types)); } return $node; @@ -280,7 +280,7 @@ public static function resolveForFile(TypeNode $node, string $file): TypeNode if ($node instanceof GenericTypeNode) { $genericType = self::resolveForFile($node->type, $file); - $innerTypes = array_map(fn($t) => self::resolveForFile($t, $file), $node->genericTypes); + $innerTypes = array_map(fn ($t) => self::resolveForFile($t, $file), $node->genericTypes); return new GenericTypeNode( $genericType instanceof IdentifierTypeNode ? $genericType : $node->type, @@ -334,11 +334,11 @@ public static function resolveForFile(TypeNode $node, string $file): TypeNode } if ($node instanceof UnionTypeNode) { - return new UnionTypeNode(array_map(fn($t) => self::resolveForFile($t, $file), $node->types)); + return new UnionTypeNode(array_map(fn ($t) => self::resolveForFile($t, $file), $node->types)); } if ($node instanceof IntersectionTypeNode) { - return new IntersectionTypeNode(array_map(fn($t) => self::resolveForFile($t, $file), $node->types)); + return new IntersectionTypeNode(array_map(fn ($t) => self::resolveForFile($t, $file), $node->types)); } return clone $node; diff --git a/src/Resolver/TemplateManager.php b/src/Resolver/TemplateManager.php index 4a14aea2..8d565c14 100644 --- a/src/Resolver/TemplateManager.php +++ b/src/Resolver/TemplateManager.php @@ -579,6 +579,12 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::checkNestedGenericVariance($existing, $expected); } + if ($existing instanceof IdentifierTypeNode && $expected instanceof GenericTypeNode) { + if ($variance === GenericTypeNode::VARIANCE_COVARIANT && self::isSubclass($existing->name, $expected->type->name)) { + return true; + } + } + if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { return self::isSubclass($existingStr, $expectedStr); } @@ -674,7 +680,7 @@ private static function checkExistingIntersectionVariance(IntersectionTypeNode $ } } - return false; + return true; } if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { @@ -710,8 +716,19 @@ private static function checkNestedGenericVariance(GenericTypeNode $existing, Ge private static function isSubclass(string $sub, string $super): bool { - if (ClassNameValidator::isValid($sub) && ClassNameValidator::isValid($super) && (class_exists($sub) || interface_exists($sub)) && (class_exists($super) || interface_exists($super))) { - return is_a($sub, $super, true); + $baseSub = ($pos = strpos($sub, '<')) !== false ? substr($sub, 0, $pos) : $sub; + $baseSuper = ($pos = strpos($super, '<')) !== false ? substr($super, 0, $pos) : $super; + + $baseSub = ltrim(trim($baseSub), '\\'); + $baseSuper = ltrim(trim($baseSuper), '\\'); + + if ( + ClassNameValidator::isValid($baseSub) + && ClassNameValidator::isValid($baseSuper) + && (class_exists($baseSub) || interface_exists($baseSub) || trait_exists($baseSub) || enum_exists($baseSub)) + && (class_exists($baseSuper) || interface_exists($baseSuper) || trait_exists($baseSuper) || enum_exists($baseSuper)) + ) { + return is_a($baseSub, $baseSuper, true); } return false; diff --git a/tests/TypeChecking/Boundaries/FibersConcurrencyTest.php b/tests/TypeChecking/Boundaries/FibersConcurrencyTest.php index 255fa698..971322fe 100644 --- a/tests/TypeChecking/Boundaries/FibersConcurrencyTest.php +++ b/tests/TypeChecking/Boundaries/FibersConcurrencyTest.php @@ -14,11 +14,12 @@ * * @param positive-int $id * @param non-empty-string $name + * * @return array{id: positive-int, name: non-empty-string} */ function fiberTaskWithContracts(int $id, string $name): array { - $step = Fiber::suspend("paused_at_step_1"); + $step = Fiber::suspend('paused_at_step_1'); return [ 'id' => $id, @@ -34,7 +35,8 @@ function fiberTaskWithContracts(int $id, string $name): array function fiberTaskWithBadReturn(): int { Fiber::suspend(); - return -99; + + return -99; } describe('PHP 8.1+ Fibers & Concurrent Coroutine Execution', function () { @@ -47,7 +49,8 @@ function fiberTaskWithBadReturn(): int $state1 = $fiber->start(42, 'Alice'); expect($state1)->toBe('paused_at_step_1') - ->and($fiber->isSuspended())->toBeTrue(); + ->and($fiber->isSuspended())->toBeTrue() + ; $fiber->resume('step_2'); @@ -55,7 +58,8 @@ function fiberTaskWithBadReturn(): int ->and($fiber->getReturn())->toBe([ 'id' => 42, 'name' => 'Alice_step_2', - ]); + ]) + ; }); test('throws TypeError immediately when starting a fiber with invalid parameters', function () { @@ -64,7 +68,8 @@ function fiberTaskWithBadReturn(): int }); expect(fn () => $fiber->start(-5, 'Alice')) - ->toThrow(TypeError::class, 'positive-int'); + ->toThrow(TypeError::class, 'positive-int') + ; }); test('throws TypeError upon fiber completion when return value violates contract', function () { @@ -76,7 +81,8 @@ function fiberTaskWithBadReturn(): int expect($fiber->isSuspended())->toBeTrue(); expect(fn () => $fiber->resume()) - ->toThrow(TypeError::class, 'Return value must be of type positive-int'); + ->toThrow(TypeError::class, 'Return value must be of type positive-int') + ; }); }); @@ -90,6 +96,7 @@ function fiberTaskWithBadReturn(): int Fiber::suspend($dogs); $dogs->add(new Dog()); + return $dogs; }); @@ -100,6 +107,7 @@ function fiberTaskWithBadReturn(): int Fiber::suspend($cats); $cats->add(new Cat()); + return $cats; }); @@ -109,10 +117,12 @@ function fiberTaskWithBadReturn(): int $catCollection = $fiberCat->start(); expect($dogCollection)->toBeInstanceOf(GenericCollection::class) - ->and(TypePHP::getGenericType($dogCollection))->toBe(Dog::class); + ->and(TypePHP::getGenericType($dogCollection))->toBe(Dog::class) + ; expect($catCollection)->toBeInstanceOf(GenericCollection::class) - ->and(TypePHP::getGenericType($catCollection))->toBe(Cat::class); + ->and(TypePHP::getGenericType($catCollection))->toBe(Cat::class) + ; $fiberDog->resume(); $fiberCat->resume(); @@ -121,13 +131,16 @@ function fiberTaskWithBadReturn(): int $finalCats = $fiberCat->getReturn(); expect($finalDogs->count())->toBe(2) - ->and($finalCats->count())->toBe(2); + ->and($finalCats->count())->toBe(2) + ; expect(fn () => $dogCollection->add(new Cat())) - ->toThrow(TypeError::class, 'must be of type ' . Dog::class); + ->toThrow(TypeError::class, 'must be of type ' . Dog::class) + ; expect(fn () => $catCollection->add(new Dog())) - ->toThrow(TypeError::class, 'must be of type ' . Cat::class); + ->toThrow(TypeError::class, 'must be of type ' . Cat::class) + ; }); }); @@ -156,7 +169,8 @@ function fiberTaskWithBadReturn(): int foreach ($fibers as $id => $fiber) { $status = $fiber->start($id); expect($status)->toBe("fiber_{$id}_paused") - ->and($fiber->isSuspended())->toBeTrue(); + ->and($fiber->isSuspended())->toBeTrue() + ; } foreach ($fibers as $id => $fiber) { @@ -165,7 +179,8 @@ function fiberTaskWithBadReturn(): int expect($fiber->isTerminated())->toBeTrue() ->and($data['user']['id'])->toBe($id) - ->and($data['dog_count'])->toBe(1); + ->and($data['dog_count'])->toBe(1) + ; } }); }); @@ -192,4 +207,4 @@ function fiberTaskWithBadReturn(): int expect($fiber->isTerminated())->toBeTrue(); }); }); -}); \ No newline at end of file +}); diff --git a/tests/TypeChecking/Generics/GenericSubclassCovarianceTest.php b/tests/TypeChecking/Generics/GenericSubclassCovarianceTest.php new file mode 100644 index 00000000..5c64591d --- /dev/null +++ b/tests/TypeChecking/Generics/GenericSubclassCovarianceTest.php @@ -0,0 +1,77 @@ + + */ +class TestSpecificEntityCollection extends TestBaseEntityCollection +{ +} + +class TestUnrelatedCollection +{ +} + +/** + * Covariant Repository (like EntityRepository with @template-covariant TCollection) + * + * @template-covariant TCollection of TestBaseEntityCollection + */ +class TestCovariantEntityRepository +{ + /** + * @param TCollection $collection + */ + public function __construct(public mixed $collection) + { + } +} + +/** + * Function mirroring CustomerLanguageSalesChannelSubscriber constructor + * + * @param TestCovariantEntityRepository> $repo + */ +function consumeCovariantEntityRepository(TestCovariantEntityRepository $repo): bool +{ + return true; +} + +describe('Covariant Generic Subclass Parameter Assignability (Shopware DAL Pattern)', function () { + test('accepts covariant repository holding child collection class without explicit generic args', function () { + $specificCollection = new TestSpecificEntityCollection(); + $repo = new TestCovariantEntityRepository($specificCollection); + + expect(consumeCovariantEntityRepository($repo))->toBeTrue(); + }); + + test('throws TypeError when repository holds an unrelated collection class', function () { + $unrelatedCollection = new TestUnrelatedCollection(); + + expect(fn () => new TestCovariantEntityRepository($unrelatedCollection)) + ->toThrow(TypeError::class, 'must be of type TestBaseEntityCollection') + ; + }); +}); From 8c411bc83637ddea9c4ce4a45f5e6439674d232a Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 26 Aug 2026 21:32:07 +0800 Subject: [PATCH 3/5] Add support for native parameter nullability and confugations support --- src/Command/ConfigInitCommand.php | 13 +++ src/Contract/ContractParser.php | 96 ++++++++++++++++++- src/Internal/Config.php | 15 ++- src/Internal/StreamWrapper.php | 26 ++--- .../Configuration/BoundaryConfigTest.php | 83 ++++++++++++++++ typephp.php | 13 +++ 6 files changed, 230 insertions(+), 16 deletions(-) diff --git a/src/Command/ConfigInitCommand.php b/src/Command/ConfigInitCommand.php index 6a3ff6d7..2a7d5d34 100644 --- a/src/Command/ConfigInitCommand.php +++ b/src/Command/ConfigInitCommand.php @@ -100,6 +100,19 @@ private static function getTemplate(): string */ 'array_validation' => 'full', + /* + |-------------------------------------------------------------------------- + | Respect Native Parameter Nullability + |-------------------------------------------------------------------------- + | When true (default), if a native PHP parameter explicitly declares + | nullable syntax (e.g. ?array $param = null), TypePHP permits null even + | if the DocBlock author omitted "|null" (e.g. @param string[] $param). + | + | Set to false for strict pedantic enforcement where DocBlocks are the + | absolute law and null is rejected unless explicitly typed in the DocBlock. + */ + 'respect_native_nullability' => true, + /* |-------------------------------------------------------------------------- | Enable Caching & Cache Directory diff --git a/src/Contract/ContractParser.php b/src/Contract/ContractParser.php index 73194086..37dcd5e2 100644 --- a/src/Contract/ContractParser.php +++ b/src/Contract/ContractParser.php @@ -489,7 +489,7 @@ private static function parseMethod(\ReflectionMethod $ref): array self::parseMethodHierarchyDocs($ref, $types, $methodTemplates, $returnType, $aliases); if ($ref->getName() === '__construct') { - self::applyConstructorPromotionFallback($ref, $types); + self::applyConstructorPromotionFallback($ref, $types, $classTemplates); } return [ @@ -540,8 +540,10 @@ private static function parseFunction(\ReflectionFunction $ref): array $baseParams = $ref->getParameters(); $baseParamVariadic = []; + $baseParamObjects = []; foreach ($baseParams as $p) { $baseParamVariadic[$p->getName()] = $p->isVariadic(); + $baseParamObjects[$p->getName()] = $p; } foreach (DocblockExtractor::getParamTags($phpDocNode) as $paramName => $paramTag) { @@ -554,6 +556,19 @@ private static function parseFunction(\ReflectionFunction $ref): array ) { $type = new ArrayTypeNode($type); } + + $pObj = $baseParamObjects[$paramName] ?? null; + $isTemplateType = ($type instanceof IdentifierTypeNode && isset($templates[$type->name])); + if ( + Config::isRespectNativeNullabilityEnabled() + && $pObj !== null + && self::parameterExplicitlyAllowsNull($pObj) + && ! $isTemplateType + && ! self::typeContainsNull($type) + ) { + $type = new NullableTypeNode($type); + } + $substitutedType = self::substituteAliases($type, $aliases); $resolvedType = SpecialTypeResolver::resolve($substitutedType, $ref); @@ -650,12 +665,14 @@ private static function parseMethodHierarchyDocs( $baseParamNames = []; $baseParamSet = []; $baseParamVariadic = []; + $baseParamObjects = []; $isConstructor = ($ref->getName() === '__construct'); foreach ($baseParams as $idx => $p) { $baseParamNames[$idx] = $p->getName(); $baseParamSet[$p->getName()] = $idx; $baseParamVariadic[$p->getName()] = $p->isVariadic(); + $baseParamObjects[$p->getName()] = $p; } foreach ($hierarchy as $hierRef) { @@ -710,6 +727,19 @@ private static function parseMethodHierarchyDocs( ) { $type = new ArrayTypeNode($type); } + + $pObj = $baseParamObjects[$targetParamName] ?? null; + $isTemplateType = ($type instanceof IdentifierTypeNode && isset($templates[$type->name])); + if ( + Config::isRespectNativeNullabilityEnabled() + && $pObj !== null + && self::parameterExplicitlyAllowsNull($pObj) + && ! $isTemplateType + && ! self::typeContainsNull($type) + ) { + $type = new NullableTypeNode($type); + } + $substitutedType = self::substituteAliases($type, $aliases); $resolvedType = SpecialTypeResolver::resolve($substitutedType, $hierRef); @@ -769,8 +799,9 @@ private static function resolveTargetParamName( * * @param \ReflectionMethod $ref * @param array $types + * @param array $classTemplates */ - private static function applyConstructorPromotionFallback(\ReflectionMethod $ref, array &$types): void + private static function applyConstructorPromotionFallback(\ReflectionMethod $ref, array &$types, array $classTemplates = []): void { $declaringClass = $ref->getDeclaringClass(); @@ -811,6 +842,17 @@ private static function applyConstructorPromotionFallback(\ReflectionMethod $ref ) { $propType = new ArrayTypeNode($propType); } + + $isTemplateType = ($propType instanceof IdentifierTypeNode && isset($classTemplates[$propType->name])); + if ( + Config::isRespectNativeNullabilityEnabled() + && self::parameterExplicitlyAllowsNull($p) + && ! $isTemplateType + && ! self::typeContainsNull($propType) + ) { + $propType = new NullableTypeNode($propType); + } + $substitutedProp = self::substituteAliases($propType, []); $resolvedProp = SpecialTypeResolver::resolve($substitutedProp, $ref); @@ -825,6 +867,56 @@ private static function applyConstructorPromotionFallback(\ReflectionMethod $ref } } + /** + * Checks if a reflection parameter explicitly declares a nullable native typehint or default null value (excluding mixed). + */ + private static function parameterExplicitlyAllowsNull(\ReflectionParameter $p): bool + { + if (! $p->hasType()) { + return $p->isDefaultValueAvailable() && $p->getDefaultValue() === null; + } + + $type = $p->getType(); + if ($type instanceof \ReflectionNamedType) { + $name = strtolower($type->getName()); + if ($name === 'mixed') { + return false; + } + + return $type->allowsNull(); + } + + if ($type instanceof \ReflectionUnionType) { + return $type->allowsNull(); + } + + return false; + } + + /** + * Checks if a TypeNode already represents or contains null. + */ + private static function typeContainsNull(TypeNode $node): bool + { + if ($node instanceof NullableTypeNode) { + return true; + } + + if ($node instanceof IdentifierTypeNode && (\in_array(strtolower($node->name), ['null', 'mixed'], true))) { + return true; + } + + if ($node instanceof UnionTypeNode) { + foreach ($node->types as $t) { + if (self::typeContainsNull($t)) { + return true; + } + } + } + + return false; + } + /** * Recursively substitutes all type aliases inside a TypeNode AST and simplifies unions/intersections containing `mixed`. * diff --git a/src/Internal/Config.php b/src/Internal/Config.php index e04bbcb0..5bfe0e05 100644 --- a/src/Internal/Config.php +++ b/src/Internal/Config.php @@ -43,6 +43,8 @@ final class Config private static bool $respectIgnoreTags = true; + private static bool $respectNativeNullability = true; + private static string $arrayValidation = 'full'; public static function isEnabled(): bool @@ -99,6 +101,15 @@ public static function isRespectIgnoreTagsEnabled(): bool return self::$respectIgnoreTags; } + public static function isRespectNativeNullabilityEnabled(): bool + { + if (self::$cachedConfig === null) { + self::get(); + } + + return self::$respectNativeNullability; + } + public static function isArrayValidationHybrid(): bool { if (self::$cachedConfig === null) { @@ -177,6 +188,7 @@ public static function get(): array 'magic_properties' => true, 'magic_methods' => true, 'respect_ignore_tags' => true, + 'respect_native_nullability' => true, 'array_validation' => 'full', 'cache' => true, 'cache_dir' => null, @@ -216,7 +228,6 @@ public static function get(): array $mergedConfig = self::mergeConfig($defaultConfig, $userConfig); - // Append extension whitelist includes and stubs /** @var array $currentIncludes */ $currentIncludes = \is_array($mergedConfig['include'] ?? null) ? $mergedConfig['include'] : []; /** @var array $currentStubs */ @@ -314,6 +325,7 @@ public static function reset(): void self::$magicProperties = true; self::$magicMethods = true; self::$respectIgnoreTags = true; + self::$respectNativeNullability = true; self::$arrayValidation = 'full'; ContractParser::reset(); @@ -342,6 +354,7 @@ private static function syncFlags(array $config): void self::$magicProperties = (bool) ($config['magic_properties'] ?? true); self::$magicMethods = (bool) ($config['magic_methods'] ?? true); self::$respectIgnoreTags = (bool) ($config['respect_ignore_tags'] ?? true); + self::$respectNativeNullability = (bool) ($config['respect_native_nullability'] ?? true); self::$arrayValidation = \is_string($config['array_validation'] ?? null) ? $config['array_validation'] : 'full'; } } diff --git a/src/Internal/StreamWrapper.php b/src/Internal/StreamWrapper.php index 37ac13d2..5736ac0c 100644 --- a/src/Internal/StreamWrapper.php +++ b/src/Internal/StreamWrapper.php @@ -220,13 +220,13 @@ public function stream_open(string $path, string $mode, int $options, ?string &$ self::unregister(); - $exists = (bool) self::silent(fn() => file_exists($path)); - $resolvedPath = $exists ? self::silent(fn() => realpath($path)) : false; + $exists = (bool) self::silent(fn () => file_exists($path)); + $resolvedPath = $exists ? self::silent(fn () => realpath($path)) : false; if (! $exists || $resolvedPath === false || ! self::isApplicationFile($path, $resolvedPath)) { $target = ($resolvedPath !== false) ? $resolvedPath : $path; /** @var resource|false $handle */ - $handle = self::silent(fn() => fopen($target, $mode)); + $handle = self::silent(fn () => fopen($target, $mode)); $this->handle = $handle !== false ? $handle : null; self::register(); @@ -263,7 +263,7 @@ private function openDirectHandle(string $targetFile, string $mode): bool { self::unregister(); /** @var resource|false $handle */ - $handle = self::silent(fn() => fopen($targetFile, $mode)); + $handle = self::silent(fn () => fopen($targetFile, $mode)); $this->handle = $handle !== false ? $handle : null; self::register(); @@ -410,7 +410,7 @@ public function url_stat(string $path, int $flags): array|false self::unregister(); /** @var array|false $result */ - $result = self::silent(fn() => (($flags & STREAM_URL_STAT_LINK) !== 0) ? @lstat($path) : @stat($path)); + $result = self::silent(fn () => (($flags & STREAM_URL_STAT_LINK) !== 0) ? @lstat($path) : @stat($path)); self::register(); if ($result !== false) { @@ -436,11 +436,11 @@ public function stream_metadata(string $path, int $option, mixed $value): bool $valueArray = \is_array($value) ? $value : []; $time = $valueArray[0] ?? time(); $atime = $valueArray[1] ?? $time; - $result = (bool) self::silent(fn() => @touch($path, (int) $time, (int) $atime)); + $result = (bool) self::silent(fn () => @touch($path, (int) $time, (int) $atime)); } elseif ($option === STREAM_META_ACCESS) { /** @var int $mode */ $mode = \is_int($value) ? $value : 0777; - $result = (bool) self::silent(fn() => @chmod($path, $mode)); + $result = (bool) self::silent(fn () => @chmod($path, $mode)); } self::register(); @@ -451,7 +451,7 @@ public function dir_opendir(string $path, int $options): bool { self::unregister(); /** @var resource|false $dh */ - $dh = self::silent(fn() => @opendir($path)); + $dh = self::silent(fn () => @opendir($path)); $this->dirHandle = $dh !== false ? $dh : null; self::register(); @@ -494,7 +494,7 @@ public function mkdir(string $path, int $mode, int $options): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn() => @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0)); + $result = (bool) self::silent(fn () => @mkdir($path, $mode, ($options & STREAM_MKDIR_RECURSIVE) !== 0)); self::register(); return $result; @@ -506,7 +506,7 @@ public function rmdir(string $path, int $options): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn() => @rmdir($path)); + $result = (bool) self::silent(fn () => @rmdir($path)); self::register(); return $result; @@ -518,7 +518,7 @@ public function unlink(string $path): bool unset(self::$statCache[$normalized], self::$staticNegativeStatCache[$normalized]); self::unregister(); - $result = (bool) self::silent(fn() => @unlink($path)); + $result = (bool) self::silent(fn () => @unlink($path)); self::register(); return $result; @@ -536,7 +536,7 @@ public function rename(string $pathFrom, string $pathTo): bool ); self::unregister(); - $result = (bool) self::silent(fn() => @rename($pathFrom, $pathTo)); + $result = (bool) self::silent(fn () => @rename($pathFrom, $pathTo)); self::register(); return $result; @@ -553,7 +553,7 @@ public function rename(string $pathFrom, string $pathTo): bool */ private static function silent(callable $callback): mixed { - set_error_handler(static fn() => true); + set_error_handler(static fn () => true); try { return $callback(); diff --git a/tests/TypeChecking/Configuration/BoundaryConfigTest.php b/tests/TypeChecking/Configuration/BoundaryConfigTest.php index e582df26..6bf7c6b0 100644 --- a/tests/TypeChecking/Configuration/BoundaryConfigTest.php +++ b/tests/TypeChecking/Configuration/BoundaryConfigTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use TypePHP\Exception\TypeError; use TypePHP\Internal\Config; use TypePHP\Tests\Fixtures\Domain\Car; use TypePHP\Tests\Fixtures\Domain\Dog; @@ -27,6 +28,27 @@ function testReturnOnlyFunction(int $id): int return $id; } +/** + * Function with native nullable parameter (?array) but non-nullable docblock + * + * @param string[] $tags + */ +function testNativeNullableWithNonNullableDocblock(?array $tags = null): ?array +{ + return $tags; +} + +/** + * Function with PHP 8.0+ native union parameters (int|null, array|null) but non-nullable docblocks + * + * @param positive-int $id + * @param string[] $tags + */ +function testNativeUnionWithNull(int|null $id = null, array|null $tags = null): array +{ + return [$id, $tags]; +} + describe('Function Boundary Config Toggles (params & returns)', function () { afterEach(function () { Config::reset(); @@ -59,3 +81,64 @@ function testReturnOnlyFunction(int $id): int expect($dogs->count())->toBe(1); }); }); + +describe('Respect Native Nullability Configuration (respect_native_nullability)', function () { + afterEach(function () { + Config::reset(); + }); + + describe('PHP 7.1+ Nullable Syntax (?Type $param = null)', function () { + test('accepts null when respect_native_nullability is true (default)', function () { + Config::set(['respect_native_nullability' => true]); + + expect(testNativeNullableWithNonNullableDocblock(null))->toBeNull(); + expect(testNativeNullableWithNonNullableDocblock(['tag1', 'tag2']))->toBe(['tag1', 'tag2']); + + expect(fn () => testNativeNullableWithNonNullableDocblock([123])) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + + test('rejects null when respect_native_nullability is false (strict pedantic mode)', function () { + Config::set(['respect_native_nullability' => false]); + + expect(fn () => testNativeNullableWithNonNullableDocblock(null)) + ->toThrow(TypeError::class, 'must be of type array, null given') + ; + + expect(testNativeNullableWithNonNullableDocblock(['tag1']))->toBe(['tag1']); + }); + }); + + describe('PHP 8.0+ Native Union Syntax (Type|null $param = null)', function () { + test('accepts null on PHP 8 native unions when respect_native_nullability is true (default)', function () { + Config::set(['respect_native_nullability' => true]); + + expect(testNativeUnionWithNull())->toBe([null, null]); + expect(testNativeUnionWithNull(null, null))->toBe([null, null]); + expect(testNativeUnionWithNull(42, ['php', 'typephp']))->toBe([42, ['php', 'typephp']]); + + expect(fn () => testNativeUnionWithNull(-10, ['php'])) + ->toThrow(TypeError::class, 'must be of type positive-int') + ; + + expect(fn () => testNativeUnionWithNull(42, [999])) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + + test('rejects null on PHP 8 native unions when respect_native_nullability is false (strict pedantic mode)', function () { + Config::set(['respect_native_nullability' => false]); + + expect(fn () => testNativeUnionWithNull(null, ['tag1'])) + ->toThrow(TypeError::class, 'must be of type positive-int, null given') + ; + + expect(fn () => testNativeUnionWithNull(42, null)) + ->toThrow(TypeError::class, 'must be of type array, null given') + ; + + expect(testNativeUnionWithNull(42, ['tag1']))->toBe([42, ['tag1']]); + }); + }); +}); \ No newline at end of file diff --git a/typephp.php b/typephp.php index a6518e01..24350188 100644 --- a/typephp.php +++ b/typephp.php @@ -82,6 +82,19 @@ */ 'array_validation' => 'hybrid', + /* + |-------------------------------------------------------------------------- + | Respect Native Parameter Nullability + |-------------------------------------------------------------------------- + | When true (default), if a native PHP parameter explicitly declares + | nullable syntax (e.g. ?array $param = null), TypePHP permits null even + | if the DocBlock author omitted "|null" (e.g. @param string[] $param). + | + | Set to false for strict pedantic enforcement where DocBlocks are the + | absolute law and null is rejected unless explicitly typed in the DocBlock. + */ + 'respect_native_nullability' => true, + /* |-------------------------------------------------------------------------- | Inline Variable Validation (@var $x = ...) From b1699b19592ef122e2b9760b0ccc3ee39b5162fa Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Wed, 26 Aug 2026 21:51:01 +0800 Subject: [PATCH 4/5] Enhance TemplateSubstitutor with visited tracking for recursive substitutions; add ChainedTemplateBoundsTest for generic collection behavior validation --- src/Resolver/TemplateSubstitutor.php | 102 ++++++++++++------ .../Configuration/BoundaryConfigTest.php | 2 +- .../Generics/ChainedTemplateBoundsTest.php | 101 +++++++++++++++++ 3 files changed, 170 insertions(+), 35 deletions(-) create mode 100644 tests/TypeChecking/Generics/ChainedTemplateBoundsTest.php diff --git a/src/Resolver/TemplateSubstitutor.php b/src/Resolver/TemplateSubstitutor.php index 906cddb5..05dd3b2d 100644 --- a/src/Resolver/TemplateSubstitutor.php +++ b/src/Resolver/TemplateSubstitutor.php @@ -36,54 +36,68 @@ public static function substitute(TypeNode $node, array $boundTemplates, array $ return $node; } + return self::substituteNode($node, $boundTemplates, $declaredTemplates, []); + } + + /** + * @param array $boundTemplates + * @param array $declaredTemplates + * @param array $visited + */ + private static function substituteNode( + TypeNode $node, + array $boundTemplates, + array $declaredTemplates, + array $visited + ): TypeNode { if ($node instanceof IdentifierTypeNode) { - return self::substituteIdentifier($node, $boundTemplates, $declaredTemplates); + return self::substituteIdentifier($node, $boundTemplates, $declaredTemplates, $visited); } if ($node instanceof CallableTypeNode) { - return self::substituteCallable($node, $boundTemplates, $declaredTemplates); + return self::substituteCallable($node, $boundTemplates, $declaredTemplates, $visited); } if ($node instanceof ConditionalTypeNode) { - return self::substituteConditional($node, $boundTemplates, $declaredTemplates); + return self::substituteConditional($node, $boundTemplates, $declaredTemplates, $visited); } if ($node instanceof ConditionalTypeForParameterNode) { - return self::substituteParameterConditional($node, $boundTemplates, $declaredTemplates); + return self::substituteParameterConditional($node, $boundTemplates, $declaredTemplates, $visited); } if ($node instanceof ArrayTypeNode) { - return new ArrayTypeNode(self::substitute($node->type, $boundTemplates, $declaredTemplates)); + return new ArrayTypeNode(self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited)); } if ($node instanceof GenericTypeNode) { - return self::substituteGeneric($node, $boundTemplates, $declaredTemplates); + return self::substituteGeneric($node, $boundTemplates, $declaredTemplates, $visited); } if ($node instanceof NullableTypeNode) { - return new NullableTypeNode(self::substitute($node->type, $boundTemplates, $declaredTemplates)); + return new NullableTypeNode(self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited)); } if ($node instanceof UnionTypeNode) { return new UnionTypeNode(array_map( - fn ($t) => self::substitute($t, $boundTemplates, $declaredTemplates), + fn ($t) => self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited), $node->types )); } if ($node instanceof IntersectionTypeNode) { return new IntersectionTypeNode(array_map( - fn ($t) => self::substitute($t, $boundTemplates, $declaredTemplates), + fn ($t) => self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited), $node->types )); } if ($node instanceof ArrayShapeNode) { - return self::substituteArrayShape($node, $boundTemplates, $declaredTemplates); + return self::substituteArrayShape($node, $boundTemplates, $declaredTemplates, $visited); } if ($node instanceof ObjectShapeNode) { - return self::substituteObjectShape($node, $boundTemplates, $declaredTemplates); + return self::substituteObjectShape($node, $boundTemplates, $declaredTemplates, $visited); } return $node; @@ -92,20 +106,28 @@ public static function substitute(TypeNode $node, array $boundTemplates, array $ /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteIdentifier( IdentifierTypeNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): TypeNode { if (isset($boundTemplates[$node->name])) { return $boundTemplates[$node->name]; } if (isset($declaredTemplates[$node->name])) { + if (isset($visited[$node->name])) { + return new IdentifierTypeNode('mixed'); + } + $visited[$node->name] = true; + $templateTag = $declaredTemplates[$node->name]; + $fallback = $templateTag->default ?? $templateTag->bound ?? new IdentifierTypeNode('mixed'); - return $templateTag->default ?? $templateTag->bound ?? new IdentifierTypeNode('mixed'); + return self::substituteNode($fallback, $boundTemplates, $declaredTemplates, $visited); } return $node; @@ -114,15 +136,17 @@ private static function substituteIdentifier( /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteCallable( CallableTypeNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): CallableTypeNode { $parameters = array_map( fn (CallableTypeParameterNode $param) => new CallableTypeParameterNode( - self::substitute($param->type, $boundTemplates, $declaredTemplates), + self::substituteNode($param->type, $boundTemplates, $declaredTemplates, $visited), $param->isReference, $param->isVariadic, $param->parameterName, @@ -131,7 +155,7 @@ private static function substituteCallable( $node->parameters ); - $returnType = self::substitute($node->returnType, $boundTemplates, $declaredTemplates); + $returnType = self::substituteNode($node->returnType, $boundTemplates, $declaredTemplates, $visited); return new CallableTypeNode( $node->identifier, @@ -144,17 +168,19 @@ private static function substituteCallable( /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteConditional( ConditionalTypeNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): ConditionalTypeNode { return new ConditionalTypeNode( - self::substitute($node->subjectType, $boundTemplates, $declaredTemplates), - self::substitute($node->targetType, $boundTemplates, $declaredTemplates), - self::substitute($node->if, $boundTemplates, $declaredTemplates), - self::substitute($node->else, $boundTemplates, $declaredTemplates), + self::substituteNode($node->subjectType, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->targetType, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->if, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->else, $boundTemplates, $declaredTemplates, $visited), $node->negated ); } @@ -162,17 +188,19 @@ private static function substituteConditional( /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteParameterConditional( ConditionalTypeForParameterNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): ConditionalTypeForParameterNode { return new ConditionalTypeForParameterNode( $node->parameterName, - self::substitute($node->targetType, $boundTemplates, $declaredTemplates), - self::substitute($node->if, $boundTemplates, $declaredTemplates), - self::substitute($node->else, $boundTemplates, $declaredTemplates), + self::substituteNode($node->targetType, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->if, $boundTemplates, $declaredTemplates, $visited), + self::substituteNode($node->else, $boundTemplates, $declaredTemplates, $visited), $node->negated ); } @@ -180,15 +208,17 @@ private static function substituteParameterConditional( /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteGeneric( GenericTypeNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): GenericTypeNode { - $type = self::substitute($node->type, $boundTemplates, $declaredTemplates); + $type = self::substituteNode($node->type, $boundTemplates, $declaredTemplates, $visited); $genericTypes = array_map( - fn ($t) => self::substitute($t, $boundTemplates, $declaredTemplates), + fn ($t) => self::substituteNode($t, $boundTemplates, $declaredTemplates, $visited), $node->genericTypes ); @@ -202,21 +232,23 @@ private static function substituteGeneric( /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteArrayShape( ArrayShapeNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): ArrayShapeNode { foreach ($node->items as $item) { - $item->valueType = self::substitute($item->valueType, $boundTemplates, $declaredTemplates); + $item->valueType = self::substituteNode($item->valueType, $boundTemplates, $declaredTemplates, $visited); } if ($node->unsealedType !== null) { if ($node->unsealedType->keyType !== null) { - $node->unsealedType->keyType = self::substitute($node->unsealedType->keyType, $boundTemplates, $declaredTemplates); + $node->unsealedType->keyType = self::substituteNode($node->unsealedType->keyType, $boundTemplates, $declaredTemplates, $visited); } - $node->unsealedType->valueType = self::substitute($node->unsealedType->valueType, $boundTemplates, $declaredTemplates); + $node->unsealedType->valueType = self::substituteNode($node->unsealedType->valueType, $boundTemplates, $declaredTemplates, $visited); } return $node; @@ -225,14 +257,16 @@ private static function substituteArrayShape( /** * @param array $boundTemplates * @param array $declaredTemplates + * @param array $visited */ private static function substituteObjectShape( ObjectShapeNode $node, array $boundTemplates, - array $declaredTemplates + array $declaredTemplates, + array $visited ): ObjectShapeNode { foreach ($node->items as $item) { - $item->valueType = self::substitute($item->valueType, $boundTemplates, $declaredTemplates); + $item->valueType = self::substituteNode($item->valueType, $boundTemplates, $declaredTemplates, $visited); } return $node; diff --git a/tests/TypeChecking/Configuration/BoundaryConfigTest.php b/tests/TypeChecking/Configuration/BoundaryConfigTest.php index 6bf7c6b0..1ba4a748 100644 --- a/tests/TypeChecking/Configuration/BoundaryConfigTest.php +++ b/tests/TypeChecking/Configuration/BoundaryConfigTest.php @@ -141,4 +141,4 @@ function testNativeUnionWithNull(int|null $id = null, array|null $tags = null): expect(testNativeUnionWithNull(42, ['tag1']))->toBe([42, ['tag1']]); }); }); -}); \ No newline at end of file +}); diff --git a/tests/TypeChecking/Generics/ChainedTemplateBoundsTest.php b/tests/TypeChecking/Generics/ChainedTemplateBoundsTest.php new file mode 100644 index 00000000..05ed3c46 --- /dev/null +++ b/tests/TypeChecking/Generics/ChainedTemplateBoundsTest.php @@ -0,0 +1,101 @@ + + */ + public array $elements = []; + + public function add(mixed $element): void + { + $this->elements[] = $element; + } + + /** + * Method template T bounded by class template TElement (like Collection::firstWhere) + * + * @template T of TElement + * + * @param Closure(T): bool $closure + * + * @return TElement|null + */ + public function firstWhere(Closure $closure): mixed + { + foreach ($this->elements as $element) { + if ($closure($element)) { + return $element; + } + } + + return null; + } +} + +/** + * Concrete collection binding TElement to ChainedField + * + * @extends ChainedBaseCollection + */ +class ChainedFieldCollection extends ChainedBaseCollection +{ +} + +/** + * Unparameterized collection where TElement is unbound (mixed) + */ +class ChainedUnparameterizedCollection extends ChainedBaseCollection +{ +} + +describe('Chained Template Bounds (@template T of TElement in Closures)', function () { + test('resolves chained method template T bounded by class template TElement in closure parameter', function () { + $fields = new ChainedFieldCollection(); + $assocField = new ChainedAssociationField('customer'); + $fields->add($assocField); + + $result = $fields->firstWhere(function (ChainedField $field): bool { + return $field->name === 'customer'; + }); + + expect($result)->toBe($assocField); + }); + + test('falls back chained template T to mixed when class template TElement is unbound', function () { + $collection = new ChainedUnparameterizedCollection(); + $collection->add(new ChainedCar()); + + $result = $collection->firstWhere(function ($item): bool { + return true; + }); + + expect($result)->toBeInstanceOf(ChainedCar::class); + }); +}); From c732c0b99673838a471281912c8c3652b13b95a5 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Thu, 27 Aug 2026 13:52:33 +0800 Subject: [PATCH 5/5] Update README.md with installation instructions and quick start guide; refine type-checking documentation --- README.md | 90 ++++++++++++++++++++++++++++- tests/Wrapper/IteratorProxyTest.php | 3 +- 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0aa3f279..6f397c53 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,87 @@ TypePHP is a transparent, pure-PHP runtime type checker. You don't have to refac **[Read the full TypePHP documentation »](https://typephp-php.github.io/docs/)** -**[Quick Start Guide »](https://typephp-php.github.io/docs/getting-started/quick-start)** +--- + +## Installation + +Install TypePHP as a development dependency via Composer: + +```bash +composer require typephp/typephp --dev +``` + +*Note: TypePHP boots automatically via Composer's autoloader. No service providers, bootstrap edits, or framework configurations are required.* + +--- + +## Quick Start + +### 1. Initialize Configuration (Optional) + +Generate a default `typephp.php` configuration file in your project root: + +```bash +vendor/bin/typephp config:init +``` + +### 2. Write Standard DocBlocks + +Annotate your functions, methods, and classes with standard static analysis DocBlocks: + +```php +namespace App\Services; + +class PaymentService +{ + /** + * @param positive-int $amount + * @param array{gateway: 'stripe'|'paypal', currency: non-empty-string} $options + * @return non-empty-string + */ + public function charge(int $amount, array $options): string + { + return "Transaction successful"; + } +} +``` + +### 3. Run Your Application or Tests + +If your application runs through an entry point where `require 'vendor/autoload.php'` is declared (such as a web framework's `public/index.php`, CLI commands, or test runners like **Pest** and **PHPUnit**), **TypePHP runs automatically and transparently in the background**. + +Simply run your tests or use your local development server (**Laravel**, **Symfony**, **FrankenPHP**, **PHP-FPM**). TypePHP immediately intercepts and enforces all parameter, return, shape, and generic contracts in real time. + +--- + +## Executing Standalone Scripts (CLI Runner) + +For standalone, single-execution PHP scripts that do not have an explicit autoloader entry point, run them directly with the TypePHP CLI binary: + +```bash +vendor/bin/typephp script.php +``` + +--- + +## Type-Checking Files Anywhere (`"*"` Wildcard Glob) + +By default, TypePHP checks standard application folders (`src/**`, `app/**`, `tests/**`). To type-check PHP files anywhere in your project root while still respecting your excluded folders, set the `"*"` wildcard glob in `typephp.php`: + +```php +// typephp.php +return [ + 'include' => [ + '*', // Intercepts and type-checks PHP files anywhere in the project + ], + 'exclude' => [ + 'vendor/**', + 'storage/**', + 'var/**', + 'cache/**', + ], +]; +``` --- @@ -150,18 +230,26 @@ All the documentation lives on the **[typephp-php.github.io/docs website](https: * [Official Blog & Announcements](https://typephp-php.github.io/docs/blog/) * [Troubleshooting & FAQ](https://typephp-php.github.io/docs/troubleshooting) +--- + ## Inspiration TypePHP is conceptually inspired by Python's [Beartype](https://github.com/beartype/beartype), bringing transparent runtime type enforcement for type annotations to the PHP ecosystem without any decorators or attributes. +--- + ## Sponsors Want to support the open-source development and maintenance of TypePHP? [Sponsor me on GitHub »](https://github.com/sponsors/rcalicdan) +--- + ## Contributing Any contributions are welcome. Feel free to open issues or submit pull requests on GitHub. +--- + ## License TypePHP is open-source software licensed under the [MIT License](https://choosealicense.com/licenses/mit/). diff --git a/tests/Wrapper/IteratorProxyTest.php b/tests/Wrapper/IteratorProxyTest.php index 7a296a60..f6ab869f 100644 --- a/tests/Wrapper/IteratorProxyTest.php +++ b/tests/Wrapper/IteratorProxyTest.php @@ -52,8 +52,7 @@ test('forwards custom method calls to inner iterator via __call', function () { $inner = new ArrayIterator(['a' => 10]); $proxy = new IteratorProxy($inner, fn () => null); - - // ArrayIterator has offsetExists + expect($proxy->offsetExists('a'))->toBeTrue() ->and($proxy->offsetExists('z'))->toBeFalse() ;