From 2f3e9be0ae108c75f9de8fbf2ea92f0393ad9839 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Thu, 8 Jun 2023 16:18:48 +0200 Subject: [PATCH] [DX] Test BetterNodeFinder with Laravel container (#4106) --- composer.json | 1 + .../CommentRemover/CommentRemoverTest.php | 9 +- .../Error/InvalidNameNodeReporter.php | 90 ------------------- .../NodeNameResolver/NodeNameResolver.php | 10 +-- .../Testing/PHPUnit/AbstractLazyTestCase.php | 22 +++++ phpstan.neon | 2 + .../ClassMethod/ArgumentAdderRector.php | 6 +- .../If_/SimplifyIfElseToTernaryRector.php | 6 +- .../Rector/If_/SimplifyIfReturnBoolRector.php | 6 +- .../NodeAnalyzer/ExprUsedInNodeAnalyzer.php | 6 +- .../Array_/RemoveDuplicatedArrayKeyRector.php | 6 +- .../SimplifyIfElseWithSameContentRector.php | 10 +-- .../Assign/ListSwapArrayOrderRector.php | 6 +- .../TryCatch/MultiExceptionCatchRector.php | 6 +- ...AddParamBasedOnParentClassMethodRector.php | 8 +- ...urnedNodesReturnTypeInfererTypeInferer.php | 8 +- .../Parameter/ParameterProvider.php | 8 +- src/Configuration/RectorConfigProvider.php | 2 +- .../PhpParser/NodePrinterInterface.php | 29 ------ src/Kernel/RectorKernel.php | 2 +- src/PhpParser/Comparing/NodeComparator.php | 10 +-- src/PhpParser/Node/BetterNodeFinder.php | 2 + src/PhpParser/Parser/InlineCodeParser.php | 8 +- .../Printer/BetterStandardPrinter.php | 3 +- .../NodesWithFileDestinationPrinter.php | 5 +- .../BetterNodeFinder/BetterNodeFinderTest.php | 10 +-- 26 files changed, 90 insertions(+), 191 deletions(-) delete mode 100644 packages/NodeNameResolver/Error/InvalidNameNodeReporter.php create mode 100644 packages/Testing/PHPUnit/AbstractLazyTestCase.php delete mode 100644 src/Contract/PhpParser/NodePrinterInterface.php diff --git a/composer.json b/composer.json index d7d5880f36a..15e291b7635 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ "composer/xdebug-handler": "^3.0.3", "doctrine/inflector": "^2.0.6", "fidry/cpu-core-counter": "^0.5.1", + "illuminate/container": "^10.13", "nette/neon": "^3.4", "nette/utils": "^3.2", "nikic/php-parser": "^4.15.4", diff --git a/packages-tests/Comments/CommentRemover/CommentRemoverTest.php b/packages-tests/Comments/CommentRemover/CommentRemoverTest.php index 89735c99fe6..268cc3a784c 100644 --- a/packages-tests/Comments/CommentRemover/CommentRemoverTest.php +++ b/packages-tests/Comments/CommentRemover/CommentRemoverTest.php @@ -7,7 +7,6 @@ use Iterator; use PHPUnit\Framework\Attributes\DataProvider; use Rector\Comments\CommentRemover; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\FileSystemRector\Parser\FileInfoParser; use Rector\Testing\Fixture\FixtureFileFinder; @@ -21,7 +20,7 @@ final class CommentRemoverTest extends AbstractTestCase private FileInfoParser $fileInfoParser; - private NodePrinterInterface $nodePrinter; + private BetterStandardPrinter $betterStandardPrinter; protected function setUp(): void { @@ -29,7 +28,7 @@ protected function setUp(): void $this->commentRemover = $this->getService(CommentRemover::class); $this->fileInfoParser = $this->getService(FileInfoParser::class); - $this->nodePrinter = $this->getService(BetterStandardPrinter::class); + $this->betterStandardPrinter = $this->getService(BetterStandardPrinter::class); } #[DataProvider('provideData')] @@ -41,14 +40,14 @@ public function test(string $filePath): void $nodes = $this->fileInfoParser->parseFileInfoToNodesAndDecorate($inputFilePath); $nodesWithoutComments = $this->commentRemover->removeFromNode($nodes); - $fileContent = $this->nodePrinter->print($nodesWithoutComments); + $fileContent = $this->betterStandardPrinter->print($nodesWithoutComments); $fileContent = trim($fileContent); $expectedContent = trim((string) $expectedOutputContents); $this->assertSame($fileContent, $expectedContent); // original nodes are not touched - $originalContent = $this->nodePrinter->print($nodes); + $originalContent = $this->betterStandardPrinter->print($nodes); $this->assertNotSame($expectedContent, $originalContent); } diff --git a/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php b/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php deleted file mode 100644 index 88d2db3c28b..00000000000 --- a/packages/NodeNameResolver/Error/InvalidNameNodeReporter.php +++ /dev/null @@ -1,90 +0,0 @@ -name"', $node::class); - - $file = $this->currentFileProvider->getFile(); - - if ($file instanceof File) { - $message .= PHP_EOL . PHP_EOL; - - $relativeFilePath = $this->filePathHelper->relativePath($file->getFilePath()); - - $message .= sprintf( - 'Caused in "%s" file on line %d on code "%s"', - $relativeFilePath, - $node->getStartLine(), - $this->nodePrinter->print($node) - ); - } - - $backtrace = debug_backtrace(); - $rectorBacktrace = $this->matchRectorBacktraceCall($backtrace); - - if ($rectorBacktrace !== null) { - // issues to find the file in prefixed - if (file_exists($rectorBacktrace[self::FILE])) { - $filePath = $rectorBacktrace[self::FILE]; - $relativeFilePath = $this->filePathHelper->relativePath($filePath); - $fileAndLine = $relativeFilePath . ':' . $rectorBacktrace['line']; - } else { - $fileAndLine = $rectorBacktrace[self::FILE] . ':' . $rectorBacktrace['line']; - } - - $message .= PHP_EOL . PHP_EOL; - $message .= sprintf('Look at "%s"', $fileAndLine); - } - - throw new ShouldNotHappenException($message); - } - - /** - * @param mixed[] $backtrace - * @return string[]|null - */ - private function matchRectorBacktraceCall(array $backtrace): ?array - { - foreach ($backtrace as $singleBacktrace) { - if (! isset($singleBacktrace['object'])) { - continue; - } - - // match a Rector class - if (! is_a($singleBacktrace['object'], RectorInterface::class)) { - continue; - } - - return $singleBacktrace; - } - - return $backtrace[1] ?? null; - } -} diff --git a/packages/NodeNameResolver/NodeNameResolver.php b/packages/NodeNameResolver/NodeNameResolver.php index c89618c8cfc..5d790971ee4 100644 --- a/packages/NodeNameResolver/NodeNameResolver.php +++ b/packages/NodeNameResolver/NodeNameResolver.php @@ -17,7 +17,6 @@ use Rector\Core\NodeAnalyzer\CallAnalyzer; use Rector\Core\Util\StringUtils; use Rector\NodeNameResolver\Contract\NodeNameResolverInterface; -use Rector\NodeNameResolver\Error\InvalidNameNodeReporter; use Rector\NodeNameResolver\Regex\RegexPatternDetector; use Rector\NodeTypeResolver\Node\AttributeKey; @@ -42,7 +41,6 @@ final class NodeNameResolver public function __construct( private readonly RegexPatternDetector $regexPatternDetector, private readonly ClassNaming $classNaming, - private readonly InvalidNameNodeReporter $invalidNameNodeReporter, private readonly CallAnalyzer $callAnalyzer, private readonly array $nodeNameResolvers = [] ) { @@ -123,12 +121,8 @@ public function getName(Node | string $node): ?string return $namespacedName; } - if ($node instanceof MethodCall || $node instanceof StaticCall) { - if ($this->isCallOrIdentifier($node->name)) { - return null; - } - - $this->invalidNameNodeReporter->reportInvalidNodeForName($node); + if (($node instanceof MethodCall || $node instanceof StaticCall) && $this->isCallOrIdentifier($node->name)) { + return null; } $scope = $node->getAttribute(AttributeKey::SCOPE); diff --git a/packages/Testing/PHPUnit/AbstractLazyTestCase.php b/packages/Testing/PHPUnit/AbstractLazyTestCase.php new file mode 100644 index 00000000000..2880c2b1f86 --- /dev/null +++ b/packages/Testing/PHPUnit/AbstractLazyTestCase.php @@ -0,0 +1,22 @@ + $class + * @return TType + */ + protected function make(string $class): object + { + $container = new Container(); + return $container->make($class); + } +} diff --git a/phpstan.neon b/phpstan.neon index 9b43a8a3412..0a9162ffd06 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -719,6 +719,8 @@ parameters: - '#Cognitive complexity for "Rector\\(.*?)\:\:refactor\(\)" is (1[0-9]|20), keep it under 11#' - '#Cognitive complexity for "Rector\\DeadCode\\Rector\\StaticCall\\RemoveParentCallWithoutParentRector\:\:refactor\(\)" is 26, keep it under 11#' + - '#Call to deprecated method findFirstPrevious\(\) of class Rector\\Core\\PhpParser\\Node\\BetterNodeFinder#' + - '#Return type (.*?) should be covariant with return type \(1\|2\|3\|4\|array\|PhpParser\\Node\|null\) of method Rector\\Core\\Contract\\Rector(.*?)\:\:(.*?)#' # false positive diff --git a/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php b/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php index a8341e57952..6365495dbe5 100644 --- a/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php +++ b/rules/Arguments/Rector/ClassMethod/ArgumentAdderRector.php @@ -21,11 +21,11 @@ use Rector\Arguments\NodeAnalyzer\ArgumentAddingScope; use Rector\Arguments\NodeAnalyzer\ChangedArgumentsDetector; use Rector\Arguments\ValueObject\ArgumentAdder; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\Contract\Rector\ConfigurableRectorInterface; use Rector\Core\Enum\ObjectReference; use Rector\Core\Exception\ShouldNotHappenException; use Rector\Core\PhpParser\AstResolver; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Rector\PHPStanStaticTypeMapper\Enum\TypeKind; use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample; @@ -48,7 +48,7 @@ public function __construct( private readonly ArgumentAddingScope $argumentAddingScope, private readonly ChangedArgumentsDetector $changedArgumentsDetector, private readonly AstResolver $astResolver, - private readonly NodePrinterInterface $nodePrinter + private readonly BetterStandardPrinter $betterStandardPrinter ) { } @@ -215,7 +215,7 @@ private function fillGapBetweenWithDefaultValue(MethodCall | StaticCall $node, i throw new ShouldNotHappenException('Previous position does not have default value'); } - $default = $this->nodePrinter->print($param->default); + $default = $this->betterStandardPrinter->print($param->default); $node->args[$index] = new Arg(new ConstFetch(new Name($default))); } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php index 216b6384b8c..37502da0500 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfElseToTernaryRector.php @@ -13,7 +13,7 @@ use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\If_; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; @@ -29,7 +29,7 @@ final class SimplifyIfElseToTernaryRector extends AbstractRector private const LINE_LENGTH_LIMIT = 120; public function __construct( - private readonly NodePrinterInterface $nodePrinter + private readonly BetterStandardPrinter $betterStandardPrinter ) { } @@ -192,7 +192,7 @@ private function haveNestedTernary(array $nodes): bool private function isNodeTooLong(Assign $assign): bool { - $assignContent = $this->nodePrinter->print($assign); + $assignContent = $this->betterStandardPrinter->print($assign); return Strings::length($assignContent) > self::LINE_LENGTH_LIMIT; } } diff --git a/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php b/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php index 7d35637ca30..fee0152df06 100644 --- a/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php +++ b/rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php @@ -15,7 +15,7 @@ use Rector\BetterPhpDocParser\Comment\CommentsMerger; use Rector\CodeQuality\NodeManipulator\ExprBoolCaster; use Rector\Core\Contract\PhpParser\Node\StmtsAwareInterface; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; @@ -28,7 +28,7 @@ final class SimplifyIfReturnBoolRector extends AbstractRector public function __construct( private readonly CommentsMerger $commentsMerger, private readonly ExprBoolCaster $exprBoolCaster, - private readonly NodePrinterInterface $nodePrinter + private readonly BetterStandardPrinter $betterStandardPrinter ) { } @@ -146,7 +146,7 @@ private function shouldSkipIfAndReturn(If_ $if, Return_ $return): bool return ! $this->valueResolver->isTrueOrFalse($return->expr); } - $condString = $this->nodePrinter->print($if->cond); + $condString = $this->betterStandardPrinter->print($if->cond); if (! \str_contains($condString, '!=')) { return ! $this->valueResolver->isTrueOrFalse($return->expr); } diff --git a/rules/DeadCode/NodeAnalyzer/ExprUsedInNodeAnalyzer.php b/rules/DeadCode/NodeAnalyzer/ExprUsedInNodeAnalyzer.php index 0d5ffa435fe..daae0ac2774 100644 --- a/rules/DeadCode/NodeAnalyzer/ExprUsedInNodeAnalyzer.php +++ b/rules/DeadCode/NodeAnalyzer/ExprUsedInNodeAnalyzer.php @@ -8,15 +8,15 @@ use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\Include_; use PhpParser\Node\Expr\Variable; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\NodeAnalyzer\CompactFuncCallAnalyzer; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; final class ExprUsedInNodeAnalyzer { public function __construct( private readonly UsedVariableNameAnalyzer $usedVariableNameAnalyzer, private readonly CompactFuncCallAnalyzer $compactFuncCallAnalyzer, - private readonly NodePrinterInterface $nodePrinter + private readonly BetterStandardPrinter $betterStandardPrinter ) { } @@ -28,7 +28,7 @@ public function isUsed(Node $node, Variable $variable): bool // variable as variable variable need mark as used if ($node instanceof Variable) { - $print = $this->nodePrinter->print($node); + $print = $this->betterStandardPrinter->print($node); if (\str_starts_with($print, '${$')) { return true; } diff --git a/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php b/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php index 5cbb8e65861..6bc39c22b74 100644 --- a/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php +++ b/rules/DeadCode/Rector/Array_/RemoveDuplicatedArrayKeyRector.php @@ -10,7 +10,7 @@ use PhpParser\Node\Expr\ArrayItem; use PhpParser\Node\Expr\PreDec; use PhpParser\Node\Expr\PreInc; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Rector\Core\Util\MultiInstanceofChecker; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; @@ -28,7 +28,7 @@ final class RemoveDuplicatedArrayKeyRector extends AbstractRector private const ALLOWED_KEY_DUPLICATES = [PreInc::class, PreDec::class]; public function __construct( - private readonly NodePrinterInterface $nodePrinter, + private readonly BetterStandardPrinter $betterStandardPrinter, private readonly MultiInstanceofChecker $multiInstanceofChecker ) { } @@ -102,7 +102,7 @@ private function resolveDuplicateKeysArrayItems(Array_ $array): array continue; } - $keyValue = $this->nodePrinter->print($arrayItem->key); + $keyValue = $this->betterStandardPrinter->print($arrayItem->key); $arrayItemsByKeys[$keyValue][] = $arrayItem; } diff --git a/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php b/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php index 707d8423370..468e021d3c0 100644 --- a/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php +++ b/rules/DeadCode/Rector/If_/SimplifyIfElseWithSameContentRector.php @@ -8,8 +8,8 @@ use PhpParser\Node\Stmt; use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\If_; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\Exception\ShouldNotHappenException; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; @@ -20,7 +20,7 @@ final class SimplifyIfElseWithSameContentRector extends AbstractRector { public function __construct( - private readonly NodePrinterInterface $nodePrinter, + private readonly BetterStandardPrinter $betterStandardPrinter, ) { } @@ -83,10 +83,10 @@ public function refactor(Node $node): ?array private function isIfWithConstantReturns(If_ $if): bool { $possibleContents = []; - $possibleContents[] = $this->nodePrinter->print($if->stmts); + $possibleContents[] = $this->betterStandardPrinter->print($if->stmts); foreach ($if->elseifs as $elseif) { - $possibleContents[] = $this->nodePrinter->print($elseif->stmts); + $possibleContents[] = $this->betterStandardPrinter->print($elseif->stmts); } $else = $if->else; @@ -94,7 +94,7 @@ private function isIfWithConstantReturns(If_ $if): bool throw new ShouldNotHappenException(); } - $possibleContents[] = $this->nodePrinter->print($else->stmts); + $possibleContents[] = $this->betterStandardPrinter->print($else->stmts); $uniqueContents = array_unique($possibleContents); diff --git a/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php b/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php index 44ae09927b5..4f2033daaeb 100644 --- a/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php +++ b/rules/Php70/Rector/Assign/ListSwapArrayOrderRector.php @@ -11,7 +11,7 @@ use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\List_; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Rector\Core\ValueObject\PhpVersionFeature; use Rector\VersionBonding\Contract\MinPhpVersionInterface; @@ -25,7 +25,7 @@ final class ListSwapArrayOrderRector extends AbstractRector implements MinPhpVersionInterface { public function __construct( - private readonly NodePrinterInterface $nodePrinter + private readonly BetterStandardPrinter $betterStandardPrinter ) { } @@ -64,7 +64,7 @@ public function refactor(Node $node): ?Node } if ($arrayItem->value instanceof ArrayDimFetch && ! $arrayItem->value->dim instanceof Expr) { - $printedVariables[] = $this->nodePrinter->print($arrayItem->value->var); + $printedVariables[] = $this->betterStandardPrinter->print($arrayItem->value->var); } else { return null; } diff --git a/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php b/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php index f553e2548aa..d375ee89bed 100644 --- a/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php +++ b/rules/Php71/Rector/TryCatch/MultiExceptionCatchRector.php @@ -6,7 +6,7 @@ use PhpParser\Node; use PhpParser\Node\Stmt\TryCatch; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Rector\Core\ValueObject\PhpVersionFeature; use Rector\VersionBonding\Contract\MinPhpVersionInterface; @@ -21,7 +21,7 @@ final class MultiExceptionCatchRector extends AbstractRector implements MinPhpVersionInterface { public function __construct( - private readonly NodePrinterInterface $nodePrinter + private readonly BetterStandardPrinter $betterStandardPrinter ) { } @@ -74,7 +74,7 @@ public function refactor(Node $node): ?Node $hasChanged = false; foreach ($node->catches as $key => $catch) { - $currentPrintedCatch = $this->nodePrinter->print($catch->stmts); + $currentPrintedCatch = $this->betterStandardPrinter->print($catch->stmts); // already duplicated catch → remove it and join the type if (in_array($currentPrintedCatch, $printedCatches, true)) { diff --git a/rules/Php80/Rector/ClassMethod/AddParamBasedOnParentClassMethodRector.php b/rules/Php80/Rector/ClassMethod/AddParamBasedOnParentClassMethodRector.php index f6f1782e41f..c2ba821f9c2 100644 --- a/rules/Php80/Rector/ClassMethod/AddParamBasedOnParentClassMethodRector.php +++ b/rules/Php80/Rector/ClassMethod/AddParamBasedOnParentClassMethodRector.php @@ -15,8 +15,8 @@ use PhpParser\Node\Param; use PhpParser\Node\Stmt\ClassMethod; use PHPStan\Reflection\MethodReflection; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\PhpParser\AstResolver; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Rector\AbstractRector; use Rector\Core\ValueObject\MethodName; use Rector\Core\ValueObject\PhpVersionFeature; @@ -35,7 +35,7 @@ final class AddParamBasedOnParentClassMethodRector extends AbstractRector implem public function __construct( private readonly ParentClassMethodTypeOverrideGuard $parentClassMethodTypeOverrideGuard, private readonly AstResolver $astResolver, - private readonly NodePrinterInterface $nodePrinter, + private readonly BetterStandardPrinter $betterStandardPrinter, ) { } @@ -213,7 +213,7 @@ function (Node $subNode) use ($parentClassMethodParam): bool { $paramDefault = $parentClassMethodParam->default; if ($paramDefault instanceof Expr) { - $printParamDefault = $this->nodePrinter->print($paramDefault); + $printParamDefault = $this->betterStandardPrinter->print($paramDefault); $paramDefault = new ConstFetch(new Name($printParamDefault)); } @@ -231,7 +231,7 @@ function (Node $subNode) use ($parentClassMethodParam): bool { ); if ($parentClassMethodParam->attrGroups !== []) { - $attrGroupsAsComment = $this->nodePrinter->print($parentClassMethodParam->attrGroups); + $attrGroupsAsComment = $this->betterStandardPrinter->print($parentClassMethodParam->attrGroups); $node->params[$key]->setAttribute(AttributeKey::COMMENTS, [new Comment($attrGroupsAsComment)]); } } diff --git a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInfererTypeInferer.php b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInfererTypeInferer.php index 69d6b453b4b..bc2899c53b0 100644 --- a/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInfererTypeInferer.php +++ b/rules/TypeDeclaration/TypeInferer/ReturnTypeInferer/ReturnedNodesReturnTypeInfererTypeInferer.php @@ -19,9 +19,9 @@ use PHPStan\Type\MixedType; use PHPStan\Type\Type; use PHPStan\Type\VoidType; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\PhpParser\AstResolver; use Rector\Core\PhpParser\Node\BetterNodeFinder; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Reflection\ReflectionResolver; use Rector\NodeTypeResolver\NodeTypeResolver; use Rector\NodeTypeResolver\PHPStan\Type\TypeFactory; @@ -41,7 +41,7 @@ public function __construct( private readonly TypeFactory $typeFactory, private readonly SplArrayFixedTypeNarrower $splArrayFixedTypeNarrower, private readonly AstResolver $reflectionAstResolver, - private readonly NodePrinterInterface $nodePrinter, + private readonly BetterStandardPrinter $betterStandardPrinter, private readonly ReflectionResolver $reflectionResolver, private readonly BetterNodeFinder $betterNodeFinder, ) { @@ -185,8 +185,8 @@ private function resolveClassMethod(MethodReflection $methodReflection, Function return new MixedType(); } - $classMethodCacheKey = $this->nodePrinter->print($classMethod); - $functionLikeCacheKey = $this->nodePrinter->print($originalFunctionLike); + $classMethodCacheKey = $this->betterStandardPrinter->print($classMethod); + $functionLikeCacheKey = $this->betterStandardPrinter->print($originalFunctionLike); if ($classMethodCacheKey === $functionLikeCacheKey) { return new MixedType(); diff --git a/src/Configuration/Parameter/ParameterProvider.php b/src/Configuration/Parameter/ParameterProvider.php index 1f407376675..35835764f7c 100644 --- a/src/Configuration/Parameter/ParameterProvider.php +++ b/src/Configuration/Parameter/ParameterProvider.php @@ -41,11 +41,13 @@ public function provideParameter(string $name): mixed /** * @api */ - public function provideStringParameter(string $name): string + public function provideStringParameter(string $name, ?string $default = null): string { - $this->ensureParameterIsSet($name); + if ($default === null) { + $this->ensureParameterIsSet($name); + } - return (string) $this->parameters[$name]; + return (string) ($this->parameters[$name] ?? $default); } /** diff --git a/src/Configuration/RectorConfigProvider.php b/src/Configuration/RectorConfigProvider.php index d09235e3b2a..65ad3ce23ea 100644 --- a/src/Configuration/RectorConfigProvider.php +++ b/src/Configuration/RectorConfigProvider.php @@ -45,7 +45,7 @@ public function getSymfonyContainerXml(): string public function getIndentChar(): string { - return $this->parameterProvider->provideStringParameter(Option::INDENT_CHAR); + return $this->parameterProvider->provideStringParameter(Option::INDENT_CHAR, ' '); } public function getIndentSize(): int diff --git a/src/Contract/PhpParser/NodePrinterInterface.php b/src/Contract/PhpParser/NodePrinterInterface.php deleted file mode 100644 index 4d6fdbc6a9e..00000000000 --- a/src/Contract/PhpParser/NodePrinterInterface.php +++ /dev/null @@ -1,29 +0,0 @@ -commentRemover->removeFromNode($node); - $content = $this->nodePrinter->print($node); + $content = $this->betterStandardPrinter->print($node); return trim($content); } @@ -96,8 +96,8 @@ public function areSameNode(Node $firstNode, Node $secondNode): bool return false; } - $printFirstNode = $this->nodePrinter->print($firstNode); - $printSecondNode = $this->nodePrinter->print($secondNode); + $printFirstNode = $this->betterStandardPrinter->print($firstNode); + $printSecondNode = $this->betterStandardPrinter->print($secondNode); return $printFirstNode === $printSecondNode; } diff --git a/src/PhpParser/Node/BetterNodeFinder.php b/src/PhpParser/Node/BetterNodeFinder.php index 376f77cdeb1..ea030c9de5b 100644 --- a/src/PhpParser/Node/BetterNodeFinder.php +++ b/src/PhpParser/Node/BetterNodeFinder.php @@ -260,6 +260,8 @@ public function findPreviousAssignToExpr(Expr $expr): ?Node } /** + * @deprecated Use nodes directly + * * Search in previous Node/Stmt, when no Node found, lookup previous Stmt of Parent Node * * @param callable(Node $node): bool $filter diff --git a/src/PhpParser/Parser/InlineCodeParser.php b/src/PhpParser/Parser/InlineCodeParser.php index 8f4f9869de0..75a50ea91a9 100644 --- a/src/PhpParser/Parser/InlineCodeParser.php +++ b/src/PhpParser/Parser/InlineCodeParser.php @@ -12,9 +12,9 @@ use PhpParser\Node\Scalar\Encapsed; use PhpParser\Node\Scalar\String_; use PhpParser\Node\Stmt; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\PhpParser\Node\BetterNodeFinder; use Rector\Core\PhpParser\Node\Value\ValueResolver; +use Rector\Core\PhpParser\Printer\BetterStandardPrinter; use Rector\Core\Util\StringUtils; final class InlineCodeParser @@ -62,7 +62,7 @@ final class InlineCodeParser private const BACKREFERENCE_NO_DOUBLE_QUOTE_START_REGEX = '#(?\$\d+)#'; public function __construct( - private readonly NodePrinterInterface $nodePrinter, + private readonly BetterStandardPrinter $betterStandardPrinter, private readonly SimplePhpParser $simplePhpParser, private readonly ValueResolver $valueResolver, private readonly BetterNodeFinder $betterNodeFinder @@ -112,7 +112,7 @@ public function stringify(Expr $expr): string return $this->resolveConcatValue($expr); } - return $this->nodePrinter->print($expr); + return $this->betterStandardPrinter->print($expr); } private function resolveEncapsedValue(Encapsed $encapsed): string @@ -129,7 +129,7 @@ private function resolveEncapsedValue(Encapsed $encapsed): string $value .= $partValue; } - $printedExpr = $isRequirePrint ? $this->nodePrinter->print($encapsed) : $value; + $printedExpr = $isRequirePrint ? $this->betterStandardPrinter->print($encapsed) : $value; // remove " $printedExpr = trim($printedExpr, '""'); diff --git a/src/PhpParser/Printer/BetterStandardPrinter.php b/src/PhpParser/Printer/BetterStandardPrinter.php index 09b8c839632..606513d7a8d 100644 --- a/src/PhpParser/Printer/BetterStandardPrinter.php +++ b/src/PhpParser/Printer/BetterStandardPrinter.php @@ -29,7 +29,6 @@ use PhpParser\PrettyPrinter\Standard; use Rector\Comments\NodeDocBlock\DocBlockUpdater; use Rector\Core\Configuration\RectorConfigProvider; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\Core\PhpParser\Node\CustomNode\FileWithoutNamespace; use Rector\Core\Util\StringUtils; use Rector\NodeTypeResolver\Node\AttributeKey; @@ -39,7 +38,7 @@ * * @property array $insertionMap */ -final class BetterStandardPrinter extends Standard implements NodePrinterInterface +final class BetterStandardPrinter extends Standard { /** * @var string diff --git a/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php b/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php index 3732f880886..48c4674a688 100644 --- a/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php +++ b/src/PhpParser/Printer/NodesWithFileDestinationPrinter.php @@ -4,14 +4,13 @@ namespace Rector\Core\PhpParser\Printer; -use Rector\Core\Contract\PhpParser\NodePrinterInterface; use Rector\FileSystemRector\ValueObject\AddedFileWithNodes; use Rector\PostRector\Application\PostFileProcessor; final class NodesWithFileDestinationPrinter { public function __construct( - private readonly NodePrinterInterface $nodePrinter, + private readonly BetterStandardPrinter $betterStandardPrinter, private readonly PostFileProcessor $postFileProcessor ) { } @@ -19,6 +18,6 @@ public function __construct( public function printNodesWithFileDestination(AddedFileWithNodes $addedFileWithNodes): string { $nodes = $this->postFileProcessor->traverse($addedFileWithNodes->getNodes()); - return $this->nodePrinter->prettyPrintFile($nodes); + return $this->betterStandardPrinter->prettyPrintFile($nodes); } } diff --git a/tests/PhpParser/Node/BetterNodeFinder/BetterNodeFinderTest.php b/tests/PhpParser/Node/BetterNodeFinder/BetterNodeFinderTest.php index 38513297fbb..7b1075e33c0 100644 --- a/tests/PhpParser/Node/BetterNodeFinder/BetterNodeFinderTest.php +++ b/tests/PhpParser/Node/BetterNodeFinder/BetterNodeFinderTest.php @@ -11,9 +11,9 @@ use PhpParser\Node\Stmt\ClassLike; use Rector\Core\PhpParser\Node\BetterNodeFinder; use Rector\Core\PhpParser\Parser\SimplePhpParser; -use Rector\Testing\PHPUnit\AbstractTestCase; +use Rector\Testing\PHPUnit\AbstractLazyTestCase; -final class BetterNodeFinderTest extends AbstractTestCase +final class BetterNodeFinderTest extends AbstractLazyTestCase { /** * @var Node[] @@ -24,11 +24,9 @@ final class BetterNodeFinderTest extends AbstractTestCase protected function setUp(): void { - $this->boot(); + $this->betterNodeFinder = $this->make(BetterNodeFinder::class); - $this->betterNodeFinder = $this->getService(BetterNodeFinder::class); - - $simplePhpParser = $this->getService(SimplePhpParser::class); + $simplePhpParser = $this->make(SimplePhpParser::class); $this->nodes = $simplePhpParser->parseFile(__DIR__ . '/Source/SomeFile.php.inc'); }