Skip to content

Commit

Permalink
Added the resolution of class names of PHPDoc for SchemaClassDocRefle…
Browse files Browse the repository at this point in the history
…ctor (#605)

* added the resolution of names in PHPDoc for SchemaClassDocReflector

* Fix styling

---------

Co-authored-by: romalytvynenko <[email protected]>
  • Loading branch information
romalytvynenko and romalytvynenko authored Oct 27, 2024
1 parent 1a7547b commit d32b280
Showing 1 changed file with 44 additions and 5 deletions.
49 changes: 44 additions & 5 deletions src/Support/SchemaClassDocReflector.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@

namespace Dedoc\Scramble\Support;

use Dedoc\Scramble\Infer\Reflector\ClassReflector;
use Dedoc\Scramble\Infer\Services\FileNameResolver;
use Dedoc\Scramble\PhpDoc\PhpDocTypeWalker;
use Dedoc\Scramble\PhpDoc\ResolveFqnPhpDocTypeVisitor;
use PhpParser\NameContext;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
use ReflectionClass;

class SchemaClassDocReflector
{
Expand Down Expand Up @@ -33,15 +37,50 @@ static function (PhpDocChildNode $child): string {
)));
}

public static function createFromDocString(string $phpDocString)
public static function createFromDocString(string $phpDocString, ?string $definingClassName = null)
{
return new self(PhpDoc::parse($phpDocString ?: '/** */'));
$parsedDoc = PhpDoc::parse($phpDocString ?: '/** */');

if ($definingClassName) {
$classReflector = ClassReflector::make($definingClassName);

$nameContext = $classReflector->getNameContext();

$parsedDoc = static::replaceClassNamesInDoc($parsedDoc, $nameContext);
}

return new self($parsedDoc);
}

public static function createFromClassName(string $className)
{
$reflection = new ReflectionClass($className);
$classReflector = ClassReflector::make($className);

$nameContext = $classReflector->getNameContext();
$reflection = $classReflector->getReflection();

$parsedDoc = static::replaceClassNamesInDoc(PhpDoc::parse($reflection->getDocComment() ?: '/** */'), $nameContext);

return new self($parsedDoc);
}

private static function replaceClassNamesInDoc(PhpDocNode $docNode, NameContext $nameContext): PhpDocNode
{
$tagValues = [
...$docNode->getReturnTagValues(),
...$docNode->getVarTagValues(),
...$docNode->getThrowsTagValues(),
];

foreach ($tagValues as $tagValue) {
if (! $tagValue->type) {
continue;
}
PhpDocTypeWalker::traverse($tagValue->type, [
new ResolveFqnPhpDocTypeVisitor(new FileNameResolver($nameContext)),
]);
}

return new self(PhpDoc::parse($reflection->getDocComment() ?: '/** */'));
return $docNode;
}
}

0 comments on commit d32b280

Please sign in to comment.