Skip to content

Commit 4ec4c76

Browse files
committed
Add support for inline generic template variable support
1 parent 06a9e2a commit 4ec4c76

3 files changed

Lines changed: 218 additions & 28 deletions

File tree

‎src/Internal/Checker/InlineChecker.php‎

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,12 @@ final class InlineChecker
4242
*/
4343
private static array $parsedTypeNodeCache = [];
4444

45-
/**
46-
* In-memory cache for fully resolved type nodes per type string and file.
47-
*
48-
* @var array<string, TypeNode>
49-
*/
50-
private static array $resolvedTypeNodeCache = [];
51-
5245
/**
5346
* Resets internal type node caches. Useful for test isolation.
5447
*/
5548
public static function reset(): void
5649
{
5750
self::$parsedTypeNodeCache = [];
58-
self::$resolvedTypeNodeCache = [];
5951
}
6052

6153
/**
@@ -119,21 +111,15 @@ public static function checkVariable(mixed $value, string $typeString, string $v
119111
}
120112

121113
try {
122-
$cacheKey = $typeString . '|' . $file;
123-
if (isset(self::$resolvedTypeNodeCache[$cacheKey])) {
124-
$typeNode = self::$resolvedTypeNodeCache[$cacheKey];
125-
} else {
126-
$normalized = DocblockNormalizer::normalize($typeString);
127-
$typeNode = self::parseTypeString($normalized);
128-
129-
if ($file !== '') {
130-
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file);
131-
}
114+
$normalized = DocblockNormalizer::normalize($typeString);
115+
$typeNode = self::parseTypeString($normalized);
132116

133-
$typeNode = self::resolveCallerContext($typeNode);
134-
self::$resolvedTypeNodeCache[$cacheKey] = $typeNode;
117+
if ($file !== '') {
118+
$typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file);
135119
}
136120

121+
$typeNode = self::resolveCallerContext($typeNode);
122+
137123
if (! self::shouldValidateType($typeNode, $config)) {
138124
return $value;
139125
}
@@ -224,17 +210,21 @@ private static function hasActiveInlineChecks(array $config): bool
224210
}
225211

226212
/**
227-
* Resolves caller class context and applies class-level type aliases to the AST.
213+
* Resolves caller class context and applies class-level and method-level templates & type aliases to the AST.
228214
*/
229215
private static function resolveCallerContext(TypeNode $typeNode): TypeNode
230216
{
231217
$className = null;
232-
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 7);
218+
$methodName = null;
219+
$thisObj = null;
220+
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 7);
233221

234222
foreach ($trace as $frame) {
235223
$classCandidate = $frame['class'] ?? null;
236224
if ($classCandidate !== null && ! str_starts_with($classCandidate, 'TypePHP\\Internal\\') && ! str_starts_with($classCandidate, 'TypePHP\\Wrapper\\')) {
237225
$className = $classCandidate;
226+
$methodName = $frame['function'];
227+
$thisObj = $frame['object'] ?? null;
238228

239229
break;
240230
}
@@ -245,12 +235,25 @@ private static function resolveCallerContext(TypeNode $typeNode): TypeNode
245235
}
246236

