Skip to content

Commit db38b21

Browse files
committed
Enhance TemplateManager with support for ArrayShape, ObjectShape, CallableType, and OffsetAccess types; add comprehensive tests for inherited generic shapes and namespace resolution
1 parent 7b3268c commit db38b21

2 files changed

Lines changed: 366 additions & 0 deletions

File tree

‎src/Internal/Generics/TemplateManager.php‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,19 @@
55
namespace TypePHP\Internal\Generics;
66

77
use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
8+
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
89
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
10+
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeUnsealedTypeNode;
911
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
12+
use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
13+
use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
1014
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
1115
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
1216
use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
1317
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
18+
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode;
19+
use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
20+
use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode;
1421
use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
1522
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
1623
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
@@ -1573,6 +1580,69 @@ private static function resolveTypeNodeAst(TypeNode $n, \ReflectionClass $ref):
15731580
return new IntersectionTypeNode(array_map(fn ($t) => self::resolveTypeNodeAst($t, $ref), $n->types));
15741581
}
15751582

1583+
if ($n instanceof ArrayShapeNode) {
1584+
$items = array_map(function ($item) use ($ref) {
1585+
return new ArrayShapeItemNode(
1586+
$item->keyName,
1587+
$item->optional,
1588+
self::resolveTypeNodeAst($item->valueType, $ref)
1589+
);
1590+
}, $n->items);
1591+
1592+
$unsealed = null;
1593+
if ($n->unsealedType !== null) {
1594+
$unsealedKey = $n->unsealedType->keyType !== null
1595+
? self::resolveTypeNodeAst($n->unsealedType->keyType, $ref)
1596+
: null;
1597+
$unsealedVal = self::resolveTypeNodeAst($n->unsealedType->valueType, $ref);
1598+
$unsealed = new ArrayShapeUnsealedTypeNode($unsealedVal, $unsealedKey);
1599+
}
1600+
1601+
if ($n->sealed) {
1602+
return ArrayShapeNode::createSealed($items, $n->kind);
1603+
}
1604+
1605+
return ArrayShapeNode::createUnsealed($items, $unsealed, $n->kind);
1606+
}
1607+
1608+
if ($n instanceof ObjectShapeNode) {
1609+
$items = array_map(function ($item) use ($ref) {
1610+
return new ObjectShapeItemNode(
1611+
$item->keyName,
1612+
$item->optional,
1613+
self::resolveTypeNodeAst($item->valueType, $ref)
1614+
);
1615+
}, $n->items);
1616+
1617+
return new ObjectShapeNode($items);
1618+
}
1619+
1620+
if ($n instanceof CallableTypeNode) {
1621+
$params = array_map(function ($p) use ($ref) {
1622+
return new CallableTypeParameterNode(
1623+
self::resolveTypeNodeAst($p->type, $ref),
1624+
$p->isReference,
1625+
$p->isVariadic,
1626+
$p->parameterName,
1627+
$p->isOptional
1628+
);
1629+
}, $n->parameters);
1630+
1631+
return new CallableTypeNode(
1632+
$n->identifier,
1633+
$params,
1634+
self::resolveTypeNodeAst($n->returnType, $ref),
1635+
$n->templateTypes
1636+
);
1637+
}
1638+
1639+
if ($n instanceof OffsetAccessTypeNode) {
1640+
return new OffsetAccessTypeNode(
1641+
self::resolveTypeNodeAst($n->type, $ref),
1642+
self::resolveTypeNodeAst($n->offset, $ref)
1643+
);
1644+
}
1645+
15761646
return $n;
15771647
}
15781648
}
Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace TypePHP\Tests\TypeChecking\Generics;
6+
7+
use ArrayIterator;
8+
use Generator;
9+
use Traversable;
10+
use TypePHP\Exception\TypeError;
11+
use TypePHP\Internal\Util\Config;
12+
use TypePHP\Tests\Fixtures\Domain\Car;
13+
use TypePHP\Tests\Fixtures\Domain\User;
14+
use TypePHP\TypePHP;
15+
16+
/**
17+
* @template T
18+
*/
19+
class InheritedShapeBaseBox
20+
{
21+
/**
22+
* @param T $value
23+
*/
24+
public function put(mixed $value): mixed
25+
{
26+
return $value;
27+
}
28+
}
29+
30+
/**
31+
* @extends InheritedShapeBaseBox<array{user: User, car?: Car}>
32+
*/
33+
class InheritedArrayShapeUserBox extends InheritedShapeBaseBox
34+
{
35+
}
36+
37+
/**
38+
* @extends InheritedShapeBaseBox<object{user: User}>
39+
*/
40+
class InheritedObjectShapeUserBox extends InheritedShapeBaseBox
41+
{
42+
}
43+
44+
/**
45+
* @extends InheritedShapeBaseBox<callable(User): User>
46+
*/
47+
class InheritedCallableUserBox extends InheritedShapeBaseBox
48+
{
49+
}
50+
51+
/**
52+
* Extends BaseBox with an iterable containing an unqualified class name
53+
*
54+
* @extends InheritedShapeBaseBox<iterable<User>>
55+
*/
56+
class InheritedIterableUserBox extends InheritedShapeBaseBox
57+
{
58+
}
59+
60+
/**
61+
* Extends BaseBox with a Traversable containing an unqualified class name
62+
*
63+
* @extends InheritedShapeBaseBox<Traversable<string, User>>
64+
*/
65+
class InheritedTraversableUserBox extends InheritedShapeBaseBox
66+
{
67+
/**
68+
* Consumes the Traversable so lazy iteration checks fire
69+
*
70+
* @param Traversable<string, User> $items
71+
*
72+
* @return list<User>
73+
*/
74+
public function consume(Traversable $items): array
75+
{
76+
$collected = [];
77+
foreach ($items as $item) {
78+
$collected[] = $item;
79+
}
80+
81+
return $collected;
82+
}
83+
}
84+
85+
/**
86+
* Extends BaseBox with a Generator containing an unqualified class name
87+
*
88+
* @extends InheritedShapeBaseBox<Generator<int, User>>
89+
*/
90+
class InheritedGeneratorUserBox extends InheritedShapeBaseBox
91+
{
92+
/**
93+
* @return Generator<int, User>
94+
*/
95+
public function stream(bool $valid = true): Generator
96+
{
97+
yield 0 => $valid ? new User('Alice') : new Car();
98+
}
99+
}
100+
101+
/**
102+
* Extends BaseBox with an array shape holding a nested iterable of unqualified User
103+
*
104+
* @extends InheritedShapeBaseBox<array{stream: iterable<User>}>
105+
*/
106+
class InheritedShapeWithIterableUserBox extends InheritedShapeBaseBox
107+
{
108+
}
109+
110+
/**
111+
* @template T
112+
*/
113+
interface InheritedShapeInterface
114+
{
115+
/**
116+
* @param T $data
117+
*/
118+
public function process(mixed $data): mixed;
119+
}
120+
121+
/**
122+
* @implements InheritedShapeInterface<array{user: User, car?: Car}>
123+
*/
124+
class InheritedShapeInterfaceImplementation implements InheritedShapeInterface
125+
{
126+
public function process(mixed $data): mixed
127+
{
128+
return $data;
129+
}
130+
}
131+
132+
/**
133+
* @template T
134+
*/
135+
trait InheritedShapeTrait
136+
{
137+
/**
138+
* @param T $record
139+
*/
140+
public function logRecord(mixed $record): mixed
141+
{
142+
return $record;
143+
}
144+
}
145+
146+
class InheritedShapeInlineTraitConsumer
147+
{
148+
/**
149+
* @use InheritedShapeTrait<array{user: User}>
150+
*/
151+
use InheritedShapeTrait;
152+
}
153+
154+
/**
155+
* @use InheritedShapeTrait<array{user: User}>
156+
*/
157+
class InheritedShapeClassLevelTraitConsumer
158+
{
159+
use InheritedShapeTrait;
160+
}
161+
162+
describe('Inherited Generic Shapes & Iterables Namespace Resolution', function () {
163+
beforeEach(function () {
164+
Config::reset();
165+
});
166+
167+
afterEach(function () {
168+
Config::reset();
169+
});
170+
171+
describe('Class Shapes & Callables (@extends)', function () {
172+
test('resolves unqualified class names inside array shapes in @extends tag (reported bug)', function () {
173+
$box = new InheritedArrayShapeUserBox();
174+
175+
$payload = ['user' => new User('Alice')];
176+
expect($box->put($payload))->toBe($payload);
177+
178+
expect(fn () => $box->put(['user' => new Car()]))
179+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
180+
;
181+
});
182+
183+
test('resolves unqualified class names inside object shapes in @extends tag', function () {
184+
$box = new InheritedObjectShapeUserBox();
185+
186+
$valid = (object)['user' => new User('Bob')];
187+
expect($box->put($valid))->toBe($valid);
188+
189+
$invalid = (object)['user' => new Car()];
190+
expect(fn () => $box->put($invalid))
191+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
192+
;
193+
});
194+
195+
test('resolves unqualified class names inside callables in @extends tag', function () {
196+
$box = new InheritedCallableUserBox();
197+
198+
$cb = fn (User $u): User => $u;
199+
$wrapped = $box->put($cb);
200+
201+
expect($wrapped(new User('Charlie')))->toBeInstanceOf(User::class);
202+
});
203+
});
204+
205+
describe('Iterables and Generators (@extends)', function () {
206+
test('resolves unqualified class names inside iterable<User> in @extends tag', function () {
207+
$box = new InheritedIterableUserBox();
208+
209+
expect(TypePHP::getGenericType($box))->toBe('iterable<TypePHP\Tests\Fixtures\Domain\User>');
210+
211+
$payload = [new User('Alice'), new User('Bob')];
212+
expect($box->put($payload))->toBe($payload);
213+
214+
expect(fn () => $box->put([new Car()]))
215+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
216+
;
217+
});
218+
219+
test('resolves unqualified class names inside Traversable<string, User> in @extends tag and validates on iteration', function () {
220+
$box = new InheritedTraversableUserBox();
221+
222+
expect(TypePHP::getGenericType($box))->toBe('Traversable<string, TypePHP\Tests\Fixtures\Domain\User>');
223+
224+
$iter = new ArrayIterator(['first' => new User('Alice')]);
225+
expect($box->consume($iter))->toHaveCount(1);
226+
227+
$badIter = new ArrayIterator(['first' => new Car()]);
228+
expect(fn () => $box->consume($badIter))
229+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
230+
;
231+
});
232+
233+
test('resolves unqualified class names inside Generator<int, User> in @extends tag and validates on yield', function () {
234+
$box = new InheritedGeneratorUserBox();
235+
236+
expect(TypePHP::getGenericType($box))->toBe('Generator<int, TypePHP\Tests\Fixtures\Domain\User>');
237+
238+
$validGen = $box->stream(true);
239+
expect($validGen->current())->toBeInstanceOf(User::class);
240+
241+
$badGen = $box->stream(false);
242+
expect(fn () => $badGen->current())
243+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
244+
;
245+
});
246+
247+
test('resolves unqualified class names inside array shape containing nested iterable<User>', function () {
248+
$box = new InheritedShapeWithIterableUserBox();
249+
250+
$valid = ['stream' => [new User('Alice'), new User('Bob')]];
251+
expect($box->put($valid))->toBe($valid);
252+
253+
$invalid = ['stream' => [new Car()]];
254+
expect(fn () => $box->put($invalid))
255+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
256+
;
257+
});
258+
});
259+
260+
describe('Interface Implementation (@implements)', function () {
261+
test('resolves unqualified class names inside array shapes in @implements tag', function () {
262+
$service = new InheritedShapeInterfaceImplementation();
263+
264+
$valid = ['user' => new User('Dave')];
265+
expect($service->process($valid))->toBe($valid);
266+
267+
expect(fn () => $service->process(['user' => new Car()]))
268+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
269+
;
270+
});
271+
});
272+
273+
describe('Trait Usage (@use)', function () {
274+
test('resolves unqualified class names inside array shapes in inline trait use statement', function () {
275+
$consumer = new InheritedShapeInlineTraitConsumer();
276+
277+
$valid = ['user' => new User('Eve')];
278+
expect($consumer->logRecord($valid))->toBe($valid);
279+
280+
expect(fn () => $consumer->logRecord(['user' => new Car()]))
281+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
282+
;
283+
});
284+
285+
test('resolves unqualified class names inside array shapes in class-level trait use docblock', function () {
286+
$consumer = new InheritedShapeClassLevelTraitConsumer();
287+
288+
$valid = ['user' => new User('Frank')];
289+
expect($consumer->logRecord($valid))->toBe($valid);
290+
291+
expect(fn () => $consumer->logRecord(['user' => new Car()]))
292+
->toThrow(TypeError::class, 'must be of type TypePHP\Tests\Fixtures\Domain\User')
293+
;
294+
});
295+
});
296+
});

0 commit comments

Comments
 (0)