From 76817fc35792a5f2bfdd280d00829d611b5292df Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 28 Nov 2026 13:41:04 +0800 Subject: [PATCH 1/2] Enhance CallerBoundaryResolver with vendor file checks and improve error handling in ErrorFactory; update version in CacheManager; add tests for call-site attribution integrity and vendor method/property access. --- src/Internal/Ast/FunctionContractInjector.php | 19 +- src/Internal/Diagnostic/ErrorFactory.php | 13 +- src/Internal/Io/CacheManager.php | 2 +- .../Resolver/CallerBoundaryResolver.php | 31 ++- src/Internal/RuntimeTypeChecker.php | 38 +++- src/Internal/Util/Config.php | 2 + .../Internal/Diagnostic/ErrorFactoryTest.php | 187 ++++++++++++++++++ .../CallerBoundaryResolverInheritanceTest.php | 183 +++++++++++++++++ 8 files changed, 456 insertions(+), 19 deletions(-) create mode 100644 tests/Internal/Resolver/CallerBoundaryResolverInheritanceTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index ae33abe4..54ec35fb 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -283,7 +283,8 @@ public static function inject( $useDynamicMethodKey, ! $isMagicGet && ! $isMagicCall, $currentNamespace, - $effectiveAliases + $effectiveAliases, + $isMagicGet ); } @@ -2096,7 +2097,8 @@ private static function wrapNonGeneratorReturns( bool $useDynamicMethodKey = false, bool $canGuardReturnCache = true, ?string $currentNamespace = null, - array $effectiveAliases = [] + array $effectiveAliases = [], + bool $isMagicGet = false ): array { self::tagPrecedingAssignments($stmts); @@ -2117,7 +2119,8 @@ private static function wrapNonGeneratorReturns( $useDynamicMethodKey, $canGuardReturnCache, $currentNamespace, - $effectiveAliases + $effectiveAliases, + $isMagicGet ) extends NodeVisitorAbstract { /** * @param array $byRefParams @@ -2141,7 +2144,8 @@ public function __construct( private bool $useDynamicMethodKey, private bool $canGuardReturnCache, private ?string $currentNamespace, - private array $effectiveAliases + private array $effectiveAliases, + private bool $isMagicGet ) { } @@ -2241,7 +2245,10 @@ public function enterNode(Node $n): int|array|null ); } else { $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); - $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine()); + $n->expr = FunctionContractInjector::buildTernaryReturnExpr( + $checkCall, + $this->isMagicGet ? null : $n->getStartLine() + ); } return $exitStmts !== [] ? [...$exitStmts, $n] : null; @@ -2285,7 +2292,7 @@ public function enterNode(Node $n): int|array|null $byRefGuardStmts = self::buildByRefReturnGuard($checkCall, $retStmt, $fallbackLine); $newStmts = [...$newStmts, ...$exitStmts, ...$byRefGuardStmts]; } else { - $fallbackLine = $lastStmt instanceof Node\Stmt ? $lastStmt->getStartLine() : null; + $fallbackLine = (! $isMagicGet && $lastStmt instanceof Node\Stmt) ? $lastStmt->getStartLine() : null; $ternaryExpr = $canGuardReturnCache ? self::buildGuardedTernaryReturnExpr( new Node\Expr\ConstFetch(new Node\Name('null')), diff --git a/src/Internal/Diagnostic/ErrorFactory.php b/src/Internal/Diagnostic/ErrorFactory.php index 7694058d..dffded9f 100644 --- a/src/Internal/Diagnostic/ErrorFactory.php +++ b/src/Internal/Diagnostic/ErrorFactory.php @@ -111,11 +111,16 @@ private static function filterTrace( $filtered[] = $frame; - if ($isCallSite && $targetFile === null && isset($frame['file'], $frame['line']) && \is_string($frame['file']) && \is_int($frame['line'])) { + if ( + $isCallSite + && $targetFile === null + && $targetLine === null + && isset($frame['file'], $frame['line']) + && \is_string($frame['file']) + && \is_int($frame['line']) + ) { $targetFile = $frame['file']; - if ($targetLine === null) { - $targetLine = $frame['line']; - } + $targetLine = $frame['line']; } } diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index 369fc401..023e754b 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -16,7 +16,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.14.2_'; + public const VERSION_PREFIX = 'v0.14.4_'; /** * Config keys that only steer runtime behaviour and never change the transformed source. diff --git a/src/Internal/Resolver/CallerBoundaryResolver.php b/src/Internal/Resolver/CallerBoundaryResolver.php index f6e1d5e0..a721cdb1 100644 --- a/src/Internal/Resolver/CallerBoundaryResolver.php +++ b/src/Internal/Resolver/CallerBoundaryResolver.php @@ -34,11 +34,29 @@ final class CallerBoundaryResolver */ public static array $nonBypassCalleeCache = []; + /** + * @var array rawFilePath => isVendorFile + */ + private static array $vendorFileCache = []; + public static function reset(): void { self::$calleeVendorCache = []; self::$callerVendorCache = []; self::$nonBypassCalleeCache = []; + self::$vendorFileCache = []; + } + + /** + * Checks if a source file path is located inside a vendor directory (memoized). + */ + public static function isVendorFile(string $file): bool + { + if ($file === '') { + return false; + } + + return self::$vendorFileCache[$file] ??= PathMatcher::isVendorPath(PathMatcher::normalizePath($file)); } /** @@ -98,11 +116,20 @@ public static function isCalleeVendor(string $function): bool try { if (str_contains($function, '::')) { - [$class] = explode('::', $function, 2); + [$class, $member] = explode('::', $function, 2); if (class_exists($class) || interface_exists($class) || trait_exists($class)) { /** @var class-string $class */ $ref = new ReflectionClass($class); - $fileName = $ref->getFileName(); + if (str_starts_with($member, '$')) { + $propName = substr($member, 1); + $fileName = $ref->hasProperty($propName) + ? $ref->getProperty($propName)->getDeclaringClass()->getFileName() + : $ref->getFileName(); + } elseif ($member !== '' && $ref->hasMethod($member)) { + $fileName = $ref->getMethod($member)->getFileName(); + } else { + $fileName = $ref->getFileName(); + } } } elseif (\function_exists($function)) { $ref = new ReflectionFunction($function); diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 3cb5adc1..895681db 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -180,6 +180,8 @@ final class RuntimeTypeChecker public static bool $inlinePropertiesEnabled = true; + public static bool $vendorBoundaryOnly = true; + public static bool $arrayValidationHybrid = false; private static ?TypeValidatorRegistry $registry = null; @@ -600,7 +602,11 @@ public static function checkPropertyMemberAssign( if ($res instanceof ErrorMessage) { $className = \is_object($objectOrClass) ? $objectOrClass::class : (\is_string($objectOrClass) ? $objectOrClass : ''); - if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName)) { + if ( + IgnoreManager::isCallerIgnored() + || (self::$vendorBoundaryOnly && CallerBoundaryResolver::isVendorFile($file)) + || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName) + ) { return $value; } @@ -643,7 +649,11 @@ public static function checkMemberAssign( ); if ($res instanceof ErrorMessage) { - if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($caller ?? '')) { + if ( + IgnoreManager::isCallerIgnored() + || (self::$vendorBoundaryOnly && CallerBoundaryResolver::isVendorFile($file)) + || CallerBoundaryResolver::shouldBypass($caller ?? '') + ) { return $value; } @@ -685,7 +695,11 @@ public static function checkMemberUnset( ); if ($res instanceof ErrorMessage) { - if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($caller ?? '')) { + if ( + IgnoreManager::isCallerIgnored() + || (self::$vendorBoundaryOnly && CallerBoundaryResolver::isVendorFile($file)) + || CallerBoundaryResolver::shouldBypass($caller ?? '') + ) { return null; } @@ -729,7 +743,11 @@ public static function checkPropertyMemberUnset( ); if ($res instanceof ErrorMessage) { - if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName)) { + if ( + IgnoreManager::isCallerIgnored() + || (self::$vendorBoundaryOnly && CallerBoundaryResolver::isVendorFile($file)) + || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName) + ) { return null; } @@ -961,7 +979,11 @@ public static function checkVariable( ); if ($res instanceof ErrorMessage) { - if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($caller !== null ? $caller : '')) { + if ( + IgnoreManager::isCallerIgnored() + || (self::$vendorBoundaryOnly && CallerBoundaryResolver::isVendorFile($file)) + || CallerBoundaryResolver::shouldBypass($caller !== null ? $caller : '') + ) { return $value; } @@ -988,7 +1010,11 @@ public static function checkProperty(mixed $value, mixed $objectOrClass, string $res = InlineChecker::checkProperty($value, $objectOrClass, $propName, $file, self::getRegistry()); if ($res instanceof ErrorMessage) { - if (IgnoreManager::isCallerIgnored() || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName)) { + if ( + IgnoreManager::isCallerIgnored() + || (self::$vendorBoundaryOnly && CallerBoundaryResolver::isVendorFile($file)) + || CallerBoundaryResolver::shouldBypass($className . '::$' . $propName) + ) { return $value; } diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index 00d3edd2..c0ae2981 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -889,6 +889,7 @@ public static function reset(): void RuntimeTypeChecker::$paramsOutEnabled = true; RuntimeTypeChecker::$selfOutEnabled = true; RuntimeTypeChecker::$inlinePropertiesEnabled = true; + RuntimeTypeChecker::$vendorBoundaryOnly = true; RuntimeTypeChecker::$arrayValidationHybrid = false; DocblockParser::reset(); @@ -974,6 +975,7 @@ private static function syncFlags(array $config): void RuntimeTypeChecker::$paramsOutEnabled = self::$params && self::$paramsOut; RuntimeTypeChecker::$selfOutEnabled = self::$selfOut; RuntimeTypeChecker::$inlinePropertiesEnabled = self::$inlineProperties; + RuntimeTypeChecker::$vendorBoundaryOnly = self::$vendorBoundaryOnly; RuntimeTypeChecker::$arrayValidationHybrid = (self::$arrayValidation === 'hybrid'); } diff --git a/tests/Internal/Diagnostic/ErrorFactoryTest.php b/tests/Internal/Diagnostic/ErrorFactoryTest.php index 7999cd7a..05d1f56d 100644 --- a/tests/Internal/Diagnostic/ErrorFactoryTest.php +++ b/tests/Internal/Diagnostic/ErrorFactoryTest.php @@ -2,8 +2,11 @@ declare(strict_types=1); +use TypePHP\Exception\TypeError as TypePHPTypeError; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Io\StreamWrapper; +use TypePHP\Internal\Util\Config; test('error factory creates an ErrorMessage value object', function () { $err = ErrorFactory::createError('Test argument error message'); @@ -69,3 +72,187 @@ expect($err->getMessage())->toBe("getOrderDiscount(): Return value must be of type positive-int, string 'discount given to customer' returned"); }); + +describe('Call-Site File & Line Attribution Integrity', function () { + beforeEach(function () { + Config::reset(); + StreamWrapper::reset(); + }); + + afterEach(function () { + Config::reset(); + StreamWrapper::reset(); + }); + + test('never combines caller file with callee line when an explicit line is provided for a property error', function () { + $baseTemp = sys_get_temp_dir() . '/typephp_err_atomic_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + + $calleeFile = $tempDir . '/CalleePropWriter.php'; + $callerFile = $tempDir . '/CallerEntry.php'; + + file_put_contents($calleeFile, <<<'PHP' +getFile())) + ->toBe(str_replace('\\', '/', $calleeFile)) + ->and($prepared->getLine())->toBe(14) + ; + } finally { + @unlink($calleeFile); + @unlink($callerFile); + @rmdir($tempDir); + } + }); + + test('points cross-file magic __get() property violation to exact caller file and caller line', function () { + $baseTemp = sys_get_temp_dir() . '/typephp_err_magic_cross_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + + $modelFile = $tempDir . '/MagicBaseModel.php'; + $consumerFile = $tempDir . '/MagicConsumer.php'; + + $padding = str_repeat("\n", 25); + file_put_contents($modelFile, " */\n protected array \$attributes = ['is_active' => true];\n{$padding} public function __get(string \$key): mixed\n {\n return \$this->attributes[\$key] ?? null;\n }\n}\n\n/**\n * @property object \$is_active\n */\nclass MagicUser extends MagicBaseModel\n{\n}\n"); + + file_put_contents($consumerFile, <<<'PHP' +is_active; +} +PHP); + + try { + Config::set([ + 'magic_properties' => ['write' => true, 'read' => true], + 'include' => [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $modelFile; + require_once $consumerFile; + + $user = new TypePHP\Tests\Internal\Diagnostic\MagicCrossFixture\MagicUser(); + + try { + \TypePHP\Tests\Internal\Diagnostic\MagicCrossFixture\readActiveFlag($user); + $this->fail('Expected TypePHP TypeError to be thrown'); + } catch (TypePHPTypeError $e) { + expect(str_replace('\\', '/', $e->getFile())) + ->toBe(str_replace('\\', '/', $consumerFile)) + ->and($e->getLine())->toBe(9) + ; + } + } finally { + @unlink($modelFile); + @unlink($consumerFile); + @rmdir($tempDir); + } + }); + + test('points same-file magic __get() property violation to the caller read line, not the __get return line', function () { + $baseTemp = sys_get_temp_dir() . '/typephp_err_magic_same_' . uniqid(); + mkdir($baseTemp, 0777, true); + $tempDir = realpath($baseTemp) !== false ? realpath($baseTemp) : $baseTemp; + + $sameFile = $tempDir . '/SameFileMagic.php'; + + file_put_contents($sameFile, <<<'PHP' + */ + protected array $attributes = ['is_active' => false]; + + public function __get(string $key): mixed + { + return $this->attributes[$key] ?? null; + } +} + +function readSameFileActive(SameFileMagicUser $user): mixed +{ + return $user->is_active; +} +PHP); + + try { + Config::set([ + 'magic_properties' => ['write' => true, 'read' => true], + 'include' => [str_replace('\\', '/', $tempDir) . '/**'], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $sameFile; + + $user = new TypePHP\Tests\Internal\Diagnostic\MagicSameFixture\SameFileMagicUser(); + + try { + \TypePHP\Tests\Internal\Diagnostic\MagicSameFixture\readSameFileActive($user); + $this->fail('Expected TypePHP TypeError to be thrown'); + } catch (TypePHPTypeError $e) { + expect(str_replace('\\', '/', $e->getFile())) + ->toBe(str_replace('\\', '/', $sameFile)) + ->and($e->getLine())->toBe(23) + ; + } + } finally { + @unlink($sameFile); + @rmdir($tempDir); + } + }); +}); diff --git a/tests/Internal/Resolver/CallerBoundaryResolverInheritanceTest.php b/tests/Internal/Resolver/CallerBoundaryResolverInheritanceTest.php new file mode 100644 index 00000000..28169908 --- /dev/null +++ b/tests/Internal/Resolver/CallerBoundaryResolverInheritanceTest.php @@ -0,0 +1,183 @@ + + */ + protected static array $classAttributes = []; + + /** + * @var array + */ + protected array $attributes = []; + + public static function resolveClassAttribute(string $attributeClass, string $property): mixed + { + $cacheKey = static::class . '@' . $attributeClass . '@' . $property; + + if (array_key_exists($cacheKey, static::$classAttributes)) { + return static::$classAttributes[$cacheKey]; + } + + return static::$classAttributes[$cacheKey] = 'cached_attr'; + } + + public function __get(string $key): mixed + { + return $this->attributes[$key] ?? null; + } + + public function setRawAttr(string $key, mixed $val): void + { + $this->attributes[$key] = $val; + } +} +PHP); + + file_put_contents($vendorCallerFile, <<<'PHP' +setRawAttr('is_active', true); + + // Vendor-internal magic read of an app model property should bypass under vendor_boundary_only + $active = $instance->is_active; + + return [$attr, $active]; + } +} +PHP); + + file_put_contents($appModelFile, <<<'PHP' +is_active; + } +} +PHP); + + try { + Config::set([ + 'vendor_boundary_only' => true, + 'magic_properties' => ['write' => true, 'read' => true], + 'include' => [ + $realBase . '/app/**', + $realBase . '/vendor/acme/eloquent/VendorBaseModel.php', + ], + 'exclude' => ['vendor/**'], + ]); + StreamWrapper::register(); + + require_once $vendorModelFile; + require_once $vendorCallerFile; + require_once $appModelFile; + require_once $appServiceFile; + + $res = \Acme\VendorEloquent\VendorCallerService::bootAndResolve(\App\VendorBoundaryDemo\InheritedAppUser::class); + expect($res)->toBe(['cached_attr', true]); + + $user = new \App\VendorBoundaryDemo\InheritedAppUser(); + $user->setRawAttr('is_active', true); + $authService = new \App\VendorBoundaryDemo\AppAuthService(); + + expect(fn () => $authService->readInvalidMagicProperty($user)) + ->toThrow(TypeError::class, 'Property App\VendorBoundaryDemo\InheritedAppUser::$is_active must be of type object') + ; + + expect(fn () => \App\VendorBoundaryDemo\InheritedAppUser::writeBadClassAttributeFromApp()) + ->toThrow(TypeError::class, 'class-string') + ; + } finally { + @unlink($vendorModelFile); + @unlink($vendorCallerFile); + @unlink($appModelFile); + @unlink($appServiceFile); + @rmdir($vendorDir); + @rmdir($realBase . '/vendor/acme'); + @rmdir($realBase . '/vendor'); + @rmdir($appDir); + @rmdir($realBase); + } + }); +}); From 906b364ae48449cf4b789d8cc7a1647cbc263d99 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 28 Nov 2026 15:50:43 +0800 Subject: [PATCH 2/2] Refactor ParamChecker and ReturnChecker for improved template handling; add GenericMagicMethodAndPropertyTest for comprehensive generic magic method and property validation --- src/Internal/Checker/ParamChecker.php | 9 +- src/Internal/Checker/ReturnChecker.php | 4 +- .../GenericMagicMethodAndPropertyTest.php | 574 ++++++++++++++++++ 3 files changed, 584 insertions(+), 3 deletions(-) create mode 100644 tests/TypeChecking/Generics/GenericMagicMethodAndPropertyTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index effc08ba..9fdaf7d7 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -2636,6 +2636,10 @@ private static function validateMagicArguments( $typeNode = new ArrayTypeNode($typeNode); } + if ($index > 0 && $templates !== []) { + $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + } + $err = self::validateSingleParam( $paramName, $typeNode, @@ -2647,8 +2651,9 @@ private static function validateMagicArguments( $boundTemplates, $declaredTemplates, $registry, - [], - $args + $templates, + $args, + $thisObj ); if ($err !== null) { diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index b0f61079..5ed0ffcd 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -435,7 +435,9 @@ private static function evaluateReturn( return $value; } - $hasClassTemplates = ($contract['classTemplates'] ?? []) !== []; + $hasClassTemplates = $contract !== [] + ? ($contract['classTemplates'] ?? []) !== [] + : $hasGenerics; $hasMethodTemplates = ($contract['templates'] ?? []) !== []; if ($thisObj !== null && ! $hasMethodTemplates) { diff --git a/tests/TypeChecking/Generics/GenericMagicMethodAndPropertyTest.php b/tests/TypeChecking/Generics/GenericMagicMethodAndPropertyTest.php new file mode 100644 index 00000000..9445f3b9 --- /dev/null +++ b/tests/TypeChecking/Generics/GenericMagicMethodAndPropertyTest.php @@ -0,0 +1,574 @@ + $items) + * @method list getMagicItems() + */ +class GenericMagicBox +{ + private mixed $data = null; + + /** + * @var list + */ + private array $listData = []; + + public function forceCorruptData(mixed $raw): void + { + $this->data = $raw; + } + + /** + * @param list $raw + */ + public function forceCorruptListData(array $raw): void + { + $this->listData = $raw; + } + + public function __get(string $name): mixed + { + return $this->data; + } + + public function __set(string $name, mixed $value): void + { + $this->data = $value; + } + + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + if ($name === 'getMagicItem') { + return $this->data; + } + if ($name === 'setMagicItem') { + $this->data = $args[0]; + + return null; + } + if ($name === 'setMagicItems') { + $this->listData = $args[0]; + + return null; + } + if ($name === 'getMagicItems') { + return $this->listData; + } + + return null; + } +} + +/** + * 1. Concrete @extends specialization + * + * @extends GenericMagicBox + */ +final class ConcreteUserMagicBox extends GenericMagicBox +{ +} + +/** + * 2. Multi-level generic @extends with renamed template U -> T + * + * @template U + * + * @extends GenericMagicBox + */ +class RenamedGenericMagicBox extends GenericMagicBox +{ +} + +/** + * @extends RenamedGenericMagicBox + */ +final class LeafUserMagicBox extends RenamedGenericMagicBox +{ +} + +/** + * 3. Child adding its own @method referencing parent's @template T + * + * @extends GenericMagicBox + * + * @method T echoChildMagic(T $val) + */ +final class ExtendedMethodMagicBox extends GenericMagicBox +{ + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + if ($name === 'echoChildMagic') { + return $args[0]; + } + + return parent::__call($name, $args); + } +} + +/** + * 4. Generic interface with @method contracts + * + * @template T + * + * @method T fetchMagic() + * @method void storeMagic(T $val) + */ +interface GenericMagicContractInterface +{ +} + +/** + * @implements GenericMagicContractInterface + */ +final class InterfaceMagicHolder implements GenericMagicContractInterface +{ + private mixed $stored = null; + + public function forceCorruptStored(mixed $raw): void + { + $this->stored = $raw; + } + + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + if ($name === 'storeMagic') { + $this->stored = $args[0]; + + return null; + } + if ($name === 'fetchMagic') { + return $this->stored; + } + + return null; + } +} + +/** + * 5. Trait composition (@use) with generic @property and @method + * + * @template T + * + * @property T $traitItem + * + * @method T getTraitMagic() + * @method void setTraitMagic(T $value) + */ +trait GenericMagicBehaviorTrait +{ + private mixed $traitData = null; + + public function forceCorruptTraitData(mixed $raw): void + { + $this->traitData = $raw; + } + + public function __get(string $name): mixed + { + return $this->traitData; + } + + public function __set(string $name, mixed $value): void + { + $this->traitData = $value; + } + + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + if ($name === 'getTraitMagic') { + return $this->traitData; + } + if ($name === 'setTraitMagic') { + $this->traitData = $args[0]; + + return null; + } + + return null; + } +} + +final class ConcreteTraitMagicBox +{ + /** @use GenericMagicBehaviorTrait */ + use GenericMagicBehaviorTrait; +} + +/** + * @template U + */ +final class ForwardedTraitMagicBox +{ + /** @use GenericMagicBehaviorTrait */ + use GenericMagicBehaviorTrait; +} + +/** + * 6. Object composition: generic magic container wrapping GenericMagicBox + * + * @template T + * + * @property GenericMagicBox $innerBox + * + * @method GenericMagicBox getInnerBox() + * @method void setInnerBox(GenericMagicBox $box) + */ +final class ComposedMagicContainer +{ + private mixed $inner = null; + + public function forceCorruptInner(mixed $raw): void + { + $this->inner = $raw; + } + + public function __get(string $name): mixed + { + return $this->inner; + } + + public function __set(string $name, mixed $value): void + { + $this->inner = $value; + } + + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + if ($name === 'setInnerBox') { + $this->inner = $args[0]; + + return null; + } + if ($name === 'getInnerBox') { + return $this->inner; + } + + return null; + } +} + +/** + * 7. Static generic magic methods (__callStatic) with @extends + * + * @template T + * + * @method static T echoStaticMagic(T $value) + * @method static T returnCorruptStaticMagic(mixed $raw) + */ +abstract class StaticGenericMagicBase +{ + /** + * @param array $args + */ + public static function __callStatic(string $name, array $args): mixed + { + return $args[0] ?? null; + } +} + +/** + * @extends StaticGenericMagicBase + */ +final class StaticUserMagicBox extends StaticGenericMagicBase +{ +} + +describe('Generic Magic Methods & Properties with Inheritance and Composition', function () { + beforeEach(function () { + Config::reset(); + }); + + afterEach(function () { + Config::reset(); + }); + + test('enforces inherited generic @property and @method via concrete @extends without @var', function () { + Config::set(['magic_properties' => ['write' => true, 'read' => true]]); + + $box = new ConcreteUserMagicBox(); + $alice = new MagicGenUser('Alice'); + + $box->item = $alice; + expect($box->item)->toBe($alice); + + expect(function () use ($box): void { + $box->item = new MagicGenProduct('SKU-EXT-1'); + })->toThrow(TypeError::class, MagicGenUser::class); + + $box->setMagicItem($alice); + expect($box->getMagicItem())->toBe($alice); + + expect(fn () => $box->setMagicItem(new MagicGenProduct('SKU-EXT-2'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $box->forceCorruptData(new MagicGenProduct('SKU-EXT-3')); + expect(fn () => $box->getMagicItem()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + expect(fn () => $box->item) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces multi-level @extends with template renaming (U -> T) both via @var and concrete leaf class', function () { + /** @var RenamedGenericMagicBox $mid */ + $mid = new RenamedGenericMagicBox(); + $mid->setMagicItem(new MagicGenUser('MidUser')); + + expect(fn () => $mid->setMagicItem(new MagicGenProduct('SKU-MID'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $leaf = new LeafUserMagicBox(); + $leaf->setMagicItem(new MagicGenUser('LeafUser')); + expect($leaf->getMagicItem()->name)->toBe('LeafUser'); + + expect(fn () => $leaf->setMagicItem(new MagicGenProduct('SKU-LEAF-1'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $leaf->forceCorruptData(new MagicGenProduct('SKU-LEAF-2')); + expect(fn () => $leaf->getMagicItem()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces child-declared @method referencing inherited @template T', function () { + $box = new ExtendedMethodMagicBox(); + $alice = new MagicGenUser('Alice'); + + expect($box->echoChildMagic($alice))->toBe($alice); + + expect(fn () => $box->echoChildMagic(new MagicGenProduct('SKU-CHILD'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces generic @method inherited from @implements interface', function () { + $holder = new InterfaceMagicHolder(); + $alice = new MagicGenUser('Alice'); + + $holder->storeMagic($alice); + expect($holder->fetchMagic())->toBe($alice); + + expect(fn () => $holder->storeMagic(new MagicGenProduct('SKU-IFACE-1'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $holder->forceCorruptStored(new MagicGenProduct('SKU-IFACE-2')); + expect(fn () => $holder->fetchMagic()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces generic @property and @method via trait composition (concrete @use and forwarded @use )', function () { + Config::set(['magic_properties' => ['write' => true, 'read' => true]]); + + $concrete = new ConcreteTraitMagicBox(); + $alice = new MagicGenUser('Alice'); + + $concrete->traitItem = $alice; + expect($concrete->traitItem)->toBe($alice); + expect(function () use ($concrete): void { + $concrete->traitItem = new MagicGenProduct('SKU-TR-1'); + })->toThrow(TypeError::class, MagicGenUser::class); + + $concrete->setTraitMagic($alice); + expect($concrete->getTraitMagic())->toBe($alice); + expect(fn () => $concrete->setTraitMagic(new MagicGenProduct('SKU-TR-2'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $concrete->forceCorruptTraitData(new MagicGenProduct('SKU-TR-3')); + expect(fn () => $concrete->getTraitMagic()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + /** @var ForwardedTraitMagicBox $forwarded */ + $forwarded = new ForwardedTraitMagicBox(); + $forwarded->setTraitMagic($alice); + expect($forwarded->getTraitMagic())->toBe($alice); + + expect(fn () => $forwarded->setTraitMagic(new MagicGenProduct('SKU-TR-4'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $forwarded->forceCorruptTraitData(new MagicGenProduct('SKU-TR-5')); + expect(fn () => $forwarded->getTraitMagic()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces object composition with nested generic magic boxes (@property & @method GenericMagicBox)', function () { + Config::set(['magic_properties' => ['write' => true, 'read' => true]]); + + /** @var ComposedMagicContainer $container */ + $container = new ComposedMagicContainer(); + + /** @var GenericMagicBox $userBox */ + $userBox = new GenericMagicBox(); + /** @var GenericMagicBox $productBox */ + $productBox = new GenericMagicBox(); + + $container->innerBox = $userBox; + expect($container->innerBox)->toBe($userBox); + + expect(function () use ($container, $productBox): void { + $container->innerBox = $productBox; + })->toThrow(TypeError::class, MagicGenUser::class); + + $container->setInnerBox($userBox); + expect($container->getInnerBox())->toBe($userBox); + + expect(fn () => $container->setInnerBox($productBox)) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $container->forceCorruptInner($productBox); + expect(fn () => $container->getInnerBox()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + expect(fn () => $container->innerBox) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces static generic @method (__callStatic) specialized via @extends', function () { + $alice = new MagicGenUser('Alice'); + + expect(StaticUserMagicBox::echoStaticMagic($alice))->toBe($alice); + + expect(fn () => StaticUserMagicBox::echoStaticMagic(new MagicGenProduct('SKU-ST-1'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + expect(fn () => StaticUserMagicBox::returnCorruptStaticMagic(new MagicGenProduct('SKU-ST-2'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); +}); + +describe('Generic Magic Properties & Magic Methods (@template T + @property / @method)', function () { + beforeEach(function () { + Config::reset(); + }); + + afterEach(function () { + Config::reset(); + }); + + test('enforces generic @property T writes and reads on MagicBox', function () { + Config::set(['magic_properties' => ['write' => true, 'read' => true]]); + + /** @var GenericMagicBox $userBox */ + $userBox = new GenericMagicBox(); + + $alice = new MagicGenUser('Alice'); + $userBox->item = $alice; + expect($userBox->item)->toBe($alice); + + expect(function () use ($userBox): void { + $userBox->item = new MagicGenProduct('SKU-1'); + })->toThrow(TypeError::class, MagicGenUser::class); + + $userBox->forceCorruptData(new MagicGenProduct('CORRUPT')); + expect(fn () => $userBox->item) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces generic @method parameter T on pre-bound MagicBox', function () { + /** @var GenericMagicBox $userBox */ + $userBox = new GenericMagicBox(); + + $bob = new MagicGenUser('Bob'); + $userBox->setMagicItem($bob); + expect($userBox->getMagicItem())->toBe($bob); + + expect(fn () => $userBox->setMagicItem(new MagicGenProduct('SKU-2'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces generic @method return type T on MagicBox', function () { + /** @var GenericMagicBox $userBox */ + $userBox = new GenericMagicBox(); + + $userBox->forceCorruptData(new MagicGenProduct('SKU-BAD')); + + expect(fn () => $userBox->getMagicItem()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('enforces compound generic @method parameters and returns (list)', function () { + /** @var GenericMagicBox $userBox */ + $userBox = new GenericMagicBox(); + + $alice = new MagicGenUser('Alice'); + $userBox->setMagicItems([$alice]); + expect($userBox->getMagicItems())->toBe([$alice]); + + expect(fn () => $userBox->setMagicItems([new MagicGenProduct('SKU-3')])) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + + $userBox->forceCorruptListData([new MagicGenProduct('SKU-4')]); + expect(fn () => $userBox->getMagicItems()) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); + + test('infers and locks class template T on first magic method call when no @var is used', function () { + $box = new GenericMagicBox(); + + $box->setMagicItem(new MagicGenUser('Charlie')); + + expect(fn () => $box->setMagicItem(new MagicGenProduct('SKU-5'))) + ->toThrow(TypeError::class, MagicGenUser::class) + ; + }); +});