247237
try {
238+
/** @var class-string<object> $className */
248239
$refClass = new \ReflectionClass($className);
249240
$typeNode = SpecialTypeResolver::resolve($typeNode, $refClass);
250241

251242
$classAliases = ContractParser::parseClassAliases($className);
252-
if (\count($classAliases) > 0) {
253-
$typeNode = TemplateSubstitutor::substitute($typeNode, $classAliases);
243+
244+
$targetFunc = ($methodName !== '{closure}')
245+
? $className . '::' . $methodName
246+
: $className . '::__construct';
247+
248+
$contract = ContractParser::parse($targetFunc);
249+
$declaredTemplates = $contract['allTemplates'] ?? ($contract['classTemplates'] ?? []);
250+
$boundTemplates = TemplateManager::getBoundTemplates($targetFunc, $thisObj, $declaredTemplates);
251+
252+
$activeBindings = array_merge($classAliases, $boundTemplates);
253+
254+
if (\count($activeBindings) > 0 || \count($declaredTemplates) > 0) {
255+
$typeNode = TemplateSubstitutor::substitute($typeNode, $activeBindings, $declaredTemplates);
256+
$typeNode = SpecialTypeResolver::resolve($typeNode, $refClass);
254257
}
255258
} catch (\ReflectionException $e) {
256259
// Silently continue if reflection fails
@@ -276,6 +279,7 @@ private static function substitutePropertyGenerics(TypeNode $typeNode, object $o
276279

277280
if (class_exists($className) || interface_exists($className) || trait_exists($className)) {
278281
try {
282+
/** @var class-string<object> $className */
279283
$refClass = new \ReflectionClass($className);
280284
$typeNode = SpecialTypeResolver::resolve($typeNode, $refClass);
281285
} catch (\ReflectionException $e) {

‎src/Internal/ContractVisitor.php‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,15 @@ public function enterNode(Node $node): array|int|null
7575
$extracted = DocblockExtractor::extractVarTagFromDoc($doc->getText());
7676
if ($extracted !== null) {
7777
[$typeString, $varName] = $extracted;
78-
$effectiveVarName = ($varName !== '') ? $varName : 'return';
79-
$checkCall = NodeBuilder::createVariableCheckCall($node->expr, $typeString, $effectiveVarName);
80-
$node->expr = NodeBuilder::createTernaryThrowExpr($checkCall, $node->getStartLine());
81-
$node->setAttribute('typephp_var_wrapped', true);
78+
$isApplicableToReturn = ($varName === '')
79+
|| ($node->expr instanceof Node\Expr\Variable && $node->expr->name === $varName);
80+
81+
if ($isApplicableToReturn) {
82+
$effectiveVarName = ($varName !== '') ? $varName : 'return';
83+
$checkCall = NodeBuilder::createVariableCheckCall($node->expr, $typeString, $effectiveVarName);
84+
$node->expr = NodeBuilder::createTernaryThrowExpr($checkCall, $node->getStartLine());
85+
$node->setAttribute('typephp_var_wrapped', true);
86+
}
8287
}
8388
}
8489
}
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\TypeChecking\Generics;
6+
7+
use TypePHP\Exception\TypeError;
8+
use TypePHP\Internal\Config;
9+
use TypePHP\Tests\Fixtures\Collections\ShopwareCollection;
10+
use TypePHP\Tests\Fixtures\Collections\ShopwareEntityCollection;
11+
use TypePHP\Tests\Fixtures\Collections\ShopwareEntitySearchResult;
12+
use TypePHP\Tests\Fixtures\Collections\SpecificDogSearchResult;
13+
use TypePHP\Tests\Fixtures\Domain\Car;
14+
use TypePHP\Tests\Fixtures\Domain\Dog;
15+
16+
/**
17+
* @template TEntityCollection of ShopwareCollection
18+
*/
19+
class ClassTemplateInlineVarRepository
20+
{
21+
/**
22+
* Case 1: Exact Shopware Line 129 Pattern Named @var $result on a return expression constructing SearchResult
23+
*/
24+
public function searchConstructsResult(): object
25+
{
26+
$result = new ShopwareEntityCollection();
27+
28+
/** @var TEntityCollection $result */
29+
return new ShopwareEntitySearchResult($result);
30+
}
31+
32+
/**
33+
* Case 2: Named @var $result where the return expression IS $result
34+
*/
35+
public function searchDirectReturn(): object
36+
{
37+
/** @var TEntityCollection $result */
38+
$result = new ShopwareEntityCollection();
39+
40+
return $result;
41+
}
42+
43+
/**
44+
* Case 3: Unnamed @var on return statement
45+
*/
46+
public function searchUnnamedReturn(): object
47+
{
48+
/** @var TEntityCollection */
49+
return new ShopwareEntityCollection();
50+
}
51+
52+
/**
53+
* Case 4: Template used inside Generic Container on inline variable
54+
*/
55+
public function searchWithGenericContainer(): object
56+
{
57+
$collection = new ShopwareEntityCollection();
58+
59+
/** @var ShopwareEntitySearchResult<TEntityCollection> $searchResult */
60+
$searchResult = new ShopwareEntitySearchResult($collection);
61+
62+
return $searchResult;
63+
}
64+
65+
/**
66+
* Case 5: Method-level generic template in inline variable
67+
*
68+
* @template TItem of object
69+
*
70+
* @param TItem $item
71+
*/
72+
public function processItem(object $item): object
73+
{
74+
/** @var TItem $localItem */
75+
$localItem = $item;
76+
77+
return $localItem;
78+
}
79+
80+
/**
81+
* Case 6: Assigning an invalid object violating the template upper bound
82+
*/
83+
public function assignInvalidObject(): void
84+
{
85+
/** @var TEntityCollection $bad */
86+
$bad = new Car(); // Car is not a ShopwareCollection!
87+
}
88+
}
89+
90+
/**
91+
* Subclass binding TEntityCollection to SpecificDogSearchResult
92+
*
93+
* @extends ClassTemplateInlineVarRepository<SpecificDogSearchResult>
94+
*/
95+
class ConcreteDogRepository extends ClassTemplateInlineVarRepository
96+
{
97+
public function searchSpecificDog(): object
98+
{
99+
/** @var TEntityCollection $dogResult */
100+
$dogResult = new SpecificDogSearchResult();
101+
102+
return $dogResult;
103+
}
104+
105+
public function searchWrongCollection(): object
106+
{
107+
/** @var TEntityCollection $wrongResult */
108+
$wrongResult = new ShopwareEntityCollection();
109+
110+
return $wrongResult;
111+
}
112+
}
113+
114+
describe('Class-Level & Method-Level Template Resolution in Inline @var Annotations', function () {
115+
test('resolves named @var on return expression constructing new object (Exact Shopware Line 129)', function () {
116+
$repo = new ClassTemplateInlineVarRepository();
117+
expect($repo->searchConstructsResult())->toBeInstanceOf(ShopwareEntitySearchResult::class);
118+
});
119+
120+
test('resolves named @var where return expression is the variable', function () {
121+
$repo = new ClassTemplateInlineVarRepository();
122+
expect($repo->searchDirectReturn())->toBeInstanceOf(ShopwareEntityCollection::class);
123+
});
124+
125+
test('resolves unnamed @var directly on return statement', function () {
126+
$repo = new ClassTemplateInlineVarRepository();
127+
expect($repo->searchUnnamedReturn())->toBeInstanceOf(ShopwareEntityCollection::class);
128+
});
129+
130+
test('resolves template used inside generic container on inline @var', function () {
131+
$repo = new ClassTemplateInlineVarRepository();
132+
expect($repo->searchWithGenericContainer())->toBeInstanceOf(ShopwareEntitySearchResult::class);
133+
});
134+
135+
test('resolves method-level template in inline @var variable', function () {
136+
$repo = new ClassTemplateInlineVarRepository();
137+
$dog = new Dog();
138+
139+
expect($repo->processItem($dog))->toBe($dog);
140+
});
141+
142+
test('throws TypeError when inline variable violates template upper bound', function () {
143+
$repo = new ClassTemplateInlineVarRepository();
144+
145+
expect(fn () => $repo->assignInvalidObject())
146+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Collections\ShopwareCollection')
147+
;
148+
});
149+
150+
test('resolves pre-bound template in subclass on inline @var variable', function () {
151+
$repo = new ConcreteDogRepository();
152+
153+
expect($repo->searchSpecificDog())->toBeInstanceOf(SpecificDogSearchResult::class);
154+
155+
expect(fn () => $repo->searchWrongCollection())
156+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Collections\SpecificDogSearchResult')
157+
;
158+
});
159+
160+
test('respects inline_vars configuration toggles when disabled', function () {
161+
try {
162+
$repo = new ClassTemplateInlineVarRepository();
163+
164+
expect(fn () => $repo->assignInvalidObject())
165+
->toThrow(TypeError::class)
166+
;
167+
168+
Config::set([
169+
'inline_vars' => [
170+
'objects' => false,
171+
'generics' => false,
172+
],
173+
]);
174+
175+
$repo->assignInvalidObject();
176+
expect(true)->toBeTrue();
177+
} finally {
178+
Config::reset();
179+
}
180+
});
181+
});

0 commit comments

Comments
 (0)