Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/Analyser/RuleErrorTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,12 +246,14 @@ private function fix(string $fixingFile, array $fileNodes, array $fixes): ?Fixed
return null;
}

$nameResolver = new NameResolver(new Collecting(), ['replaceNodes' => false]);
/** @var Stmt[] $newStmts */
$newStmts = (new NodeTraverser(
$nameResolver,
new NewClassNamesVisitor($nameResolver->getNameContext(), $this->importNames, $this->preferSelf),
))->traverse($newStmts);
if (NewClassNamesVisitor::hasWork($replacingVisitor->getFixedNodes())) {
$nameResolver = new NameResolver(new Collecting(), ['replaceNodes' => false]);
/** @var Stmt[] $newStmts */
$newStmts = (new NodeTraverser(
$nameResolver,
new NewClassNamesVisitor($nameResolver->getNameContext(), $this->importNames, $this->preferSelf),
))->traverse($newStmts);
}

$newCode = $this->getPrinter($indent)->printFormatPreserving($newStmts, $fileNodes, $parsedFile['tokens']);
if ($parsedFile['code'] === $newCode) {
Expand Down
25 changes: 25 additions & 0 deletions src/Fixable/NewClassNamesVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,31 @@ public function __construct(
$this->phpDocParser = new PhpDocParser($config, new TypeParser($config, $constExprParser), $constExprParser);
}

/**
* Whether the nodes that the fixes returned contain a class name
* or a PHPDoc that this visitor may need to write.
*
* @param Node[] $fixedNodes
*/
public static function hasWork(array $fixedNodes): bool
{
return (new NodeFinder())->findFirst($fixedNodes, static function (Node $node): bool {
$originalNode = $node->getAttribute('origNode');
if ($node instanceof FullyQualified && $originalNode === null) {
return true;
}

$doc = $node->getDocComment();
if ($doc === null) {
return false;
}

$originalDoc = $originalNode instanceof Node ? $originalNode->getDocComment() : null;

return $originalDoc === null || $originalDoc->getText() !== $doc->getText();
}) !== null;
}

#[Override]
public function beforeTraverse(array $nodes): ?array
{
Expand Down
15 changes: 15 additions & 0 deletions src/Fixable/ReplacingNodeVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ final class ReplacingNodeVisitor extends NodeVisitorAbstract

private bool $failed = false;

/** @var list<Node> */
private array $fixedNodes = [];

/**
* @param non-empty-list<NodeFix> $fixes
*/
Expand Down Expand Up @@ -115,9 +118,21 @@ public function leaveNode(Node $node): Node|int|null
}
}

$this->fixedNodes[] = $newNode;

return $newNode;
}

/**
* Nodes returned by the fixes. A fix changes only these nodes and their children.
*
* @return list<Node>
*/
public function getFixedNodes(): array
{
return $this->fixedNodes;
}

/**
* Whether every node was found and fixed.
*/
Expand Down
22 changes: 16 additions & 6 deletions tests/PHPStan/Fixable/AddNamesRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function count;
use function in_array;
use function preg_match_all;
use function sprintf;

