Skip to content

Commit ac2a84f

Browse files
committed
Enhance stub system to resolve imported type aliases and improve docblock extraction
1 parent cc91dc8 commit ac2a84f

5 files changed

Lines changed: 125 additions & 13 deletions

File tree

‎src/Command/ConfigInitCommand.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,4 +197,4 @@ private static function getTemplate(): string
197197
];
198198
PHP;
199199
}
200-
}
200+
}

‎src/Contract/DocblockExtractor.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use PHPStan\PhpDocParser\ParserConfig;
2020
use TypePHP\Internal\ClassNameValidator;
2121
use TypePHP\Internal\DocblockNormalizer;
22+
use TypePHP\Internal\StubManager;
2223
use TypePHP\Resolver\SpecialTypeResolver;
2324

2425
/**
@@ -345,10 +346,11 @@ public static function resolveImportedTypeAlias(string $fqcn, string $importedAl
345346
}
346347

347348
try {
349+
$stubDoc = StubManager::getClassDoc($fqcn);
348350
$ref = new \ReflectionClass($fqcn);
349-
$doc = $ref->getDocComment();
351+
$doc = $stubDoc ?? $ref->getDocComment();
350352

351-
if ($doc !== false) {
353+
if ($doc !== false && $doc !== null) {
352354
$phpDocNode = self::parseDocString($doc);
353355

354356
$targetAliases = [];

‎src/Resolver/TemplateManager.php‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
use TypePHP\Internal\ClassNameValidator;
2525
use TypePHP\Internal\ErrorFactory;
2626
use TypePHP\Internal\ErrorMessage;
27+
use TypePHP\Internal\StubManager;
2728
use WeakMap;
2829

2930
/**
@@ -168,10 +169,11 @@ public static function getTemplateVariances(object $instance): array
168169
$className = \get_class($instance);
169170

170171
try {
172+
$stubDoc = StubManager::getClassDoc($className);
171173
$ref = new \ReflectionClass($className);
172-
$classDoc = $ref->getDocComment();
174+
$classDoc = $stubDoc ?? $ref->getDocComment();
173175

174-
if ($classDoc !== false) {
176+
if ($classDoc !== false && $classDoc !== null) {
175177
[$phpDocParser, $lexer] = self::getPhpDocParserComponents();
176178

177179
$classTokens = new TokenIterator($lexer->tokenize($classDoc));
@@ -309,8 +311,11 @@ private static function collectHierarchyTemplatesAndVariances(\ReflectionClass $
309311
$classVariances = [];
310312

311313
foreach ($classHierarchy as $hierClass) {
312-
$classDoc = $hierClass->getDocComment();
313-
if ($classDoc === false) {
314+
$hierClassName = $hierClass->getName();
315+
$stubDoc = StubManager::getClassDoc($hierClassName);
316+
$classDoc = $stubDoc ?? $hierClass->getDocComment();
317+
318+
if ($classDoc === false || $classDoc === null) {
314319
continue;
315320
}
316321

@@ -402,7 +407,7 @@ private static function bindSingleTemplateArgument(
402407

403408
/**
404409
* Resolves and binds parent class (@extends), interface (@implements), and trait (@use) template mappings.
405-
* Respects Vendor Isolation by skipping docblocks from excluded vendor ancestor files.
410+
* Respects Vendor Isolation by skipping docblocks from excluded vendor ancestor files unless stubbed.
406411
*/
407412
public static function resolveInheritedTemplates(object $instance, string $targetClassName): void
408413
{
@@ -415,8 +420,10 @@ public static function resolveInheritedTemplates(object $instance, string $targe
415420

416421
foreach ($classHierarchy as $hierClass) {
417422
$fileName = $hierClass->getFileName();
423+
$hierClassName = $hierClass->getName();
424+
$stubDoc = StubManager::getClassDoc($hierClassName);
418425

419-
if ($hierClass->getName() !== $actualClassName && FileFilter::isFileExcluded($fileName !== false ? $fileName : null)) {
426+
if ($stubDoc === null && $hierClass->getName() !== $actualClassName && FileFilter::isFileExcluded($fileName !== false ? $fileName : null)) {
420427
continue;
421428
}
422429

@@ -457,8 +464,9 @@ private static function collectDocsForClassHierarchyMember(\ReflectionClass $hie
457464
{
458465
$docs = [];
459466

460-
$classDoc = $hierClass->getDocComment();
461-
if ($classDoc !== false) {
467+
$stubDoc = StubManager::getClassDoc($hierClass->getName());
468+
$classDoc = $stubDoc ?? $hierClass->getDocComment();
469+
if ($classDoc !== false && $classDoc !== null) {
462470
$docs[] = $classDoc;
463471
}
464472

@@ -492,10 +500,11 @@ private static function bindInheritedGenericTag(
492500
}
493501

494502
try {
503+
$stubDoc = StubManager::getClassDoc($parentName);
495504
$parentRef = new \ReflectionClass($parentName);
496-
$parentDoc = $parentRef->getDocComment();
505+
$parentDoc = $stubDoc ?? $parentRef->getDocComment();
497506

498-
if ($parentDoc === false) {
507+
if ($parentDoc === false || $parentDoc === null) {
499508
return;
500509
}
501510

‎tests/Contract/DocblockExtractorTest.php‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
66
use TypePHP\Contract\DocblockExtractor;
7+
use TypePHP\Tests\Fixtures\Services\HelperService;
78
use TypePHP\Tests\Fixtures\Services\UserService;
89
use TypePHP\Tests\Fixtures\Shopware\Metric\Type as MetricTypeEnum;
910
use TypePHP\Tests\Fixtures\Types\NestedAliasChainedB;
@@ -252,4 +253,47 @@
252253

253254
expect($inherited)->toHaveCount(3);
254255
});
256+
257+
test('resolves imported type aliases defined inside stub files', function () {
258+
$tempDir = sys_get_temp_dir() . '/typephp_doc_stub_' . uniqid();
259+
mkdir($tempDir, 0777, true);
260+
261+
$stubPath = $tempDir . '/HelperService.stub';
262+
$stubContent = <<<'PHP'
263+
<?php
264+
265+
namespace TypePHP\Tests\Fixtures\Services;
266+
267+
/**
268+
* @phpstan-type StubbedUserShape array{id: positive-int, username: non-empty-string}
269+
*/
270+
class HelperService
271+
{
272+
}
273+
PHP;
274+
file_put_contents($stubPath, $stubContent);
275+
276+
try {
277+
TypePHP\Internal\Config::set([
278+
'stubs' => [
279+
str_replace('\\', '/', $tempDir) . '/**',
280+
],
281+
]);
282+
283+
$resolved = DocblockExtractor::resolveImportedTypeAlias(HelperService::class, 'StubbedUserShape');
284+
285+
expect($resolved)->not()->toBeNull()
286+
->and((string) $resolved)->toContain('positive-int')
287+
->and((string) $resolved)->toContain('non-empty-string')
288+
;
289+
} finally {
290+
if (file_exists($stubPath)) {
291+
@unlink($stubPath);
292+
}
293+
if (is_dir($tempDir)) {
294+
@rmdir($tempDir);
295+
}
296+
TypePHP\Internal\Config::reset();
297+
}
298+
});
255299
});

‎tests/TypeChecking/Stubs/StubSystemTest.php‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,4 +357,61 @@ public function getConfig(): array
357357
}
358358
}
359359
});
360+
361+
test('resolves @phpstan-import-type imported from a stubbed vendor class at runtime', function () {
362+
$tempDir = sys_get_temp_dir() . '/typephp_stub_import_type_' . uniqid();
363+
mkdir($tempDir, 0777, true);
364+
365+
$stubPath = $tempDir . '/SimulatedVendorParent.stub';
366+
$stubContent = <<<'PHP'
367+
<?php
368+
369+
namespace TypePHP\Tests\Fixtures\Liskov;
370+
371+
/**
372+
* @phpstan-type VendorConfig array{apiKey: non-empty-string, retries: positive-int}
373+
*/
374+
class SimulatedVendorParent
375+
{
376+
}
377+
PHP;
378+
file_put_contents($stubPath, $stubContent);
379+
380+
try {
381+
Config::set([
382+
'stubs' => [
383+
str_replace('\\', '/', $tempDir) . '/**',
384+
],
385+
]);
386+
387+
$consumer = new class () {
388+
/**
389+
* @phpstan-import-type VendorConfig from SimulatedVendorParent as AppConfig
390+
*
391+
* @param AppConfig $config
392+
*/
393+
public function initialize(array $config): bool
394+
{
395+
return true;
396+
}
397+
};
398+
399+
expect($consumer->initialize(['apiKey' => 'sec_123', 'retries' => 3]))->toBeTrue();
400+
401+
expect(fn () => $consumer->initialize(['apiKey' => '', 'retries' => 3]))
402+
->toThrow(TypeError::class, "['apiKey'] must be of type non-empty-string")
403+
;
404+
405+
expect(fn () => $consumer->initialize(['apiKey' => 'sec_123', 'retries' => -1]))
406+
->toThrow(TypeError::class, "['retries'] must be of type positive-int")
407+
;
408+
} finally {
409+
if (file_exists($stubPath)) {
410+
@unlink($stubPath);
411+
}
412+
if (is_dir($tempDir)) {
413+
@rmdir($tempDir);
414+
}
415+
}
416+
});
360417
});

0 commit comments

Comments
 (0)