Skip to content

Commit cf14616

Browse files
committed
Enhance BoxConsumer with generic methods and type validation tests and implement fix on the bug
1 parent 87770ba commit cf14616

3 files changed

Lines changed: 130 additions & 2 deletions

File tree

‎src/Internal/Checker/ParamChecker.php‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@
1818
use TypePHP\Internal\Diagnostic\ErrorFactory;
1919
use TypePHP\Internal\Diagnostic\ErrorMessage;
2020
use TypePHP\Internal\Diagnostic\TypeFormatter;
21+
use TypePHP\Internal\Docblock\DocblockExtractor;
2122
use TypePHP\Internal\Docblock\DocblockParser;
2223
use TypePHP\Internal\Generics\TemplateManager;
2324
use TypePHP\Internal\Generics\TemplateSubstitutor;
2425
use TypePHP\Internal\Resolver\HierarchyResolver;
2526
use TypePHP\Internal\Resolver\SpecialTypeResolver;
2627
use TypePHP\Internal\Util\ClassNameValidator;
2728
use TypePHP\Internal\Util\Config;
29+
use TypePHP\Internal\Util\StubManager;
2830
use TypePHP\Internal\Validator\TypeValidatorRegistry;
2931

3032
/**
@@ -51,13 +53,21 @@ final class ParamChecker
5153
*/
5254
private static array $baseTypeCache = [];
5355

56+
/**
57+
* Cache for declared class template names by class FQCN.
58+
*
59+
* @var array<string, list<string>>
60+
*/
61+
private static array $classDeclaredTemplateNamesCache = [];
62+
5463
/**
5564
* Resets internal caches. Useful for test isolation.
5665
*/
5766
public static function reset(): void
5867
{
5968
self::$effectiveFunctionCache = [];
6069
self::$noParamContractCache = [];
70+
self::$classDeclaredTemplateNamesCache = [];
6171
ClassNameValidator::reset();
6272
self::$baseTypeCache = [];
6373
}
@@ -803,6 +813,25 @@ private static function inferGenericObjectNode(
803813
return;
804814
}
805815

816+
$targetClassFqcn = SpecialTypeResolver::resolveFqcn($typeNode->type->name, new \ReflectionClass($value));
817+
$targetTemplateNames = self::$classDeclaredTemplateNamesCache[$targetClassFqcn] ?? null;
818+
819+
if ($targetTemplateNames === null) {
820+
$targetTemplateNames = [];
821+
if (class_exists($targetClassFqcn, false) || class_exists($targetClassFqcn) || interface_exists($targetClassFqcn) || trait_exists($targetClassFqcn)) {
822+
try {
823+
$targetRef = new \ReflectionClass($targetClassFqcn);
824+
$targetDoc = StubManager::getClassDoc($targetClassFqcn) ?? $targetRef->getDocComment();
825+
if ($targetDoc !== false && $targetDoc !== null) {
826+
$targetPhpDocNode = DocblockExtractor::parseDocString($targetDoc);
827+
$targetTemplateNames = array_keys(DocblockExtractor::extractTemplates($targetPhpDocNode));
828+
}
829+
} catch (\Throwable $e) {
830+
}
831+
}
832+
self::$classDeclaredTemplateNamesCache[$targetClassFqcn] = $targetTemplateNames;
833+
}
834+
806835
$instanceBoundTypes = array_values($boundOnInstance);
807836