/**
* Turns each `@add-name \Some\Class` tag into a native parameter type
* and a `@param` tag, to show new names are written the same way
* in PHP code and in PHPDocs.
* in PHP code and in PHPDocs. An `@add-doc-name \Some\Class` tag becomes
* only a `@param` tag.
*
* @implements Rule<Node\Stmt\ClassMethod>
*/
Expand All @@ -37,19 +39,27 @@ public function getNodeType(): string
public function processNode(Node $node, Scope $scope): array
{
$docComment = $node->getDocComment();
if ($docComment === null || preg_match_all('/@add-name\s+\\\\?(\S+)/', $docComment->getText(), $matches) === 0) {
if ($docComment === null || preg_match_all('/@add-(doc-)?name\s+\\\\?(\S+)/', $docComment->getText(), $matches) === 0) {
return [];
}

$names = $matches[1];
$names = $matches[2];
$parameterNames = [];
foreach ($matches[1] as $j => $docOnly) {
if ($docOnly !== '') {
continue;
}

$parameterNames[] = $names[$j];
}

return [
RuleErrorBuilder::message(sprintf('Adding %d names.', count($names)))
->identifier('tests.addNames')
->fixNode($node, function (Node\Stmt\ClassMethod $method) use ($names) {
->fixNode($node, function (Node\Stmt\ClassMethod $method) use ($parameterNames) {
$i = 0;
$this->phpDocEditor->edit($method, static function (\PHPStan\PhpDocParser\Ast\Node $phpDocNode) use (&$i) {
if (!$phpDocNode instanceof PhpDocTagNode || $phpDocNode->name !== '@add-name') {
if (!$phpDocNode instanceof PhpDocTagNode || !in_array($phpDocNode->name, ['@add-name', '@add-doc-name'], true)) {
return null;
}

Expand All @@ -64,7 +74,7 @@ public function processNode(Node $node, Scope $scope): array
));
});

foreach ($names as $j => $name) {
foreach ($parameterNames as $j => $name) {
$method->params[] = new Node\Param(
new Node\Expr\Variable('p' . ($j + 1)),
type: new FullyQualified($name),
Expand Down
5 changes: 5 additions & 0 deletions tests/PHPStan/Fixable/AddNamesRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,9 @@ public function testFixSortedUses(): void
$this->fix(__DIR__ . '/data/add-names-sorted-uses.php', __DIR__ . '/data/add-names-sorted-uses.php.fixed');
}

public function testFixPhpDocOnly(): void
{
$this->fix(__DIR__ . '/data/add-names-phpdoc-only.php', __DIR__ . '/data/add-names-phpdoc-only.php.fixed');
}

}
97 changes: 97 additions & 0 deletions tests/PHPStan/Fixable/NewClassNamesVisitorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php declare(strict_types = 1);

namespace PHPStan\Fixable;

use PhpParser\Comment\Doc;
use PhpParser\Node;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\NodeFinder;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\CloningVisitor;
use PhpParser\ParserFactory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

class NewClassNamesVisitorTest extends TestCase
{

private const CODE = <<<'PHP'
<?php

namespace HasWork;

class Foo
{

/** @return int */
#[\Override]
public function doFoo(\Bar\Baz $baz): int
{
return strlen('');
}

}
PHP;

/**
* @return iterable<string, array{callable(ClassMethod): Node, bool}>
*/
public static function dataHasWork(): iterable
{
yield 'unchanged' => [
static fn (ClassMethod $method): Node => $method,
false,
];

yield 'removed attribute' => [
static function (ClassMethod $method): Node {
$method->attrGroups = [];
return $method;
},
false,
];

yield 'added name' => [
static function (ClassMethod $method): Node {
$method->params[] = new Node\Param(new Node\Expr\Variable('qux'), type: new FullyQualified('Qux\Quux'));
return $method;
},
true,
];

yield 'changed PHPDoc' => [
static function (ClassMethod $method): Node {
$method->setDocComment(new Doc('/** @return positive-int */'));
return $method;
},
true,
];

yield 'new node with a PHPDoc' => [
static function (ClassMethod $method): Node {
$newMethod = new ClassMethod('doBar');
$newMethod->setDocComment(new Doc('/** @return void */'));
return $newMethod;
},
true,
];
}

/**
* @param callable(ClassMethod): Node $fix
*/
#[DataProvider('dataHasWork')]
public function testHasWork(callable $fix, bool $expected): void
{
$stmts = (new ParserFactory())->createForHostVersion()->parse(self::CODE);
$this->assertNotNull($stmts);

$newStmts = (new NodeTraverser(new CloningVisitor()))->traverse($stmts);
$method = (new NodeFinder())->findFirstInstanceOf($newStmts, ClassMethod::class);
$this->assertNotNull($method);

$this->assertSame($expected, NewClassNamesVisitor::hasWork([$fix($method)]));
}

}
18 changes: 18 additions & 0 deletions tests/PHPStan/Fixable/data/add-names-phpdoc-only.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace AddNamesPhpDocOnly;

use AddNamesImported\Foo;

class Bar
{

/**
* @add-doc-name \AddNamesImported\Foo
* @add-doc-name \AddNamesOther\AddNamesUnique
*/
public function doFoo($p1, $p2): void
{
}

}
19 changes: 19 additions & 0 deletions tests/PHPStan/Fixable/data/add-names-phpdoc-only.php.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace AddNamesPhpDocOnly;

use AddNamesImported\Foo;
use AddNamesOther\AddNamesUnique;

class Bar
{

/**
* @param Foo $p1
* @param AddNamesUnique $p2
*/
public function doFoo($p1, $p2): void
{
}

}
Loading