808837
foreach ($typeNode->genericTypes as $idx => $gtNode) {
@@ -812,7 +841,14 @@ private static function inferGenericObjectNode(
812841
$targetObj = $isClassLevel ? $thisObj : null;
813842

814843
if (! TemplateManager::isBound($effectiveFunction, $targetObj, $tName)) {
815-
$inferredCandidate = $instanceBoundTypes[$idx] ?? null;
844+
$targetTemplateName = $targetTemplateNames[$idx] ?? null;
845+
$inferredCandidate = null;
846+
847+
if ($targetTemplateName !== null && isset($boundOnInstance[$targetTemplateName])) {
848+
$inferredCandidate = $boundOnInstance[$targetTemplateName];
849+
} elseif (isset($instanceBoundTypes[$idx])) {
850+
$inferredCandidate = $instanceBoundTypes[$idx];
851+
}
816852

817853
if ($inferredCandidate !== null) {
818854
$templateTag = $templates[$tName];

‎tests/Fixtures/Forwarding/BoxConsumer.php‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,58 @@ final class BoxConsumer
1515
public function __construct(public readonly BoxInterface $box)
1616
{
1717
}
18+
19+
/**
20+
* @template T of ItemBase
21+
* @template U of ItemBase
22+
*
23+
* @param BoxInterface<T, U> $box
24+
*
25+
* @return T
26+
*/
27+
public function extractFirst(BoxInterface $box): ItemBase
28+
{
29+
return new ItemA();
30+
}
31+
32+
/**
33+
* @template T of ItemBase
34+
* @template U of ItemBase
35+
*
36+
* @param BoxInterface<T, U> $box
37+
*
38+
* @return U
39+
*/
40+
public function extractSecond(BoxInterface $box): ItemBase
41+
{
42+
return new ItemB();
43+
}
44+
45+
/**
46+
* Method returning invalid type (returns ItemB when T is ItemA)
47+
*
48+
* @template T of ItemBase
49+
* @template U of ItemBase
50+
*
51+
* @param BoxInterface<T, U> $box
52+
*
53+
* @return T
54+
*/
55+
public function extractBad(BoxInterface $box): ItemBase
56+
{
57+
return new ItemB();
58+
}
59+
60+
/**
61+
* @template T of ItemBase
62+
* @template U of ItemBase
63+
*
64+
* @param BoxInterface<T, U> $box
65+
*
66+
* @return BoxInterface<T, U>
67+
*/
68+
public function passThrough(BoxInterface $box): BoxInterface
69+
{
70+
return $box;
71+
}
1872
}

‎tests/TypeChecking/Generics/GenericForwardingInheritanceTest.php‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace TypePHP\Tests\TypeChecking\Generics;
66

7+
use TypePHP\Exception\TypeError;
78
use TypePHP\Tests\Fixtures\Forwarding\BoxConsumer;
89
use TypePHP\Tests\Fixtures\Forwarding\ConcreteBox;
910
use TypePHP\Tests\Fixtures\Forwarding\ItemA;
@@ -13,7 +14,6 @@
1314
describe('Generic Template Forwarding Across Abstract Hierarchies with Shifted Template Indexes', function () {
1415
test('infers method template arguments T and U from implementing class when abstract parent has extra leading template', function () {
1516
$concreteBox = new ConcreteBox();
16-
1717
$consumer = new BoxConsumer($concreteBox);
1818

1919
expect($consumer->box)->toBe($concreteBox);
@@ -26,4 +26,42 @@
2626
->and(TypePHP::getGenericType($concreteBox, 'U'))->toBe(ItemB::class)
2727
;
2828
});
29+
30+
describe('Return Type Contracts with Forwarded Generics', function () {
31+
test('validates @return T correctly uses inferred ItemA', function () {
32+
$concreteBox = new ConcreteBox();
33+
$consumer = new BoxConsumer($concreteBox);
34+
35+
$first = $consumer->extractFirst($concreteBox);
36+
expect($first)->toBeInstanceOf(ItemA::class);
37+
});
38+
39+
test('validates @return U correctly uses inferred ItemB', function () {
40+
$concreteBox = new ConcreteBox();
41+
$consumer = new BoxConsumer($concreteBox);
42+
43+
$second = $consumer->extractSecond($concreteBox);
44+
expect($second)->toBeInstanceOf(ItemB::class);
45+
});
46+
47+
test('throws TypeError when @return T returns ItemB instead of inferred ItemA', function () {
48+
$concreteBox = new ConcreteBox();
49+
$consumer = new BoxConsumer($concreteBox);
50+
51+
expect(fn () => $consumer->extractBad($concreteBox))
52+
->toThrow(
53+
TypeError::class,
54+
'Return value must be of type ' . ItemA::class . ', ' . ItemB::class . ' returned'
55+
)
56+
;
57+
});
58+
59+
test('validates @return BoxInterface<T, U> returning the forwarded concrete instance', function () {
60+
$concreteBox = new ConcreteBox();
61+
$consumer = new BoxConsumer($concreteBox);
62+
63+
$result = $consumer->passThrough($concreteBox);
64+
expect($result)->toBe($concreteBox);
65+
});
66+
});
2967
});

0 commit comments

Comments
 (0)