diff --git a/.travis.yml b/.travis.yml index b6da2055a475..097e42b1347b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,8 +22,6 @@ matrix: env: CODING_STANDARD=true - php: '7.2' env: STANDALONE=true - - php: '7.3' - env: DOG_FOOD=true install: - composer update $COMPOSER_FLAGS diff --git a/composer.json b/composer.json index 37b7515ff6ae..c10f151ceacf 100644 --- a/composer.json +++ b/composer.json @@ -200,7 +200,7 @@ "bin/rector dump-rectors -o markdown > docs/AllRectorsOverview.md", "bin/rector dump-nodes -o markdown > docs/NodesOverview.md" ], - "rector": "bin/rector process packages src --config rector-ci.yaml --dry-run" + "rector": "bin/rector process packages src tests --config rector-ci.yaml --dry-run" }, "scripts-descriptions": { "docs": "Regenerate descriptions of all Rectors to docs/AllRectorsOverview.md file" diff --git a/packages/BetterPhpDocParser/config/config.yaml b/packages/BetterPhpDocParser/config/config.yaml index 7052e96f2fe2..e83f994a95b7 100644 --- a/packages/BetterPhpDocParser/config/config.yaml +++ b/packages/BetterPhpDocParser/config/config.yaml @@ -14,3 +14,6 @@ services: PHPStan\PhpDocParser\Parser\PhpDocParser: alias: 'Rector\BetterPhpDocParser\PhpDocParser\BetterPhpDocParser' + + Doctrine\Common\Annotations\Reader: + alias: 'Doctrine\Common\Annotations\AnnotationReader' diff --git a/packages/BetterPhpDocParser/src/AnnotationReader/AnnotationReaderFactory.php b/packages/BetterPhpDocParser/src/AnnotationReader/AnnotationReaderFactory.php index ec90bb42d1a7..38223d77b4d0 100644 --- a/packages/BetterPhpDocParser/src/AnnotationReader/AnnotationReaderFactory.php +++ b/packages/BetterPhpDocParser/src/AnnotationReader/AnnotationReaderFactory.php @@ -6,10 +6,11 @@ use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; +use Doctrine\Common\Annotations\Reader; final class AnnotationReaderFactory { - public function create(): AnnotationReader + public function create(): Reader { AnnotationRegistry::registerLoader('class_exists'); diff --git a/packages/BetterPhpDocParser/src/AnnotationReader/NodeAnnotationReader.php b/packages/BetterPhpDocParser/src/AnnotationReader/NodeAnnotationReader.php index c15fa846a688..7d49d2e7713c 100644 --- a/packages/BetterPhpDocParser/src/AnnotationReader/NodeAnnotationReader.php +++ b/packages/BetterPhpDocParser/src/AnnotationReader/NodeAnnotationReader.php @@ -5,8 +5,7 @@ namespace Rector\BetterPhpDocParser\AnnotationReader; use Doctrine\Common\Annotations\AnnotationException; -use Doctrine\Common\Annotations\AnnotationReader; -use Doctrine\ORM\Mapping\Annotation; +use Doctrine\Common\Annotations\Reader; use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Property; @@ -16,24 +15,23 @@ use ReflectionClass; use ReflectionMethod; use ReflectionProperty; -use Symfony\Component\Validator\Constraint; use Throwable; final class NodeAnnotationReader { /** - * @var AnnotationReader + * @var Reader */ - private $annotationReader; + private $reader; /** * @var NameResolver */ private $nameResolver; - public function __construct(AnnotationReader $annotationReader, NameResolver $nameResolver) + public function __construct(Reader $reader, NameResolver $nameResolver) { - $this->annotationReader = $annotationReader; + $this->reader = $reader; $this->nameResolver = $nameResolver; } @@ -51,7 +49,7 @@ public function readMethodAnnotation(ClassMethod $classMethod, string $annotatio $reflectionMethod = new ReflectionMethod($className, $methodName); try { - return $this->annotationReader->getMethodAnnotation($reflectionMethod, $annotationClassName); + return $this->reader->getMethodAnnotation($reflectionMethod, $annotationClassName); } catch (AnnotationException $annotationException) { // unable to laod return null; @@ -65,11 +63,11 @@ public function readClassAnnotation(Class_ $class, string $annotationClassName) { $classReflection = $this->createClassReflectionFromNode($class); - return $this->annotationReader->getClassAnnotation($classReflection, $annotationClassName); + return $this->reader->getClassAnnotation($classReflection, $annotationClassName); } /** - * @return Annotation|Constraint|null + * @return object|null */ public function readPropertyAnnotation(Property $property, string $annotationClassName) { @@ -78,13 +76,7 @@ public function readPropertyAnnotation(Property $property, string $annotationCla return null; } - /** @var Annotation|null $propertyAnnotation */ - $propertyAnnotation = $this->annotationReader->getPropertyAnnotation($propertyReflection, $annotationClassName); - if ($propertyAnnotation === null) { - return null; - } - - return $propertyAnnotation; + return $this->reader->getPropertyAnnotation($propertyReflection, $annotationClassName); } private function createClassReflectionFromNode(Class_ $class): ReflectionClass diff --git a/packages/BetterPhpDocParser/src/PhpDocNode/Symfony/SymfonyRouteTagValueNode.php b/packages/BetterPhpDocParser/src/PhpDocNode/Symfony/SymfonyRouteTagValueNode.php index 01c3047c4347..897c0d62f0da 100644 --- a/packages/BetterPhpDocParser/src/PhpDocNode/Symfony/SymfonyRouteTagValueNode.php +++ b/packages/BetterPhpDocParser/src/PhpDocNode/Symfony/SymfonyRouteTagValueNode.php @@ -100,19 +100,19 @@ public function __toString(): string $contentItems['name'] = sprintf('name="%s"', $this->name); } - if ($this->methods) { + if ($this->methods !== []) { $contentItems['methods'] = $this->printArrayItem($this->methods, 'methods'); } - if ($this->options) { + if ($this->options !== []) { $contentItems['options'] = $this->printArrayItem($this->options, 'options'); } - if ($this->defaults) { + if ($this->defaults !== []) { $contentItems['defaults'] = $this->printArrayItem($this->defaults, 'defaults'); } - if ($this->requirements) { + if ($this->requirements !== []) { $contentItems['requirements'] = $this->printArrayItem($this->requirements, 'requirements'); } diff --git a/packages/BetterPhpDocParser/src/PhpDocNodeFactory/JMS/JMSInjectPhpDocNodeFactory.php b/packages/BetterPhpDocParser/src/PhpDocNodeFactory/JMS/JMSInjectPhpDocNodeFactory.php index f0e817bba5b3..56286e39aede 100644 --- a/packages/BetterPhpDocParser/src/PhpDocNodeFactory/JMS/JMSInjectPhpDocNodeFactory.php +++ b/packages/BetterPhpDocParser/src/PhpDocNodeFactory/JMS/JMSInjectPhpDocNodeFactory.php @@ -45,11 +45,7 @@ public function createFromNodeAndTokens(Node $node, TokenIterator $tokenIterator return null; } - if ($inject->value === null) { - $serviceName = $this->nameResolver->getName($node); - } else { - $serviceName = $inject->value; - } + $serviceName = $inject->value === null ? $this->nameResolver->getName($node) : $inject->value; // needed for proper doc block formatting $this->resolveContentFromTokenIterator($tokenIterator); diff --git a/packages/BetterPhpDocParser/src/PhpDocParser/AnnotationContentResolver.php b/packages/BetterPhpDocParser/src/PhpDocParser/AnnotationContentResolver.php index b529f0f02043..01df04079d65 100644 --- a/packages/BetterPhpDocParser/src/PhpDocParser/AnnotationContentResolver.php +++ b/packages/BetterPhpDocParser/src/PhpDocParser/AnnotationContentResolver.php @@ -74,7 +74,7 @@ public function resolveNestedKey(string $annotationContent, string $name): strin } $start = $this->tryStartWithKey($name, $start, $tokenIterator); - if ($start === false) { + if (! $start) { $tokenIterator->next(); continue; } @@ -112,7 +112,7 @@ private function cleanMultilineAnnotationContent(string $annotationContent): str private function tryStartWithKey(string $name, bool $start, TokenIterator $localTokenIterator): bool { - if ($start === true) { + if ($start) { return true; } diff --git a/packages/BetterPhpDocParser/src/PhpDocParser/BetterPhpDocParser.php b/packages/BetterPhpDocParser/src/PhpDocParser/BetterPhpDocParser.php index 2f2f8b7a3487..72518d1d21a8 100644 --- a/packages/BetterPhpDocParser/src/PhpDocParser/BetterPhpDocParser.php +++ b/packages/BetterPhpDocParser/src/PhpDocParser/BetterPhpDocParser.php @@ -245,11 +245,7 @@ private function isTagMatchingPhpDocNodeFactory( $tag = ltrim($tag, '@'); if ($phpDocNodeFactory instanceof NameAwarePhpDocNodeFactoryInterface) { - if (Strings::lower($phpDocNodeFactory->getName()) === Strings::lower($tag)) { - return true; - } - - return false; + return Strings::lower($phpDocNodeFactory->getName()) === Strings::lower($tag); } if ($phpDocNodeFactory instanceof ClassAwarePhpDocNodeFactoryInterface) { diff --git a/packages/BetterPhpDocParser/src/PhpDocParser/ClassAnnotationMatcher.php b/packages/BetterPhpDocParser/src/PhpDocParser/ClassAnnotationMatcher.php index 578eb4753f0d..a2f73a16df5d 100644 --- a/packages/BetterPhpDocParser/src/PhpDocParser/ClassAnnotationMatcher.php +++ b/packages/BetterPhpDocParser/src/PhpDocParser/ClassAnnotationMatcher.php @@ -44,7 +44,7 @@ private function matchFullAnnotationClassWithUses(string $tag, array $uses): ?st continue; } - if ($useUse->alias) { + if ($useUse->alias !== null) { $unaliasedShortClass = Strings::substring($tag, Strings::length($useUse->alias->toString())); if (Strings::startsWith($unaliasedShortClass, '\\')) { return $useUse->name . $unaliasedShortClass; @@ -62,7 +62,7 @@ private function matchFullAnnotationClassWithUses(string $tag, array $uses): ?st private function isUseMatchingName(string $tag, UseUse $useUse): bool { - $shortName = $useUse->alias ? $useUse->alias->name : $useUse->name->getLast(); + $shortName = $useUse->alias !== null ? $useUse->alias->name : $useUse->name->getLast(); $shortNamePattern = preg_quote($shortName, '#'); return (bool) Strings::match($tag, '#' . $shortNamePattern . '(\\\\[\w]+)?#i'); diff --git a/packages/BetterPhpDocParser/src/Printer/PhpDocInfoPrinter.php b/packages/BetterPhpDocParser/src/Printer/PhpDocInfoPrinter.php index f472a47b1b34..082ca7bdffbc 100644 --- a/packages/BetterPhpDocParser/src/Printer/PhpDocInfoPrinter.php +++ b/packages/BetterPhpDocParser/src/Printer/PhpDocInfoPrinter.php @@ -148,7 +148,7 @@ private function printNode( $startEndValueObject = $attributeAwareNode->getAttribute(Attribute::PHP_DOC_NODE_INFO) ?: $startEndValueObject; $attributeAwareNode = $this->multilineSpaceFormatPreserver->fixMultilineDescriptions($attributeAwareNode); - if ($startEndValueObject) { + if ($startEndValueObject !== null) { $isLastToken = ($nodeCount === $i); $output = $this->addTokensFromTo( @@ -162,7 +162,7 @@ private function printNode( } if ($attributeAwareNode instanceof PhpDocTagNode) { - if ($startEndValueObject) { + if ($startEndValueObject !== null) { return $this->printPhpDocTagNode($attributeAwareNode, $startEndValueObject, $output); } @@ -246,7 +246,7 @@ private function printPhpDocTagNode( $phpDocTagNode->value->description ); - if (substr_count($nodeOutput, "\n")) { + if (substr_count($nodeOutput, "\n") !== 0) { $nodeOutput = Strings::replace($nodeOutput, "#\n#", PHP_EOL . ' * '); } } diff --git a/packages/CodeQuality/src/Exception/TooLongException.php b/packages/CodeQuality/src/Exception/TooLongException.php new file mode 100644 index 000000000000..c74076d1abed --- /dev/null +++ b/packages/CodeQuality/src/Exception/TooLongException.php @@ -0,0 +1,11 @@ +stmts[] = new Return_($innerMethodCall); } else { $anonymousFunction->stmts[] = new Expression($innerMethodCall); diff --git a/packages/CodeQuality/src/Rector/Class_/CompleteDynamicPropertiesRector.php b/packages/CodeQuality/src/Rector/Class_/CompleteDynamicPropertiesRector.php index f0664c708013..6db6559a493a 100644 --- a/packages/CodeQuality/src/Rector/Class_/CompleteDynamicPropertiesRector.php +++ b/packages/CodeQuality/src/Rector/Class_/CompleteDynamicPropertiesRector.php @@ -12,6 +12,7 @@ use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Property; +use PhpParser\NodeTraverser; use PHPStan\Type\MixedType; use PHPStan\Type\Type; use Rector\NodeTypeResolver\Node\AttributeKey; @@ -134,7 +135,12 @@ private function resolveFetchedLocalPropertyNameToType(Class_ $class): array $this->traverseNodesWithCallable($class->stmts, function (Node $node) use ( &$fetchedLocalPropertyNameToTypes - ) { + ): ?int { + // skip anonymous class scope + if ($this->isAnonymousClass($node)) { + return NodeTraverser::DONT_TRAVERSE_CHILDREN; + } + if (! $node instanceof PropertyFetch) { return null; } @@ -164,6 +170,8 @@ private function resolveFetchedLocalPropertyNameToType(Class_ $class): array $propertyFetchType = $this->resolvePropertyFetchType($node); $fetchedLocalPropertyNameToTypes[$propertyName][] = $propertyFetchType; + + return null; }); // normalize types to union diff --git a/packages/CodeQuality/src/Rector/Concat/JoinStringConcatRector.php b/packages/CodeQuality/src/Rector/Concat/JoinStringConcatRector.php index c2c18f05a9af..acf21be35d2b 100644 --- a/packages/CodeQuality/src/Rector/Concat/JoinStringConcatRector.php +++ b/packages/CodeQuality/src/Rector/Concat/JoinStringConcatRector.php @@ -4,9 +4,11 @@ namespace Rector\CodeQuality\Rector\Concat; +use Nette\Utils\Strings; use PhpParser\Node; use PhpParser\Node\Expr\BinaryOp\Concat; use PhpParser\Node\Scalar\String_; +use Rector\CodeQuality\Exception\TooLongException; use Rector\Rector\AbstractRector; use Rector\RectorDefinition\CodeSample; use Rector\RectorDefinition\RectorDefinition; @@ -16,6 +18,11 @@ */ final class JoinStringConcatRector extends AbstractRector { + /** + * @var int + */ + private const LINE_BREAK_POINT = 80; + public function getDefinition(): RectorDefinition { return new RectorDefinition('Joins concat of 2 strings', [ @@ -56,7 +63,11 @@ public function getNodeTypes(): array */ public function refactor(Node $node): ?Node { - return $this->joinConcatIfStrings($node); + try { + return $this->joinConcatIfStrings($node); + } catch (TooLongException $tooLongException) { + return null; + } } /** @@ -80,6 +91,11 @@ private function joinConcatIfStrings(Concat $concat): Node return $concat; } + $value = $concat->left->value . $concat->right->value; + if (Strings::length($value) >= self::LINE_BREAK_POINT) { + throw new TooLongException(); + } + return new String_($concat->left->value . $concat->right->value); } } diff --git a/packages/CodeQuality/src/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector.php b/packages/CodeQuality/src/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector.php index 35ad6ccfdccd..78022cf88c85 100644 --- a/packages/CodeQuality/src/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector.php +++ b/packages/CodeQuality/src/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector.php @@ -9,6 +9,7 @@ use PhpParser\Node\Expr\Closure; use PhpParser\Node\Expr\PropertyFetch; use PhpParser\Node\Stmt\Class_; +use PhpParser\Node\Stmt\ClassLike; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\If_; @@ -22,6 +23,7 @@ /** * @see https://phpstan.org/r/e909844a-084e-427e-92ac-fed3c2aeabab + * * @see \Rector\CodeQuality\Tests\Rector\If_\RemoveAlwaysTrueConditionSetInConstructorRector\RemoveAlwaysTrueConditionSetInConstructorRectorTest */ final class RemoveAlwaysTrueConditionSetInConstructorRector extends AbstractRector @@ -181,7 +183,26 @@ private function resolvePropertyFetchTypes(PropertyFetch $propertyFetch): array $resolvedTypes = []; - $this->traverseNodesWithCallable($class->stmts, function (Node $node) use ( + // add dfeault vlaue @todo + $defaultValue = $property->props[0]->default; + if ($defaultValue !== null) { + $defaultValueStaticType = $this->getStaticType($defaultValue); + $resolvedTypes[] = $defaultValueStaticType; + } + + $assignTypes = $this->resolveAssignTypes($class, $propertyName); + + return array_merge($resolvedTypes, $assignTypes); + } + + /** + * @return Type[] + */ + private function resolveAssignTypes(ClassLike $classLike, string $propertyName): array + { + $resolvedTypes = []; + + $this->traverseNodesWithCallable($classLike->stmts, function (Node $node) use ( $propertyName, &$resolvedTypes ) { diff --git a/packages/CodeQuality/src/Rector/If_/ShortenElseIfRector.php b/packages/CodeQuality/src/Rector/If_/ShortenElseIfRector.php index cef6429309d8..eba94b87653a 100644 --- a/packages/CodeQuality/src/Rector/If_/ShortenElseIfRector.php +++ b/packages/CodeQuality/src/Rector/If_/ShortenElseIfRector.php @@ -88,7 +88,7 @@ private function shortenElseIf(If_ $node): ?Node // Try to shorten the nested if before transforming it to elseif $refactored = $this->shortenElseIf($if); - if ($refactored) { + if ($refactored !== null) { $if = $refactored; } diff --git a/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/CompleteDynamicPropertiesRectorTest.php b/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/CompleteDynamicPropertiesRectorTest.php index 10bff5f83030..a809869ac279 100644 --- a/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/CompleteDynamicPropertiesRectorTest.php +++ b/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/CompleteDynamicPropertiesRectorTest.php @@ -22,6 +22,7 @@ public function provideDataForTest(): Iterator { yield [__DIR__ . '/Fixture/fixture.php.inc']; yield [__DIR__ . '/Fixture/multiple_types.php.inc']; + yield [__DIR__ . '/Fixture/skip_anonymous_class.php.inc']; yield [__DIR__ . '/Fixture/skip_defined.php.inc']; yield [__DIR__ . '/Fixture/skip_parent_property.php.inc']; yield [__DIR__ . '/Fixture/skip_trait_used.php.inc']; diff --git a/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/Fixture/skip_anonymous_class.php.inc b/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/Fixture/skip_anonymous_class.php.inc new file mode 100644 index 000000000000..6bdeeafd1074 --- /dev/null +++ b/packages/CodeQuality/tests/Rector/Class_/CompleteDynamicPropertiesRector/Fixture/skip_anonymous_class.php.inc @@ -0,0 +1,49 @@ +addVisitor($this->createNodeVisitor($callable)); + $nodeTraverser->traverse($nodes); + } + + private function createNodeVisitor(callable $callable): NodeVisitor + { + return new class($callable) extends NodeVisitorAbstract { + /** + * @var callable + */ + private $callable; + + public function __construct(callable $callable) + { + $this->callable = $callable; + } + + /** + * @return int|Node|null + */ + public function enterNode(Node $node) + { + $callable = $this->callable; + return $callable($node); + } + }; + } +} diff --git a/packages/CodeQuality/tests/Rector/Concat/JoinStringConcatRector/Fixture/skip_longer_than_120.php.inc b/packages/CodeQuality/tests/Rector/Concat/JoinStringConcatRector/Fixture/skip_longer_than_120.php.inc new file mode 100644 index 000000000000..9ada4f4597aa --- /dev/null +++ b/packages/CodeQuality/tests/Rector/Concat/JoinStringConcatRector/Fixture/skip_longer_than_120.php.inc @@ -0,0 +1,13 @@ +value = [5]; + } + + public function go() + { + if ($this->value) { + $maybe = 'yes'; + return 'she says ' . $maybe; + } + } +} + +?> +----- +value = [5]; + } + + public function go() + { + $maybe = 'yes'; + return 'she says ' . $maybe; + } +} + +?> diff --git a/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_after_overridden.php.inc b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_after_overridden.php.inc new file mode 100644 index 000000000000..4a1ba2fb7ea9 --- /dev/null +++ b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_after_overridden.php.inc @@ -0,0 +1,26 @@ +areListenerClassesLoaded) { + return $this->listenerClassesToEvents; + } + + $this->areListenerClassesLoaded = true; + } +} diff --git a/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_array.php.inc b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_array.php.inc new file mode 100644 index 000000000000..22865dafd9cb --- /dev/null +++ b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_array.php.inc @@ -0,0 +1,21 @@ +value = $value; + } + + public function go() + { + if ($this->value) { + $maybe = 'yes'; + return 'she says ' . $maybe; + } + } +} diff --git a/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_nullable_set.php.inc b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_nullable_set.php.inc new file mode 100644 index 000000000000..f18887276e41 --- /dev/null +++ b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/Fixture/skip_nullable_set.php.inc @@ -0,0 +1,30 @@ +callback = $callback; + } + + public function __toString() + { + $contentItems = []; + + if ($this->callback) { + $contentItems['callback'] = 5; + } + + return '...'; + } +} diff --git a/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/RemoveAlwaysTrueConditionSetInConstructorRectorTest.php b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/RemoveAlwaysTrueConditionSetInConstructorRectorTest.php index c619530d67d8..07a3196d4d23 100644 --- a/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/RemoveAlwaysTrueConditionSetInConstructorRectorTest.php +++ b/packages/CodeQuality/tests/Rector/If_/RemoveAlwaysTrueConditionSetInConstructorRector/RemoveAlwaysTrueConditionSetInConstructorRectorTest.php @@ -27,11 +27,17 @@ public function provideDataForTest(): Iterator yield [__DIR__ . '/Fixture/multiple_lines.php.inc']; yield [__DIR__ . '/Fixture/multiple_lines_in_callable.php.inc']; yield [__DIR__ . '/Fixture/multiple_lines_removed.php.inc']; + yield [__DIR__ . '/Fixture/fix_static_array.php.inc']; + + // skip + yield [__DIR__ . '/Fixture/skip_after_overridden.php.inc']; + yield [__DIR__ . '/Fixture/skip_array.php.inc']; yield [__DIR__ . '/Fixture/skip_changed_value.php.inc']; yield [__DIR__ . '/Fixture/skip_scalars.php.inc']; yield [__DIR__ . '/Fixture/skip_unknown.php.inc']; yield [__DIR__ . '/Fixture/skip_optional_argument_value.php.inc']; yield [__DIR__ . '/Fixture/skip_trait.php.inc']; + yield [__DIR__ . '/Fixture/skip_nullable_set.php.inc']; } protected function getRectorClass(): string diff --git a/packages/CodingStyle/src/Application/NameImportingCommander.php b/packages/CodingStyle/src/Application/NameImportingCommander.php index fb1303b7bbac..f8ee17db8ec2 100644 --- a/packages/CodingStyle/src/Application/NameImportingCommander.php +++ b/packages/CodingStyle/src/Application/NameImportingCommander.php @@ -6,9 +6,11 @@ use PhpParser\Node; use PhpParser\Node\Name; +use PhpParser\Node\Stmt\UseUse; use Rector\CodingStyle\Node\NameImporter; use Rector\Configuration\Option; use Rector\Contract\PhpParser\Node\CommanderInterface; +use Rector\NodeTypeResolver\Node\AttributeKey; use Rector\PhpParser\NodeTraverser\CallableNodeTraverser; use Symplify\PackageBuilder\Parameter\ParameterProvider; @@ -55,6 +57,11 @@ public function traverseNodes(array $nodes): array return null; } + // skip name of UseUse + if ($node->getAttribute(AttributeKey::PARENT_NODE) instanceof UseUse) { + return null; + } + return $this->nameImporter->importName($node); }); diff --git a/packages/CodingStyle/src/Node/NameImporter.php b/packages/CodingStyle/src/Node/NameImporter.php index e7962acd2d0a..322b237813fe 100644 --- a/packages/CodingStyle/src/Node/NameImporter.php +++ b/packages/CodingStyle/src/Node/NameImporter.php @@ -57,7 +57,12 @@ public function __construct( public function importName(Name $name): ?Name { + if ($name->getAttribute('virtual_node')) { + return null; + } + $staticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($name); + if (! $staticType instanceof FullyQualifiedObjectType) { return null; } diff --git a/packages/CodingStyle/src/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php b/packages/CodingStyle/src/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php index 7070caee472e..16858e7627a1 100644 --- a/packages/CodingStyle/src/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php +++ b/packages/CodingStyle/src/Rector/ClassMethod/MakeInheritedMethodVisibilitySameAsParentRector.php @@ -122,12 +122,7 @@ private function isClassMethodCompatibleWithParentReflectionMethod( if ($reflectionMethod->isProtected() && $classMethod->isProtected()) { return true; } - - if ($reflectionMethod->isPrivate() && $classMethod->isPrivate()) { - return true; - } - - return false; + return $reflectionMethod->isPrivate() && $classMethod->isPrivate(); } /** @@ -161,7 +156,7 @@ private function isConstructorWithStaticFactory(ClassMethod $classMethod, string $isStaticSelfFactory = $this->isStaticNamedConstructor($iteratedClassMethod); - if ($isStaticSelfFactory === false) { + if (! $isStaticSelfFactory) { continue; } @@ -219,12 +214,7 @@ private function isStaticNamedConstructor(ClassMethod $classMethod): bool if ($this->isName($node->expr->class, 'self')) { return true; } - - if ($this->isName($node->expr->class, 'static')) { - return true; - } - - return false; + return $this->isName($node->expr->class, 'static'); }); } } diff --git a/packages/CodingStyle/src/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php b/packages/CodingStyle/src/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php index 0113aa32db65..29e62eff320c 100644 --- a/packages/CodingStyle/src/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php +++ b/packages/CodingStyle/src/Rector/ClassMethod/NewlineBeforeNewAssignSetRector.php @@ -139,13 +139,8 @@ private function shouldAddEmptyLine(?string $currentStmtVariableName, Node $node if (! $this->isNewVariableThanBefore($currentStmtVariableName)) { return false; } - // this is already empty line before - if ($this->isPreceededByEmptyLine($node, $key)) { - return false; - } - - return true; + return ! $this->isPreceededByEmptyLine($node, $key); } private function isNewVariableThanBefore(?string $currentStmtVariableName): bool diff --git a/packages/CodingStyle/src/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php b/packages/CodingStyle/src/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php index 62918afa4126..6ab1ba7b7886 100644 --- a/packages/CodingStyle/src/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php +++ b/packages/CodingStyle/src/Rector/ClassMethod/ReturnArrayClassMethodToYieldRector.php @@ -167,9 +167,9 @@ private function transformArrayToYieldsOnMethodNode(ClassMethod $classMethod, Ar private function completeComments(Node $node): void { - if ($this->returnDocComment) { + if ($this->returnDocComment !== null) { $node->setDocComment($this->returnDocComment); - } elseif ($this->returnComments) { + } elseif ($this->returnComments !== []) { $node->setAttribute('comments', $this->returnComments); } } diff --git a/packages/CodingStyle/src/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php b/packages/CodingStyle/src/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php index 13d04d70f547..88da20eae939 100644 --- a/packages/CodingStyle/src/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php +++ b/packages/CodingStyle/src/Rector/Class_/AddArrayDefaultToArrayPropertyRector.php @@ -115,7 +115,7 @@ private function collectPropertyNamesWithMissingDefaultArray(Class_ $class): arr return null; } - if ($node->default) { + if ($node->default !== null) { return null; } @@ -199,7 +199,7 @@ private function clearNotNullBeforeCount(Class_ $class, array $propertyNames): v return $this->isNames($countedArgument, $propertyNames); }); - if ($isNextNodeCountingProperty === false) { + if (! $isNextNodeCountingProperty) { return null; } @@ -250,13 +250,8 @@ private function isLocalPropertyOfNamesNotIdenticalToNull(Expr $expr, array $pro )) { return true; } - - if ($this->propertyFetchManipulator->isLocalPropertyOfNames($expr->right, $propertyNames) && $this->isNull( + return $this->propertyFetchManipulator->isLocalPropertyOfNames($expr->right, $propertyNames) && $this->isNull( $expr->left - )) { - return true; - } - - return false; + ); } } diff --git a/packages/CodingStyle/src/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php b/packages/CodingStyle/src/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php index 8e32487867c9..b766b600ffcb 100644 --- a/packages/CodingStyle/src/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php +++ b/packages/CodingStyle/src/Rector/FuncCall/VersionCompareFuncCallToConstantRector.php @@ -113,11 +113,7 @@ public function refactor(Node $node): ?Node private function isPhpVersionConstant(Expr $expr): bool { - if ($expr instanceof ConstFetch && $expr->name->toString() === 'PHP_VERSION') { - return true; - } - - return false; + return $expr instanceof ConstFetch && $expr->name->toString() === 'PHP_VERSION'; } private function getNewNodeForArg(Expr $expr): Node diff --git a/packages/CodingStyle/src/Rector/Use_/RemoveUnusedAliasRector.php b/packages/CodingStyle/src/Rector/Use_/RemoveUnusedAliasRector.php index be6afc951775..e124916f9eb5 100644 --- a/packages/CodingStyle/src/Rector/Use_/RemoveUnusedAliasRector.php +++ b/packages/CodingStyle/src/Rector/Use_/RemoveUnusedAliasRector.php @@ -267,17 +267,11 @@ private function renameNameNode(array $usedNameNodes, string $lastName): void private function resolveSearchNode(Use_ $node): ?Node { $searchNode = $node->getAttribute(AttributeKey::PARENT_NODE); - if ($searchNode) { + if ($searchNode !== null) { return $searchNode; } - $searchNode = $node->getAttribute(AttributeKey::NEXT_NODE); - if ($searchNode) { - return $searchNode; - } - - // skip - return null; + return $node->getAttribute(AttributeKey::NEXT_NODE); } private function resolveUsedNames(Node $searchNode): void diff --git a/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/Fixture/prevent_duplication.php.inc b/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/Fixture/prevent_duplication.php.inc new file mode 100644 index 000000000000..bbe1b511fbcf --- /dev/null +++ b/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/Fixture/prevent_duplication.php.inc @@ -0,0 +1,32 @@ + +----- + diff --git a/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/ImportFullyQualifiedNamesRectorTest.php b/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/ImportFullyQualifiedNamesRectorTest.php index 9a54e4ec155e..bd77b9bc1a14 100644 --- a/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/ImportFullyQualifiedNamesRectorTest.php +++ b/packages/CodingStyle/tests/Rector/Namespace_/ImportFullyQualifiedNamesRector/ImportFullyQualifiedNamesRectorTest.php @@ -13,6 +13,7 @@ final class ImportFullyQualifiedNamesRectorTest extends AbstractRectorTestCase /** * @dataProvider provideNamespacedClasses() * @dataProvider provideFunctions() + * @dataProvider providerPartials() */ public function test(string $file): void { @@ -21,7 +22,12 @@ public function test(string $file): void public function providerPartials(): Iterator { - // @todo fix later, details + yield [__DIR__ . '/Fixture/prevent_duplication.php.inc']; + } + + public function skippedProviderPartials(): Iterator + { +// @todo fix later yield [__DIR__ . '/Fixture/doc_combined.php.inc']; yield [__DIR__ . '/Fixture/conflicting_endings.php.inc']; yield [__DIR__ . '/Fixture/import_return_doc.php.inc']; diff --git a/packages/DeadCode/src/Analyzer/SetterOnlyMethodAnalyzer.php b/packages/DeadCode/src/Analyzer/SetterOnlyMethodAnalyzer.php index e57b86bdfda6..edb918a17351 100644 --- a/packages/DeadCode/src/Analyzer/SetterOnlyMethodAnalyzer.php +++ b/packages/DeadCode/src/Analyzer/SetterOnlyMethodAnalyzer.php @@ -94,13 +94,13 @@ public function provideSetterOnlyPropertiesAndMethodsByType(): array $relationPropertyNames = $this->doctrineEntityManipulator->resolveRelationPropertyNames($class); $assignOnlyPrivatePropertyNames = array_diff($assignOnlyPrivatePropertyNames, $relationPropertyNames); - if ($assignOnlyPrivatePropertyNames) { + if ($assignOnlyPrivatePropertyNames !== []) { $this->propertiesAndMethodsToRemoveByType[$type]['properties'] = $assignOnlyPrivatePropertyNames; } // 2. setter only methods by class $setterOnlyMethodNames = $this->resolveSetterOnlyMethodNames($class, $assignOnlyPrivatePropertyNames); - if ($setterOnlyMethodNames) { + if ($setterOnlyMethodNames !== []) { $this->propertiesAndMethodsToRemoveByType[$type]['methods'] = $setterOnlyMethodNames; } } diff --git a/packages/DeadCode/src/Doctrine/DoctrineEntityManipulator.php b/packages/DeadCode/src/Doctrine/DoctrineEntityManipulator.php index 20b9e150dfd1..497e63b3091d 100644 --- a/packages/DeadCode/src/Doctrine/DoctrineEntityManipulator.php +++ b/packages/DeadCode/src/Doctrine/DoctrineEntityManipulator.php @@ -126,7 +126,7 @@ public function removeMappedByOrInversedByFromProperty(Property $property): void } } - if ($shouldUpdate === false) { + if (! $shouldUpdate) { return; } diff --git a/packages/DeadCode/src/Rector/ClassMethod/RemoveDelegatingParentCallRector.php b/packages/DeadCode/src/Rector/ClassMethod/RemoveDelegatingParentCallRector.php index e07dc1249a77..d858c45c193e 100644 --- a/packages/DeadCode/src/Rector/ClassMethod/RemoveDelegatingParentCallRector.php +++ b/packages/DeadCode/src/Rector/ClassMethod/RemoveDelegatingParentCallRector.php @@ -109,12 +109,7 @@ private function shouldSkipClass(?ClassLike $classLike): bool if (! $classLike instanceof Class_) { return true; } - - if ($classLike->extends === null) { - return true; - } - - return false; + return $classLike->extends === null; } /** @@ -173,12 +168,7 @@ private function isParentCallMatching(ClassMethod $classMethod, ?StaticCall $sta if (! $this->areArgsAndParamsEqual($staticCall->args, $classMethod->params)) { return false; } - - if ($this->isParentClassMethodVisibilityOverride($classMethod, $staticCall)) { - return false; - } - - return true; + return ! $this->isParentClassMethodVisibilityOverride($classMethod, $staticCall); } private function hasRequiredAnnotation(Node $node): bool diff --git a/packages/DeadCode/src/Rector/If_/RemoveAlwaysTrueIfConditionRector.php b/packages/DeadCode/src/Rector/If_/RemoveAlwaysTrueIfConditionRector.php index 1a663f5059f5..9fa3ce1a06bc 100644 --- a/packages/DeadCode/src/Rector/If_/RemoveAlwaysTrueIfConditionRector.php +++ b/packages/DeadCode/src/Rector/If_/RemoveAlwaysTrueIfConditionRector.php @@ -76,7 +76,7 @@ public function refactor(Node $node): ?Node return null; } - if ($conditionStaticType->getValue() !== true) { + if (! $conditionStaticType->getValue()) { return null; } diff --git a/packages/DeadCode/src/Rector/Property/RemoveUnusedPrivatePropertyRector.php b/packages/DeadCode/src/Rector/Property/RemoveUnusedPrivatePropertyRector.php index 94d149688088..9a3fd2b46816 100644 --- a/packages/DeadCode/src/Rector/Property/RemoveUnusedPrivatePropertyRector.php +++ b/packages/DeadCode/src/Rector/Property/RemoveUnusedPrivatePropertyRector.php @@ -118,19 +118,13 @@ private function shouldSkipProperty(Property $property): bool /** @var Node\Stmt\ClassLike $class */ $class = $property->getAttribute(AttributeKey::CLASS_NODE); - $hasMagicPropertyFetch = (bool) $this->betterNodeFinder->findFirst($class->stmts, function (Node $node): bool { + return (bool) $this->betterNodeFinder->findFirst($class->stmts, function (Node $node): bool { if (! $node instanceof PropertyFetch) { return false; } return $node->name instanceof Expr; }); - - if ($hasMagicPropertyFetch) { - return true; - } - - return false; } /** diff --git a/packages/DeadCode/src/Rector/Stmt/RemoveUnreachableStatementRector.php b/packages/DeadCode/src/Rector/Stmt/RemoveUnreachableStatementRector.php index eebd861c2f7e..b0fcbae6202e 100644 --- a/packages/DeadCode/src/Rector/Stmt/RemoveUnreachableStatementRector.php +++ b/packages/DeadCode/src/Rector/Stmt/RemoveUnreachableStatementRector.php @@ -144,11 +144,6 @@ private function isBreakingScopeNode(Node $node): bool if ($node instanceof Namespace_) { return true; } - - if ($node instanceof Else_) { - return true; - } - - return false; + return $node instanceof Else_; } } diff --git a/packages/Doctrine/src/PhpDocParser/DoctrineDocBlockResolver.php b/packages/Doctrine/src/PhpDocParser/DoctrineDocBlockResolver.php index 2129cd4e5df5..6a1ce4da6284 100644 --- a/packages/Doctrine/src/PhpDocParser/DoctrineDocBlockResolver.php +++ b/packages/Doctrine/src/PhpDocParser/DoctrineDocBlockResolver.php @@ -56,7 +56,7 @@ public function isDoctrineEntityClass($class): bool if (is_string($class)) { if (ClassExistenceStaticHelper::doesClassLikeExist($class)) { $classNode = $this->parsedNodesByType->findClass($class); - if ($classNode) { + if ($classNode !== null) { return $this->isDoctrineEntityClass($classNode); } @@ -128,7 +128,7 @@ public function isDoctrineProperty(Property $property): bool return false; } - if ($propertyPhpDocInfo->getByType(ColumnTagValueNode::class)) { + if ($propertyPhpDocInfo->getByType(ColumnTagValueNode::class) !== null) { return true; } diff --git a/packages/Doctrine/src/Provider/EntityWithMissingUuidProvider.php b/packages/Doctrine/src/Provider/EntityWithMissingUuidProvider.php index e1d1a9b85cd3..fa6306da00e0 100644 --- a/packages/Doctrine/src/Provider/EntityWithMissingUuidProvider.php +++ b/packages/Doctrine/src/Provider/EntityWithMissingUuidProvider.php @@ -77,7 +77,7 @@ public function provide(): array } // already has $uuid property - if ($this->classManipulator->getProperty($class, 'uuid')) { + if ($this->classManipulator->getProperty($class, 'uuid') !== null) { continue; } diff --git a/packages/Doctrine/src/Rector/ClassMethod/ChangeReturnTypeOfClassMethodWithGetIdRector.php b/packages/Doctrine/src/Rector/ClassMethod/ChangeReturnTypeOfClassMethodWithGetIdRector.php index 56efaae2ef98..00479cc9b299 100644 --- a/packages/Doctrine/src/Rector/ClassMethod/ChangeReturnTypeOfClassMethodWithGetIdRector.php +++ b/packages/Doctrine/src/Rector/ClassMethod/ChangeReturnTypeOfClassMethodWithGetIdRector.php @@ -78,7 +78,7 @@ public function refactor(Node $node): ?Node } $hasEntityGetIdMethodCall = $this->hasEntityGetIdMethodCall($node); - if ($hasEntityGetIdMethodCall === false) { + if (! $hasEntityGetIdMethodCall) { return null; } diff --git a/packages/Doctrine/src/Rector/Class_/AddUuidMirrorForRelationPropertyRector.php b/packages/Doctrine/src/Rector/Class_/AddUuidMirrorForRelationPropertyRector.php index 7b0c618fdcc2..09737610156e 100644 --- a/packages/Doctrine/src/Rector/Class_/AddUuidMirrorForRelationPropertyRector.php +++ b/packages/Doctrine/src/Rector/Class_/AddUuidMirrorForRelationPropertyRector.php @@ -111,7 +111,7 @@ private function shouldSkipProperty(Class_ $class, Property $property): bool } $oneToOneTagValueNode = $propertyPhpDocInfo->getByType(OneToOneTagValueNode::class); - if ($oneToOneTagValueNode) { + if ($oneToOneTagValueNode !== null) { // skip mappedBy oneToOne, as the column doesn't really exist if ($oneToOneTagValueNode->getMappedBy()) { return true; @@ -197,7 +197,7 @@ private function addNewPropertyToCollector( private function refactorToManyPropertyPhpDocInfo(PhpDocInfo $propertyPhpDocInfo, Property $property): void { $doctrineJoinColumnTagValueNode = $propertyPhpDocInfo->getByType(JoinColumnTagValueNode::class); - if ($doctrineJoinColumnTagValueNode) { + if ($doctrineJoinColumnTagValueNode !== null) { // replace @ORM\JoinColumn with @ORM\JoinTable $propertyPhpDocInfo->removeTagValueNodeFromNode($doctrineJoinColumnTagValueNode); } diff --git a/packages/Doctrine/src/Rector/Class_/AlwaysInitializeUuidInEntityRector.php b/packages/Doctrine/src/Rector/Class_/AlwaysInitializeUuidInEntityRector.php index 618e2408d6e6..0c979ac86ef8 100644 --- a/packages/Doctrine/src/Rector/Class_/AlwaysInitializeUuidInEntityRector.php +++ b/packages/Doctrine/src/Rector/Class_/AlwaysInitializeUuidInEntityRector.php @@ -128,12 +128,7 @@ private function hasUuidInitAlreadyAdded(Class_ $class, string $uuidPropertyName if (! $this->isName($staticCall->name, 'uuid4')) { return false; } - - if (! $this->isName($node->var, $uuidPropertyName)) { - return false; - } - - return true; + return $this->isName($node->var, $uuidPropertyName); }); } } diff --git a/packages/Doctrine/src/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector.php b/packages/Doctrine/src/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector.php index 88accded04c0..3e9837ce84ce 100644 --- a/packages/Doctrine/src/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector.php +++ b/packages/Doctrine/src/Rector/Class_/ManagerRegistryGetManagerToEntityManagerRector.php @@ -286,12 +286,7 @@ private function isRegistryGetManagerMethodCall(Assign $assign): bool if (! $this->isObjectType($assign->expr->var, ManagerRegistry::class)) { return false; } - - if (! $this->isName($assign->expr->name, 'getManager')) { - return false; - } - - return true; + return $this->isName($assign->expr->name, 'getManager'); } /** diff --git a/packages/Doctrine/src/Rector/MethodCall/ChangeSetIdToUuidValueRector.php b/packages/Doctrine/src/Rector/MethodCall/ChangeSetIdToUuidValueRector.php index f0320e610fc4..50e29f814cae 100644 --- a/packages/Doctrine/src/Rector/MethodCall/ChangeSetIdToUuidValueRector.php +++ b/packages/Doctrine/src/Rector/MethodCall/ChangeSetIdToUuidValueRector.php @@ -114,7 +114,7 @@ public function refactor(Node $node): ?Node // A. try find "setUuid()" call on the same object later $setUuidCallOnSameVariable = $this->getSetUuidMethodCallOnSameVariable($node); - if ($setUuidCallOnSameVariable) { + if ($setUuidCallOnSameVariable !== null) { $node->args = $setUuidCallOnSameVariable->args; $this->removeNode($setUuidCallOnSameVariable); return $node; @@ -195,12 +195,7 @@ private function getSetUuidMethodCallOnSameVariable(MethodCall $methodCall): ?Me if (! $this->isObjectType($node->var, $variableType)) { return false; } - - if (! $this->isName($node->name, 'setUuid')) { - return false; - } - - return true; + return $this->isName($node->name, 'setUuid'); }); } diff --git a/packages/DoctrineCodeQuality/src/Rector/Class_/InitializeDefaultEntityCollectionRector.php b/packages/DoctrineCodeQuality/src/Rector/Class_/InitializeDefaultEntityCollectionRector.php index d8d744b82f78..86eb41207e07 100644 --- a/packages/DoctrineCodeQuality/src/Rector/Class_/InitializeDefaultEntityCollectionRector.php +++ b/packages/DoctrineCodeQuality/src/Rector/Class_/InitializeDefaultEntityCollectionRector.php @@ -95,7 +95,7 @@ public function refactor(Node $node): ?Node return null; } - if (! $classPhpDocInfo->getByType(EntityTagValueNode::class)) { + if ($classPhpDocInfo->getByType(EntityTagValueNode::class) === null) { return null; } @@ -128,7 +128,7 @@ private function resolveToManyPropertyNames(Class_ $class): array continue; } - if (! $propertyPhpDocInfo->getByType(ToManyTagNodeInterface::class)) { + if ($propertyPhpDocInfo->getByType(ToManyTagNodeInterface::class) === null) { continue; } diff --git a/packages/Laravel/src/Rector/Class_/InlineValidationRulesToArrayDefinitionRector.php b/packages/Laravel/src/Rector/Class_/InlineValidationRulesToArrayDefinitionRector.php index 2737c750e6bf..e6aa998fb349 100644 --- a/packages/Laravel/src/Rector/Class_/InlineValidationRulesToArrayDefinitionRector.php +++ b/packages/Laravel/src/Rector/Class_/InlineValidationRulesToArrayDefinitionRector.php @@ -104,12 +104,7 @@ private function shouldSkipArrayItem(ArrayItem $arrayItem): bool if (! $this->isName($methodNode, 'rules')) { return true; } - - if (! $arrayItem->value instanceof String_ && ! $arrayItem->value instanceof Concat) { - return true; - } - - return false; + return ! $arrayItem->value instanceof String_ && ! $arrayItem->value instanceof Concat; } /** diff --git a/packages/NodeTypeResolver/src/NodeTypeResolver.php b/packages/NodeTypeResolver/src/NodeTypeResolver.php index a6e5a820e76f..f65f02db0f39 100644 --- a/packages/NodeTypeResolver/src/NodeTypeResolver.php +++ b/packages/NodeTypeResolver/src/NodeTypeResolver.php @@ -262,12 +262,7 @@ public function isCountableType(Node $node): bool if (is_a($nodeType->getClassName(), 'SimpleXMLElement', true)) { return true; } - - if (is_a($nodeType->getClassName(), 'ResourceBundle', true)) { - return true; - } - - return false; + return is_a($nodeType->getClassName(), 'ResourceBundle', true); } return $this->isArrayType($node); @@ -284,7 +279,7 @@ public function isArrayType(Node $node): bool if ($node instanceof PropertyFetch || $node instanceof StaticPropertyFetch) { // PHPStan false positive, when variable has type[] docblock, but default array is missing - if ($this->isPropertyFetchWithArrayDefault($node) === false) { + if (! $this->isPropertyFetchWithArrayDefault($node)) { return false; } } diff --git a/packages/NodeTypeResolver/src/PHPStan/Type/StaticTypeAnalyzer.php b/packages/NodeTypeResolver/src/PHPStan/Type/StaticTypeAnalyzer.php index 2523604b36f8..5aadc75a677f 100644 --- a/packages/NodeTypeResolver/src/PHPStan/Type/StaticTypeAnalyzer.php +++ b/packages/NodeTypeResolver/src/PHPStan/Type/StaticTypeAnalyzer.php @@ -4,7 +4,9 @@ namespace Rector\NodeTypeResolver\PHPStan\Type; +use PHPStan\Type\ArrayType; use PHPStan\Type\BooleanType; +use PHPStan\Type\Constant\ConstantArrayType; use PHPStan\Type\ConstantScalarType; use PHPStan\Type\FloatType; use PHPStan\Type\IntegerType; @@ -13,6 +15,7 @@ use PHPStan\Type\ObjectType; use PHPStan\Type\StringType; use PHPStan\Type\Type; +use PHPStan\Type\UnionType; final class StaticTypeAnalyzer { @@ -26,6 +29,18 @@ public function areTypesAlwaysTruable(array $types): bool } foreach ($types as $type) { + if ($type instanceof ConstantArrayType) { + continue; + } + + if ($type instanceof ArrayType) { + return false; + } + + if ($this->isNullable($type)) { + return false; + } + if ($type instanceof MixedType) { return false; } @@ -51,6 +66,21 @@ public function areTypesAlwaysTruable(array $types): bool return true; } + public function isNullable(Type $type): bool + { + if (! $type instanceof UnionType) { + return false; + } + + foreach ($type->getTypes() as $unionedType) { + if ($unionedType instanceof NullType) { + return true; + } + } + + return false; + } + private function isScalarType(Type $type): bool { if ($type instanceof NullType) { diff --git a/packages/NodeTypeResolver/src/PerNodeTypeResolver/VariableTypeResolver.php b/packages/NodeTypeResolver/src/PerNodeTypeResolver/VariableTypeResolver.php index dcfb190eea46..924c4a1eaac2 100644 --- a/packages/NodeTypeResolver/src/PerNodeTypeResolver/VariableTypeResolver.php +++ b/packages/NodeTypeResolver/src/PerNodeTypeResolver/VariableTypeResolver.php @@ -110,7 +110,7 @@ private function resolveNodeScope(Node $node): ?Scope { /** @var Scope|null $nodeScope */ $nodeScope = $node->getAttribute(AttributeKey::SCOPE); - if ($nodeScope) { + if ($nodeScope !== null) { return $nodeScope; } @@ -120,7 +120,7 @@ private function resolveNodeScope(Node $node): ?Scope /** @var string $traitName */ $traitName = $node->getAttribute(AttributeKey::CLASS_NAME); $traitNodeScope = $this->traitNodeScopeCollector->getScopeForTraitAndNode($traitName, $node); - if ($traitNodeScope) { + if ($traitNodeScope !== null) { return $traitNodeScope; } } @@ -128,7 +128,7 @@ private function resolveNodeScope(Node $node): ?Scope $parentNode = $node->getAttribute(AttributeKey::PARENT_NODE); if ($parentNode instanceof Node) { $parentNodeScope = $parentNode->getAttribute(AttributeKey::SCOPE); - if ($parentNodeScope) { + if ($parentNodeScope !== null) { return $parentNodeScope; } } @@ -137,7 +137,7 @@ private function resolveNodeScope(Node $node): ?Scope $method = $node->getAttribute(AttributeKey::METHOD_NODE); if ($method instanceof Node) { $methodNodeScope = $method->getAttribute(AttributeKey::SCOPE); - if ($methodNodeScope) { + if ($methodNodeScope !== null) { return $methodNodeScope; } } diff --git a/packages/NodeTypeResolver/src/PhpDoc/NodeAnalyzer/DocBlockManipulator.php b/packages/NodeTypeResolver/src/PhpDoc/NodeAnalyzer/DocBlockManipulator.php index 0c2ddbe7451c..c7a1b9885e5c 100644 --- a/packages/NodeTypeResolver/src/PhpDoc/NodeAnalyzer/DocBlockManipulator.php +++ b/packages/NodeTypeResolver/src/PhpDoc/NodeAnalyzer/DocBlockManipulator.php @@ -412,7 +412,7 @@ public function changeUnderscoreType(Node $node, string $namespacePrefix, array return $node; }); - if ($this->hasPhpDocChanged === false) { + if (! $this->hasPhpDocChanged) { return; } @@ -523,12 +523,7 @@ private function areTypesEquals(Type $firstType, Type $secondType): bool if ($firstTypeHash === $secondTypeHash) { return true; } - - if ($this->areArrayTypeWithSingleObjectChildToParent($firstType, $secondType)) { - return true; - } - - return false; + return $this->areArrayTypeWithSingleObjectChildToParent($firstType, $secondType); } /** diff --git a/packages/NodeTypeResolver/src/StaticTypeMapper.php b/packages/NodeTypeResolver/src/StaticTypeMapper.php index 854b1dc06c83..4e659aaac79d 100644 --- a/packages/NodeTypeResolver/src/StaticTypeMapper.php +++ b/packages/NodeTypeResolver/src/StaticTypeMapper.php @@ -244,7 +244,7 @@ public function mapPHPStanTypeToPhpParserNode(Type $phpStanType, ?string $kind = if ($phpStanType instanceof UnionType) { // match array types $arrayNode = $this->matchArrayTypes($phpStanType); - if ($arrayNode) { + if ($arrayNode !== null) { return $arrayNode; } @@ -443,6 +443,7 @@ public function mapPhpParserNodePHPStanType(Node $node): Type if ($node instanceof Name) { $name = $node->toString(); + if (ClassExistenceStaticHelper::doesClassLikeExist($name)) { return new FullyQualifiedObjectType($node->toString()); } diff --git a/packages/NodeTypeResolver/src/Type/TypeExtension/KernelGetContainerAfterBootReturnTypeExtension.php b/packages/NodeTypeResolver/src/Type/TypeExtension/KernelGetContainerAfterBootReturnTypeExtension.php index eae67b3eedaa..e08ea040d7b0 100644 --- a/packages/NodeTypeResolver/src/Type/TypeExtension/KernelGetContainerAfterBootReturnTypeExtension.php +++ b/packages/NodeTypeResolver/src/Type/TypeExtension/KernelGetContainerAfterBootReturnTypeExtension.php @@ -34,7 +34,7 @@ public function getTypeFromMethodCall( ): Type { $returnType = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants())->getReturnType(); - if ($this->isCalledAfterBoot($scope, $methodCall) === false) { + if (! $this->isCalledAfterBoot($scope, $methodCall)) { return $returnType; } diff --git a/packages/PHPStan/src/Type/FullyQualifiedObjectType.php b/packages/PHPStan/src/Type/FullyQualifiedObjectType.php index fed6b0325778..83d7582b0b24 100644 --- a/packages/PHPStan/src/Type/FullyQualifiedObjectType.php +++ b/packages/PHPStan/src/Type/FullyQualifiedObjectType.php @@ -9,6 +9,7 @@ use PhpParser\Node\Stmt\Use_; use PhpParser\Node\Stmt\UseUse; use PHPStan\Type\ObjectType; +use Rector\NodeTypeResolver\Node\AttributeKey; final class FullyQualifiedObjectType extends ObjectType { @@ -33,19 +34,28 @@ public function getShortName(): string public function getShortNameNode(): Name { - return new Name($this->getShortName()); + $name = new Name($this->getShortName()); + $name->setAttribute('virtual_node', true); + + return $name; } public function getUseNode(): Use_ { - $useUse = new UseUse(new Name($this->getClassName())); + $name = new Name($this->getClassName()); + $useUse = new UseUse($name); + + $name->setAttribute(AttributeKey::PARENT_NODE, $useUse); return new Use_([$useUse]); } public function getFunctionUseNode(): Use_ { - $useUse = new UseUse(new Name($this->getClassName()), null, Use_::TYPE_FUNCTION); + $name = new Name($this->getClassName()); + $useUse = new UseUse($name, null, Use_::TYPE_FUNCTION); + + $name->setAttribute(AttributeKey::PARENT_NODE, $useUse); return new Use_([$useUse]); } diff --git a/packages/PHPStan/src/TypeFactoryStaticHelper.php b/packages/PHPStan/src/TypeFactoryStaticHelper.php index 125134ad4cae..bfd9d3bd56c0 100644 --- a/packages/PHPStan/src/TypeFactoryStaticHelper.php +++ b/packages/PHPStan/src/TypeFactoryStaticHelper.php @@ -19,11 +19,7 @@ public static function createUnionObjectType(array $types): UnionType { $objectTypes = []; foreach ($types as $type) { - if ($type instanceof Type) { - $objectTypes[] = $type; - } else { - $objectTypes[] = new ObjectType($type); - } + $objectTypes[] = $type instanceof Type ? $type : new ObjectType($type); } // this is needed to prevent missing broker static fatal error, for tests with missing class diff --git a/packages/PHPUnit/src/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector.php b/packages/PHPUnit/src/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector.php index 4685c25d3747..06fa1e311d31 100644 --- a/packages/PHPUnit/src/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector.php +++ b/packages/PHPUnit/src/Rector/ClassMethod/AddDoesNotPerformAssertionToNonAssertingTestRector.php @@ -129,18 +129,13 @@ private function shouldSkipClassMethod(ClassMethod $classMethod): bool return true; } - if ($classMethod->getDocComment()) { + if ($classMethod->getDocComment() !== null) { $text = $classMethod->getDocComment(); if (Strings::match($text->getText(), '#@expectedException\b#')) { return true; } } - - if ($this->containsAssertCall($classMethod)) { - return true; - } - - return false; + return $this->containsAssertCall($classMethod); } private function addDoesNotPerformAssertion(ClassMethod $classMethod): void @@ -192,21 +187,7 @@ private function hasDirectAssertCall(ClassMethod $classMethod): bool return false; } - if ($this->isName($node->name, 'assert*')) { - return true; - } - - // expectException(...) - if ($this->isName($node->name, 'expectException*')) { - return true; - } - - // setExpectException (deprecated method) - if ($this->isName($node->name, 'setExpectedException*')) { - return true; - } - - return false; + return $this->isNames($node->name, ['assert*', 'expectException*', 'setExpectedException*']); }); } @@ -229,7 +210,7 @@ private function hasNestedAssertCall(ClassMethod $classMethod): bool return false; } - if ($classMethod) { + if ($classMethod !== null) { return $this->containsAssertCall($classMethod); } @@ -244,12 +225,12 @@ private function findClassMethod(Node $node): ?ClassMethod { if ($node instanceof MethodCall) { $classMethod = $this->parsedNodesByType->findClassMethodByMethodCall($node); - if ($classMethod) { + if ($classMethod !== null) { return $classMethod; } } elseif ($node instanceof StaticCall) { $classMethod = $this->parsedNodesByType->findClassMethodByStaticCall($node); - if ($classMethod) { + if ($classMethod !== null) { return $classMethod; } } diff --git a/packages/PHPUnit/src/Rector/Class_/AddSeeTestAnnotationRector.php b/packages/PHPUnit/src/Rector/Class_/AddSeeTestAnnotationRector.php index 7983b47d1746..6ff63847bcb0 100644 --- a/packages/PHPUnit/src/Rector/Class_/AddSeeTestAnnotationRector.php +++ b/packages/PHPUnit/src/Rector/Class_/AddSeeTestAnnotationRector.php @@ -115,7 +115,7 @@ private function shouldSkipClass(Class_ $class): bool } // is the @see annotation already added - if ($class->getDocComment()) { + if ($class->getDocComment() !== null) { /** @var string $docCommentText */ $docCommentText = $class->getDocComment()->getText(); @@ -160,7 +160,7 @@ private function createSeePhpDocTagNode(string $className): PhpDocTagNode */ private function getPhpUnitTestCaseClasses(): array { - if ($this->phpUnitTestCaseClasses) { + if ($this->phpUnitTestCaseClasses !== []) { return $this->phpUnitTestCaseClasses; } diff --git a/packages/PHPUnit/src/Rector/Class_/ArrayArgumentInTestToDataProviderRector.php b/packages/PHPUnit/src/Rector/Class_/ArrayArgumentInTestToDataProviderRector.php index f45f15b2d95a..bd91ddeae8d8 100644 --- a/packages/PHPUnit/src/Rector/Class_/ArrayArgumentInTestToDataProviderRector.php +++ b/packages/PHPUnit/src/Rector/Class_/ArrayArgumentInTestToDataProviderRector.php @@ -271,7 +271,7 @@ private function collectParamAndArgsFromArray(Array_ $array, string $variableNam $itemsStaticType = $this->resolveItemStaticType($array, $isNestedArray); - if ($isNestedArray === false) { + if (! $isNestedArray) { foreach ($array->items as $arrayItem) { $variable = new Variable($variableName . ($i === 1 ? '' : $i)); @@ -374,7 +374,7 @@ private function resolveUniqueArrayStaticTypes(Array_ $array): Type private function resolveItemStaticType(Array_ $array, bool $isNestedArray): Type { $staticTypes = []; - if ($isNestedArray === false) { + if (! $isNestedArray) { foreach ($array->items as $arrayItem) { $arrayItemStaticType = $this->getStaticType($arrayItem->value); if ($arrayItemStaticType) { diff --git a/packages/PHPUnit/src/Rector/MethodCall/WithConsecutiveArgToArrayRector.php b/packages/PHPUnit/src/Rector/MethodCall/WithConsecutiveArgToArrayRector.php index 9a0f37c65a46..412f26478ea8 100644 --- a/packages/PHPUnit/src/Rector/MethodCall/WithConsecutiveArgToArrayRector.php +++ b/packages/PHPUnit/src/Rector/MethodCall/WithConsecutiveArgToArrayRector.php @@ -5,6 +5,7 @@ namespace Rector\PHPUnit\Rector\MethodCall; use PhpParser\Node; +use PhpParser\Node\Arg; use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Scalar\String_; @@ -140,7 +141,7 @@ public function refactor(Node $node): ?Node // split into chunks of X parameters $valueChunks = array_chunk($values, $numberOfParameters); foreach ($valueChunks as $valueChunk) { - $node->args[] = new Node\Arg($this->createArray($valueChunk)); + $node->args[] = new Arg($this->createArray($valueChunk)); } return $node; diff --git a/packages/PSR4/src/FileRelocationResolver.php b/packages/PSR4/src/FileRelocationResolver.php index b9e98e3d3123..427c0cf058d7 100644 --- a/packages/PSR4/src/FileRelocationResolver.php +++ b/packages/PSR4/src/FileRelocationResolver.php @@ -111,14 +111,14 @@ private function resolveNearestRootWithCategory( $removedParts[] = $reversedNamePart; } - if ($hasStopped === false) { + if (! $hasStopped) { $rootNameParts = $nameParts; $rootNameParts[] = $suffixName; } else { $rootNameParts = array_reverse($reversedNameParts); $rootNameParts[] = $suffixName; - if ($removedParts) { + if ($removedParts !== []) { $rootNameParts = array_merge($rootNameParts, $removedParts); } } diff --git a/packages/PSR4/src/Rector/Namespace_/NormalizeNamespaceByPSR4ComposerAutoloadRector.php b/packages/PSR4/src/Rector/Namespace_/NormalizeNamespaceByPSR4ComposerAutoloadRector.php index 21b59a626447..dc4617480930 100644 --- a/packages/PSR4/src/Rector/Namespace_/NormalizeNamespaceByPSR4ComposerAutoloadRector.php +++ b/packages/PSR4/src/Rector/Namespace_/NormalizeNamespaceByPSR4ComposerAutoloadRector.php @@ -94,7 +94,7 @@ public function refactor(Node $node): ?Node $newUseImports = array_unique($newUseImports); - if ($newUseImports) { + if ($newUseImports !== []) { $useImports = $this->createUses($newUseImports); $node->stmts = array_merge($useImports, $node->stmts); } diff --git a/packages/Php56/src/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php b/packages/Php56/src/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php index 9591a43ad6df..40d4159cff6a 100644 --- a/packages/Php56/src/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php +++ b/packages/Php56/src/Rector/FunctionLike/AddDefaultValueForUndefinedVariableRector.php @@ -197,11 +197,7 @@ private function shouldSkipVariable(Variable $variable): bool } $variableName = $this->getName($variable); - if ($variableName === null) { - return true; - } - - return false; + return $variableName === null; } private function isStaticVariable(Node $parentNode): bool diff --git a/packages/Php70/src/EregToPcreTransformer.php b/packages/Php70/src/EregToPcreTransformer.php index 0b7393b20119..5dd6c97fab3c 100644 --- a/packages/Php70/src/EregToPcreTransformer.php +++ b/packages/Php70/src/EregToPcreTransformer.php @@ -46,10 +46,8 @@ public function ere2pcre(string $s, bool $ignorecase): string if (isset($icache[$s])) { return $icache[$s]; } - } else { - if (isset($cache[$s])) { - return $cache[$s]; - } + } elseif (isset($cache[$s])) { + return $cache[$s]; } [$r, $i] = $this->_ere2pcre($s, 0); if ($i !== strlen($s)) { diff --git a/packages/Php71/src/Rector/FuncCall/RemoveExtraParametersRector.php b/packages/Php71/src/Rector/FuncCall/RemoveExtraParametersRector.php index 5ecf2b4cb4e2..fc4dc3878405 100644 --- a/packages/Php71/src/Rector/FuncCall/RemoveExtraParametersRector.php +++ b/packages/Php71/src/Rector/FuncCall/RemoveExtraParametersRector.php @@ -99,12 +99,7 @@ private function shouldSkip(Node $node): bool if ($this->callManipulator->isVariadic($reflectionFunctionLike, $node)) { return true; } - - if ($reflectionFunctionLike->getNumberOfParameters() >= count($node->args)) { - return true; - } - - return false; + return $reflectionFunctionLike->getNumberOfParameters() >= count($node->args); } /** diff --git a/packages/Php73/src/Rector/FuncCall/ArrayKeyFirstLastRector.php b/packages/Php73/src/Rector/FuncCall/ArrayKeyFirstLastRector.php index c3001a71bf3e..acbee72a0696 100644 --- a/packages/Php73/src/Rector/FuncCall/ArrayKeyFirstLastRector.php +++ b/packages/Php73/src/Rector/FuncCall/ArrayKeyFirstLastRector.php @@ -128,11 +128,6 @@ private function shouldSkip(FuncCall $funcCall): bool if (function_exists(self::ARRAY_KEY_FIRST) && function_exists(self::ARRAY_KEY_LAST)) { return false; } - - if ($this->isNames($funcCall, ['reset', 'end'])) { - return true; - } - - return false; + return $this->isNames($funcCall, ['reset', 'end']); } } diff --git a/packages/Php74/src/Rector/LNumber/AddLiteralSeparatorToNumberRector.php b/packages/Php74/src/Rector/LNumber/AddLiteralSeparatorToNumberRector.php index d7f953b9908a..b443555f121b 100644 --- a/packages/Php74/src/Rector/LNumber/AddLiteralSeparatorToNumberRector.php +++ b/packages/Php74/src/Rector/LNumber/AddLiteralSeparatorToNumberRector.php @@ -112,13 +112,8 @@ private function shouldSkip(Node $node, string $numericValueAsString): bool if (Strings::match($numericValueAsString, '#e#i')) { return true; } - // too short - if (Strings::length($numericValueAsString) <= self::GROUP_SIZE) { - return true; - } - - return false; + return Strings::length($numericValueAsString) <= self::GROUP_SIZE; } /** diff --git a/packages/Php74/src/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php b/packages/Php74/src/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php index c6c2f5a73d28..d4c87e2fb604 100644 --- a/packages/Php74/src/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php +++ b/packages/Php74/src/Rector/MethodCall/ChangeReflectionTypeToStringToGetNameRector.php @@ -179,12 +179,7 @@ private function shouldSkipMethodCall(MethodCall $methodCall): bool if ($parentNode instanceof Ternary) { return true; } - - if ($parentNode instanceof Return_) { - return true; - } - - return false; + return $parentNode instanceof Return_; } private function isReflectionParameterGetTypeMethodCall(MethodCall $methodCall): bool @@ -219,7 +214,7 @@ private function isReflectionFunctionAbstractGetReturnTypeMethodCall(MethodCall private function refactorReflectionFunctionGetReturnType(MethodCall $methodCall): Node { $refactoredMethodCall = $this->refactorIfHasReturnTypeWasCalled($methodCall); - if ($refactoredMethodCall) { + if ($refactoredMethodCall !== null) { return $refactoredMethodCall; } diff --git a/packages/Renaming/tests/Rector/Class_/RenameClassRector/NamePostImportTest.php b/packages/Renaming/tests/Rector/Class_/RenameClassRector/AutoImportNamesParameterTest.php similarity index 68% rename from packages/Renaming/tests/Rector/Class_/RenameClassRector/NamePostImportTest.php rename to packages/Renaming/tests/Rector/Class_/RenameClassRector/AutoImportNamesParameterTest.php index 9af61b05d10a..b3dfac270ce6 100644 --- a/packages/Renaming/tests/Rector/Class_/RenameClassRector/NamePostImportTest.php +++ b/packages/Renaming/tests/Rector/Class_/RenameClassRector/AutoImportNamesParameterTest.php @@ -5,13 +5,14 @@ namespace Rector\Renaming\Tests\Rector\Class_\RenameClassRector; use Iterator; +use Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector; use Rector\Configuration\Option; use Rector\Renaming\Rector\Class_\RenameClassRector; use Rector\Renaming\Tests\Rector\Class_\RenameClassRector\Source\NewClass; use Rector\Renaming\Tests\Rector\Class_\RenameClassRector\Source\OldClass; use Rector\Testing\PHPUnit\AbstractRectorTestCase; -final class NamePostImportTest extends AbstractRectorTestCase +final class AutoImportNamesParameterTest extends AbstractRectorTestCase { protected function tearDown(): void { @@ -30,7 +31,9 @@ public function test(string $filePath): void public function provideDataForTest(): Iterator { - yield [__DIR__ . '/Fixture/class_to_new_with_post_import.php.inc']; + yield [__DIR__ . '/Fixture/AutoImportNamesParameter/class_to_new_with_post_import.php.inc']; + yield [__DIR__ . '/Fixture/AutoImportNamesParameter/partial_expression.php.inc']; + yield [__DIR__ . '/Fixture/AutoImportNamesParameter/skip_closure_me.php.inc']; } /** @@ -39,6 +42,8 @@ public function provideDataForTest(): Iterator protected function getRectorsWithConfiguration(): array { return [ + # this class causes to "partial_expression.php.inc" to fail + SimplifyEmptyArrayCheckRector::class => [], RenameClassRector::class => [ '$oldToNewClasses' => [ OldClass::class => NewClass::class, diff --git a/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/class_to_new_with_post_import.php.inc b/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/AutoImportNamesParameter/class_to_new_with_post_import.php.inc similarity index 88% rename from packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/class_to_new_with_post_import.php.inc rename to packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/AutoImportNamesParameter/class_to_new_with_post_import.php.inc index aea9f805e40a..86746b4c3ddd 100644 --- a/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/class_to_new_with_post_import.php.inc +++ b/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/AutoImportNamesParameter/class_to_new_with_post_import.php.inc @@ -1,6 +1,6 @@ +----- + diff --git a/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/AutoImportNamesParameter/skip_closure_me.php.inc b/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/AutoImportNamesParameter/skip_closure_me.php.inc new file mode 100644 index 000000000000..113f7a2c7b26 --- /dev/null +++ b/packages/Renaming/tests/Rector/Class_/RenameClassRector/Fixture/AutoImportNamesParameter/skip_closure_me.php.inc @@ -0,0 +1,12 @@ +builderFactory->use($name); - if ($alias) { + if ($alias !== '') { $useBuilder->as($alias); } diff --git a/packages/SOLID/src/Rector/ClassConst/PrivatizeLocalClassConstantRector.php b/packages/SOLID/src/Rector/ClassConst/PrivatizeLocalClassConstantRector.php index d6c0da9f7253..5d272e829f93 100644 --- a/packages/SOLID/src/Rector/ClassConst/PrivatizeLocalClassConstantRector.php +++ b/packages/SOLID/src/Rector/ClassConst/PrivatizeLocalClassConstantRector.php @@ -140,9 +140,9 @@ private function findParentClassConstant(string $class, string $constant): ?Clas if ($classNode !== null && $classNode->hasAttribute(AttributeKey::PARENT_CLASS_NAME)) { /** @var string $parentClassName */ $parentClassName = $classNode->getAttribute(AttributeKey::PARENT_CLASS_NAME); - if ($parentClassName) { + if ($parentClassName !== '') { $parentClassConstant = $this->parsedNodesByType->findClassConstant($parentClassName, $constant); - if ($parentClassConstant) { + if ($parentClassConstant !== null) { // Make sure the parent's constant has been refactored $this->refactor($parentClassConstant); diff --git a/packages/SOLID/src/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector.php b/packages/SOLID/src/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector.php index 760590edb955..a660ccec4584 100644 --- a/packages/SOLID/src/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector.php +++ b/packages/SOLID/src/Rector/Class_/MakeUnusedClassesWithChildrenAbstractRector.php @@ -72,17 +72,17 @@ public function refactor(Node $node): ?Node } // 1. is in static call? - if ($this->parsedNodesByType->findMethodCallsOnClass($className)) { + if ($this->parsedNodesByType->findMethodCallsOnClass($className) !== []) { return null; } // 2. is in new? - if ($this->parsedNodesByType->findNewNodesByClass($className)) { + if ($this->parsedNodesByType->findNewNodesByClass($className) !== []) { return null; } // 3. does it have any children - if (! $this->parsedNodesByType->findChildrenOfClass($className)) { + if ($this->parsedNodesByType->findChildrenOfClass($className) === []) { return null; } diff --git a/packages/StrictCodeQuality/src/Rector/Stmt/VarInlineAnnotationToAssertRector.php b/packages/StrictCodeQuality/src/Rector/Stmt/VarInlineAnnotationToAssertRector.php index c1f130497ba3..938fda7302df 100644 --- a/packages/StrictCodeQuality/src/Rector/Stmt/VarInlineAnnotationToAssertRector.php +++ b/packages/StrictCodeQuality/src/Rector/Stmt/VarInlineAnnotationToAssertRector.php @@ -94,7 +94,7 @@ public function refactor(Node $node): ?Node } $isVariableJustCreated = $this->isVariableJustCreated($node, $docVariableName); - if ($isVariableJustCreated === false) { + if (! $isVariableJustCreated) { return $this->refactorFreshlyCreatedNode($node, $phpDocInfo, $variable); } diff --git a/packages/Symfony/src/Rector/Console/ConsoleExecuteReturnIntRector.php b/packages/Symfony/src/Rector/Console/ConsoleExecuteReturnIntRector.php index 9490f0ee1841..7ff863b5c22e 100644 --- a/packages/Symfony/src/Rector/Console/ConsoleExecuteReturnIntRector.php +++ b/packages/Symfony/src/Rector/Console/ConsoleExecuteReturnIntRector.php @@ -126,7 +126,7 @@ private function addReturn0ToMethod(ClassMethod $classMethod): void private function setReturnTo0InsteadOfNull(Return_ $return): void { - if (! $return->expr) { + if ($return->expr === null) { $return->expr = new LNumber(0); return; } diff --git a/packages/Symfony/src/Rector/Form/FormIsValidRector.php b/packages/Symfony/src/Rector/Form/FormIsValidRector.php index 8bd91ad3220d..80b69f01b2ee 100644 --- a/packages/Symfony/src/Rector/Form/FormIsValidRector.php +++ b/packages/Symfony/src/Rector/Form/FormIsValidRector.php @@ -102,11 +102,7 @@ private function shouldSkipMethodCall(MethodCall $methodCall): bool } $variableName = $this->getName($methodCall->var); - if ($variableName === null) { - return true; - } - - return false; + return $variableName === null; } private function isIsSubmittedByAlreadyCalledOnVariable(Variable $variable): bool diff --git a/packages/Symfony/src/Rector/MethodCall/MakeDispatchFirstArgumentEventRector.php b/packages/Symfony/src/Rector/MethodCall/MakeDispatchFirstArgumentEventRector.php index b6be6db72212..e5809c14df68 100644 --- a/packages/Symfony/src/Rector/MethodCall/MakeDispatchFirstArgumentEventRector.php +++ b/packages/Symfony/src/Rector/MethodCall/MakeDispatchFirstArgumentEventRector.php @@ -91,12 +91,7 @@ private function shouldSkip(MethodCall $methodCall): bool if (! $this->isName($methodCall->name, 'dispatch')) { return true; } - - if (! isset($methodCall->args[1])) { - return true; - } - - return false; + return ! isset($methodCall->args[1]); } private function refactorStringArgument(MethodCall $methodCall): Node diff --git a/packages/SymfonyCodeQuality/src/Rector/Class_/EventListenerToEventSubscriberRector.php b/packages/SymfonyCodeQuality/src/Rector/Class_/EventListenerToEventSubscriberRector.php index 8a2340d9ebf1..4f77a86be09c 100644 --- a/packages/SymfonyCodeQuality/src/Rector/Class_/EventListenerToEventSubscriberRector.php +++ b/packages/SymfonyCodeQuality/src/Rector/Class_/EventListenerToEventSubscriberRector.php @@ -120,7 +120,7 @@ class SomeEventSubscriber implements EventSubscriberInterface */ public static function getSubscribedEvents(): array { - return ['some_event' => 'methodToBeCalled']; + return ['some_event' => 'methodToBeCalled']; } public function methodToBeCalled() diff --git a/packages/TypeDeclaration/src/PHPStan/Type/ObjectTypeSpecifier.php b/packages/TypeDeclaration/src/PHPStan/Type/ObjectTypeSpecifier.php index 0324d2602932..f01dcd5515fc 100644 --- a/packages/TypeDeclaration/src/PHPStan/Type/ObjectTypeSpecifier.php +++ b/packages/TypeDeclaration/src/PHPStan/Type/ObjectTypeSpecifier.php @@ -30,17 +30,17 @@ public function narrowToFullyQualifiedOrAlaisedObjectType(Node $node, ObjectType } $aliasedObjectType = $this->matchAliasedObjectType($node, $objectType); - if ($aliasedObjectType) { + if ($aliasedObjectType !== null) { return $aliasedObjectType; } $shortenedObjectType = $this->matchShortenedObjectType($node, $objectType); - if ($shortenedObjectType) { + if ($shortenedObjectType !== null) { return $shortenedObjectType; } $sameNamespacedObjectType = $this->matchSameNamespacedObjectType($node, $objectType); - if ($sameNamespacedObjectType) { + if ($sameNamespacedObjectType !== null) { return $sameNamespacedObjectType; } @@ -89,17 +89,17 @@ private function matchShortenedObjectType(Node $node, ObjectType $objectType): ? foreach ($uses as $use) { foreach ($use->uses as $useUse) { - if ($useUse->alias) { + if ($useUse->alias !== null) { continue; } $partialNamespaceObjectType = $this->matchPartialNamespaceObjectType($objectType, $useUse); - if ($partialNamespaceObjectType) { + if ($partialNamespaceObjectType !== null) { return $partialNamespaceObjectType; } $partialNamespaceObjectType = $this->matchClassWithLastUseImportPart($objectType, $useUse); - if ($partialNamespaceObjectType) { + if ($partialNamespaceObjectType !== null) { return $partialNamespaceObjectType; } } diff --git a/packages/TypeDeclaration/src/Rector/ClassMethod/AddArrayReturnDocTypeRector.php b/packages/TypeDeclaration/src/Rector/ClassMethod/AddArrayReturnDocTypeRector.php index 1dea095da146..abcf858a87ed 100644 --- a/packages/TypeDeclaration/src/Rector/ClassMethod/AddArrayReturnDocTypeRector.php +++ b/packages/TypeDeclaration/src/Rector/ClassMethod/AddArrayReturnDocTypeRector.php @@ -153,12 +153,7 @@ private function shouldSkipArrayType(ArrayType $arrayType, ClassMethod $classMet if ($this->isNewAndCurrentTypeBothCallable($arrayType, $classMethod)) { return true; } - - if ($this->isMixedOfSpecificOverride($arrayType, $classMethod)) { - return true; - } - - return false; + return $this->isMixedOfSpecificOverride($arrayType, $classMethod); } private function isNewAndCurrentTypeBothCallable(ArrayType $newArrayType, ClassMethod $classMethod): bool @@ -176,12 +171,7 @@ private function isNewAndCurrentTypeBothCallable(ArrayType $newArrayType, ClassM if (! $newArrayType->getItemType()->isCallable()->yes()) { return false; } - - if (! $currentReturnType->getItemType()->isCallable()->yes()) { - return false; - } - - return true; + return $currentReturnType->getItemType()->isCallable()->yes(); } private function isMixedOfSpecificOverride(ArrayType $arrayType, ClassMethod $classMethod): bool @@ -196,10 +186,6 @@ private function isMixedOfSpecificOverride(ArrayType $arrayType, ClassMethod $cl } $currentReturnType = $currentPhpDocInfo->getReturnType(); - if (! $currentReturnType instanceof ArrayType) { - return false; - } - - return true; + return $currentReturnType instanceof ArrayType; } } diff --git a/packages/TypeDeclaration/src/Rector/ClassMethod/AddMethodCallBasedParamTypeRector.php b/packages/TypeDeclaration/src/Rector/ClassMethod/AddMethodCallBasedParamTypeRector.php index 71507bb812b1..0405f5160a67 100644 --- a/packages/TypeDeclaration/src/Rector/ClassMethod/AddMethodCallBasedParamTypeRector.php +++ b/packages/TypeDeclaration/src/Rector/ClassMethod/AddMethodCallBasedParamTypeRector.php @@ -158,12 +158,7 @@ private function skipArgumentStaticType(Node $node, Type $argumentStaticType, in } $parameterStaticType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($parameter->type); - // already completed → skip - if ($parameterStaticType->equals($argumentStaticType)) { - return true; - } - - return false; + return $parameterStaticType->equals($argumentStaticType); } } diff --git a/packages/TypeDeclaration/src/Rector/FunctionLike/ReturnTypeDeclarationRector.php b/packages/TypeDeclaration/src/Rector/FunctionLike/ReturnTypeDeclarationRector.php index c7357feba3f3..599e7b7b8a67 100644 --- a/packages/TypeDeclaration/src/Rector/FunctionLike/ReturnTypeDeclarationRector.php +++ b/packages/TypeDeclaration/src/Rector/FunctionLike/ReturnTypeDeclarationRector.php @@ -148,7 +148,7 @@ public function refactor(Node $node): ?Node // @see https://wiki.php.net/rfc/covariant-returns-and-contravariant-parameters if ($this->isAtLeastPhpVersion('7.4') && $isSubtype) { $node->returnType = $inferredReturnNode; - } elseif ($isSubtype === false) { // type override + } elseif (! $isSubtype) { // type override $node->returnType = $inferredReturnNode; } } else { @@ -167,7 +167,7 @@ public function refactor(Node $node): ?Node */ private function shouldSkip(Node $node): bool { - if ($this->overrideExistingReturnTypes === false) { + if (! $this->overrideExistingReturnTypes) { if ($node->returnType) { return true; } diff --git a/packages/TypeDeclaration/src/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php b/packages/TypeDeclaration/src/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php index ca56b67888f8..1fc251202c3d 100644 --- a/packages/TypeDeclaration/src/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php +++ b/packages/TypeDeclaration/src/TypeInferer/PropertyTypeInferer/ConstructorPropertyTypeInferer.php @@ -182,7 +182,7 @@ private function isParamNullable(Param $param): bool return true; } - if ($param->default) { + if ($param->default !== null) { $defaultValueStaticType = $this->nodeTypeResolver->getStaticType($param->default); if ($defaultValueStaticType instanceof NullType) { return true; diff --git a/packages/TypeDeclaration/src/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php b/packages/TypeDeclaration/src/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php index b3c249d05650..b7ba4ebdc481 100644 --- a/packages/TypeDeclaration/src/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php +++ b/packages/TypeDeclaration/src/TypeInferer/ReturnTypeInferer/YieldNodesReturnTypeInferer.php @@ -47,7 +47,7 @@ public function inferFunctionLike(FunctionLike $functionLike): Type $yieldNodes = $this->betterNodeFinder->findInstanceOf((array) $functionLike->stmts, Yield_::class); $types = []; - if (count($yieldNodes)) { + if (count($yieldNodes) > 0) { foreach ($yieldNodes as $yieldNode) { if ($yieldNode->value === null) { continue; diff --git a/packages/ZendToSymfony/src/Extension/ReportRoutesExtension.php b/packages/ZendToSymfony/src/Extension/ReportRoutesExtension.php index 872a15e16516..e14bb0d9ed43 100644 --- a/packages/ZendToSymfony/src/Extension/ReportRoutesExtension.php +++ b/packages/ZendToSymfony/src/Extension/ReportRoutesExtension.php @@ -36,11 +36,10 @@ public function run(): void $tableLines = []; foreach ($this->routeCollector->getRouteValueObjects() as $routeValueObject) { - if ($routeValueObject->getParams()) { - $paramsAsString = '$' . implode(', $', $routeValueObject->getParams()); - } else { - $paramsAsString = ''; - } + $paramsAsString = $routeValueObject->getParams() !== [] ? '$' . implode( + ', $', + $routeValueObject->getParams() + ) : ''; $tableLines[] = [ $routeValueObject->getControllerClass(), diff --git a/packages/ZendToSymfony/src/Rector/ClassMethod/ThisRequestToRequestParameterRector.php b/packages/ZendToSymfony/src/Rector/ClassMethod/ThisRequestToRequestParameterRector.php index 471cb7385d06..9ff2b9c7b9b1 100644 --- a/packages/ZendToSymfony/src/Rector/ClassMethod/ThisRequestToRequestParameterRector.php +++ b/packages/ZendToSymfony/src/Rector/ClassMethod/ThisRequestToRequestParameterRector.php @@ -94,7 +94,7 @@ public function refactor(Node $node): ?Node }); // add request argument - if ($hasRequest === false) { + if (! $hasRequest) { return null; } diff --git a/packages/ZendToSymfony/src/Rector/ClassMethod/ThisViewToThisRenderResponseRector.php b/packages/ZendToSymfony/src/Rector/ClassMethod/ThisViewToThisRenderResponseRector.php index de0a33387f56..adbe5ffbbd56 100644 --- a/packages/ZendToSymfony/src/Rector/ClassMethod/ThisViewToThisRenderResponseRector.php +++ b/packages/ZendToSymfony/src/Rector/ClassMethod/ThisViewToThisRenderResponseRector.php @@ -109,7 +109,7 @@ public function refactor(Node $node): ?Node return $node; }); - if ($hasRender === false) { + if (! $hasRender) { return null; } @@ -127,13 +127,8 @@ private function isZendViewPropertyFetch(PropertyFetch $propertyFetch): bool if ($this->isObjectType($propertyFetch, ZendClass::ZEND_VIEW)) { return true; } - // fallback if checked property is missing @var doc - if ($this->isNames($propertyFetch->name, ['_view', 'view'])) { - return true; - } - - return false; + return $this->isNames($propertyFetch->name, ['_view', 'view']); } /** diff --git a/rector-ci.yaml b/rector-ci.yaml index ba8d0d700787..98bf716d7459 100644 --- a/rector-ci.yaml +++ b/rector-ci.yaml @@ -1,9 +1,10 @@ parameters: + sets: + - "code-quality" + + auto_import_names: true + exclude_paths: - "/Fixture/" - - "/Fixtures/" - "/Source/" - "/Expected/" - - sets: - - "code-quality" diff --git a/rector.yaml b/rector.yaml index 740d5205c232..7b98c8de8fde 100644 --- a/rector.yaml +++ b/rector.yaml @@ -4,7 +4,6 @@ parameters: exclude_paths: - "/Fixture/" - - "/Fixtures/" - "/Expected/" - "/Source/" - "packages/Symfony/src/Bridge/DefaultAnalyzedSymfonyApplicationContainer.php" @@ -18,5 +17,3 @@ parameters: php_version_features: '7.1' services: - Rector\CodeQuality\Rector\FuncCall\ArrayMergeOfNonArraysToSimpleArrayRector: ~ -# Rector\PHPUnit\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector: ~ diff --git a/src/Application/RectorApplication.php b/src/Application/RectorApplication.php index 7aa5190dc6a9..586b2e0fe677 100644 --- a/src/Application/RectorApplication.php +++ b/src/Application/RectorApplication.php @@ -179,7 +179,7 @@ public function runOnFileInfos(array $fileInfos): void */ private function configureStepCount(SymfonyStyle $symfonyStyle): void { - if ($this->ciDetector->isCiDetected() === false) { + if (! $this->ciDetector->isCiDetected()) { return; } diff --git a/src/Bootstrap/SetOptionResolver.php b/src/Bootstrap/SetOptionResolver.php index 73e44957ca9f..62b9219e45a3 100644 --- a/src/Bootstrap/SetOptionResolver.php +++ b/src/Bootstrap/SetOptionResolver.php @@ -163,7 +163,7 @@ private function separateVersionedAndUnversionedSets(array $allSets): array foreach ($allSets as $set) { $hasVersion = (bool) Strings::match($set, '#\d#'); - if ($hasVersion === false) { + if (! $hasVersion) { $unversionedSets[] = $set; continue; } diff --git a/src/Console/Application.php b/src/Console/Application.php index 4c0b35060701..cc3666e13770 100644 --- a/src/Console/Application.php +++ b/src/Console/Application.php @@ -19,6 +19,7 @@ use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symplify\PackageBuilder\Console\Command\CommandNaming; +use Symplify\PackageBuilder\FileSystem\SmartFileInfo; final class Application extends SymfonyApplication { @@ -60,7 +61,7 @@ public function doRun(InputInterface $input, OutputInterface $output): int // switch working dir $newWorkDir = $this->getNewWorkingDir($input); - if ($newWorkDir) { + if ($newWorkDir !== '') { $oldWorkingDir = getcwd(); chdir($newWorkDir); $output->isDebug() && $output->writeln('Changed CWD form ' . $oldWorkingDir . ' to ' . getcwd()); @@ -81,7 +82,10 @@ public function doRun(InputInterface $input, OutputInterface $output): int $configPath = $this->configuration->getConfigFilePath(); if ($configPath) { - $output->writeln('Config file: ' . realpath($configPath)); + $configFileInfo = new SmartFileInfo($configPath); + $relativeConfigPath = $configFileInfo->getRelativeFilePathFromDirectory(getcwd()); + + $output->writeln('Config file: ' . $relativeConfigPath); $shouldFollowByNewline = true; } } diff --git a/src/Console/Command/ScreenFileCommand.php b/src/Console/Command/ScreenFileCommand.php index e5c955df063a..03670431a5a9 100644 --- a/src/Console/Command/ScreenFileCommand.php +++ b/src/Console/Command/ScreenFileCommand.php @@ -134,12 +134,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int private function decorateNodes(array $nodes): void { $this->callableNodeTraverser->traverseNodesWithCallable($nodes, function (Node $node): Node { - // not useful - if ($node instanceof Expression) { - $infoNode = $node->expr; - } else { - $infoNode = $node; - } + $infoNode = $node instanceof Expression ? $node->expr : $node; $data = $this->decorateNodeData($infoNode); diff --git a/src/Console/Output/ConsoleOutputFormatter.php b/src/Console/Output/ConsoleOutputFormatter.php index 5de080636fcf..3f399b58cf7b 100644 --- a/src/Console/Output/ConsoleOutputFormatter.php +++ b/src/Console/Output/ConsoleOutputFormatter.php @@ -116,7 +116,7 @@ private function reportErrors(array $errors): void private function reportRemovedFilesAndNodes(ErrorAndDiffCollector $errorAndDiffCollector): void { - if ($errorAndDiffCollector->getRemovedAndAddedFilesCount()) { + if ($errorAndDiffCollector->getRemovedAndAddedFilesCount() !== 0) { $this->symfonyStyle->note( sprintf('%d files were added/removed', $errorAndDiffCollector->getRemovedAndAddedFilesCount()) ); diff --git a/src/DependencyInjection/RectorContainerFactory.php b/src/DependencyInjection/RectorContainerFactory.php index ca6a37504bf8..573a2c04018b 100644 --- a/src/DependencyInjection/RectorContainerFactory.php +++ b/src/DependencyInjection/RectorContainerFactory.php @@ -41,7 +41,7 @@ public function createFromConfigs(array $configFiles): ContainerInterface $isDebug = InputDetector::isDebug(); $rectorKernel = new RectorKernel($environment, $isDebug); - if ($configFiles) { + if ($configFiles !== []) { $rectorKernel->setConfigs($configFiles); } diff --git a/src/NodeContainer/ParsedNodesByType.php b/src/NodeContainer/ParsedNodesByType.php index b5d6fdb81d90..59f054109443 100644 --- a/src/NodeContainer/ParsedNodesByType.php +++ b/src/NodeContainer/ParsedNodesByType.php @@ -337,7 +337,7 @@ public function findClassMethodByStaticCall(StaticCall $staticCall): ?ClassMetho $classNames = TypeUtils::getDirectClassNames($objectType); foreach ($classNames as $className) { $foundMethod = $this->findMethod($methodName, $className); - if ($foundMethod) { + if ($foundMethod !== null) { return $foundMethod; } } diff --git a/src/PhpDoc/PhpDocClassRenamer.php b/src/PhpDoc/PhpDocClassRenamer.php index d48803d85497..c657e02fdf18 100644 --- a/src/PhpDoc/PhpDocClassRenamer.php +++ b/src/PhpDoc/PhpDocClassRenamer.php @@ -56,7 +56,7 @@ public function changeTypeInAnnotationTypes(Node $node, array $oldToNewClasses): $this->processDoctrineRelationTagValueNode($oldToNewClasses, $phpDocInfo); $this->processSerializerTypeTagValueNode($oldToNewClasses, $phpDocInfo); - if ($this->shouldUpdate === false) { + if (! $this->shouldUpdate) { return; } diff --git a/src/PhpParser/Node/BetterNodeFinder.php b/src/PhpParser/Node/BetterNodeFinder.php index c52fcdea8ca7..e875a800e1c9 100644 --- a/src/PhpParser/Node/BetterNodeFinder.php +++ b/src/PhpParser/Node/BetterNodeFinder.php @@ -141,13 +141,8 @@ public function findClassLikes(array $nodes): array if (! $node instanceof ClassLike) { return false; } - // skip anonymous classes - if ($node instanceof Class_ && $node->isAnonymous()) { - return false; - } - - return true; + return ! ($node instanceof Class_ && $node->isAnonymous()); }); } diff --git a/src/PhpParser/Node/Manipulator/AssignManipulator.php b/src/PhpParser/Node/Manipulator/AssignManipulator.php index 8757d6bbf829..132ae6c23435 100644 --- a/src/PhpParser/Node/Manipulator/AssignManipulator.php +++ b/src/PhpParser/Node/Manipulator/AssignManipulator.php @@ -37,11 +37,7 @@ public function isLocalPropertyAssign(Node $node): bool return false; } - if ($node->var instanceof ArrayDimFetch) { - $potentialPropertyFetch = $node->var->var; - } else { - $potentialPropertyFetch = $node->var; - } + $potentialPropertyFetch = $node->var instanceof ArrayDimFetch ? $node->var->var : $node->var; return $potentialPropertyFetch instanceof PropertyFetch || $potentialPropertyFetch instanceof StaticPropertyFetch; } @@ -57,14 +53,7 @@ public function isLocalPropertyAssignWithPropertyNames(Node $node, array $proper return false; } - /** @var Assign $node */ - if ($node->var instanceof ArrayDimFetch) { - /** @var PropertyFetch|StaticPropertyFetch $propertyFetch */ - $propertyFetch = $node->var->var; - } else { - /** @var PropertyFetch|StaticPropertyFetch $propertyFetch */ - $propertyFetch = $node->var; - } + $propertyFetch = $node->var instanceof ArrayDimFetch ? $node->var->var : $node->var; return $this->nameResolver->isNames($propertyFetch, $propertyNames); } diff --git a/src/PhpParser/Node/Manipulator/ChildAndParentClassManipulator.php b/src/PhpParser/Node/Manipulator/ChildAndParentClassManipulator.php index e63d63a3c382..508e196e4acd 100644 --- a/src/PhpParser/Node/Manipulator/ChildAndParentClassManipulator.php +++ b/src/PhpParser/Node/Manipulator/ChildAndParentClassManipulator.php @@ -52,13 +52,13 @@ public function completeParentConstructor(Class_ $classNode, ClassMethod $classM // not in analyzed scope, nothing we can do $parentClassNode = $this->parsedNodesByType->findClass($parentClassName); - if ($parentClassNode) { + if ($parentClassNode !== null) { $this->completeParentConstructorBasedOnParentNode($parentClassNode, $classMethod); return; } // complete parent call for __construct() - if ($parentClassName) { + if ($parentClassName !== '') { if (method_exists($parentClassName, '__construct')) { $parentConstructCallNode = $this->nodeFactory->createParentConstructWithParams([]); $classMethod->stmts[] = new Expression($parentConstructCallNode); diff --git a/src/PhpParser/Node/Manipulator/PropertyFetchManipulator.php b/src/PhpParser/Node/Manipulator/PropertyFetchManipulator.php index fe8d9c7dd74d..4414cb009795 100644 --- a/src/PhpParser/Node/Manipulator/PropertyFetchManipulator.php +++ b/src/PhpParser/Node/Manipulator/PropertyFetchManipulator.php @@ -168,13 +168,8 @@ public function isVariableAssignToThisPropertyFetch(Node $node, string $variable if (! $node->var instanceof PropertyFetch) { return false; } - // must be local property - if (! $this->nameResolver->isName($node->var->var, 'this')) { - return false; - } - - return true; + return $this->nameResolver->isName($node->var->var, 'this'); } /** diff --git a/src/PhpParser/Printer/BetterStandardPrinter.php b/src/PhpParser/Printer/BetterStandardPrinter.php index 7dc02b1ed5e8..ca95d14ed035 100644 --- a/src/PhpParser/Printer/BetterStandardPrinter.php +++ b/src/PhpParser/Printer/BetterStandardPrinter.php @@ -105,13 +105,7 @@ protected function setIndentLevel(int $level): void */ protected function indent(): void { - if ($this->tabOrSpaceIndentCharacter === ' ') { - // 4 spaces - $multiplier = 4; - } else { - // 1 tab - $multiplier = 1; - } + $multiplier = $this->tabOrSpaceIndentCharacter === ' ' ? 4 : 1; $this->indentLevel += $multiplier; $this->nl .= str_repeat($this->tabOrSpaceIndentCharacter, $multiplier); diff --git a/src/Rector/AbstractPHPUnitRector.php b/src/Rector/AbstractPHPUnitRector.php index ad94d4ce50e3..5cb15f86e0ec 100644 --- a/src/Rector/AbstractPHPUnitRector.php +++ b/src/Rector/AbstractPHPUnitRector.php @@ -24,7 +24,7 @@ protected function isTestClassMethod(ClassMethod $classMethod): bool } $docComment = $classMethod->getDocComment(); - if ($docComment) { + if ($docComment !== null) { return (bool) Strings::match($docComment->getText(), '#@test\b#'); } diff --git a/src/Rector/AbstractRector.php b/src/Rector/AbstractRector.php index 82b4b0b7e72d..d08bf7bf52a4 100644 --- a/src/Rector/AbstractRector.php +++ b/src/Rector/AbstractRector.php @@ -4,11 +4,13 @@ namespace Rector\Rector; +use Nette\Utils\Strings; use PhpParser\BuilderFactory; use PhpParser\Node; use PhpParser\Node\Expr; use PhpParser\Node\Name; use PhpParser\Node\Stmt; +use PhpParser\Node\Stmt\Class_; use PhpParser\Node\Stmt\Expression; use PhpParser\NodeVisitorAbstract; use Rector\Commander\CommanderCollector; @@ -219,7 +221,7 @@ private function keepFileInfoAttribute(Node $node, Node $originalNode): void if ($originalNode->getAttribute(AttributeKey::FILE_INFO) !== null) { $node->setAttribute(AttributeKey::FILE_INFO, $originalNode->getAttribute(AttributeKey::FILE_INFO)); - } elseif ($originalNode->getAttribute(AttributeKey::PARENT_NODE)) { + } elseif ($originalNode->getAttribute(AttributeKey::PARENT_NODE) !== null) { /** @var Node $parentOriginalNode */ $parentOriginalNode = $originalNode->getAttribute(AttributeKey::PARENT_NODE); $node->setAttribute(AttributeKey::FILE_INFO, $parentOriginalNode->getAttribute(AttributeKey::FILE_INFO)); @@ -251,6 +253,17 @@ private function mirrorAttributes(Node $oldNode, Node $newNode): void } } + protected function isAnonymousClass(Node $node): bool + { + if (! $node instanceof Class_) { + return false; + } + + $className = $this->nameResolver->getName($node); + + return $className === null || Strings::contains($className, 'AnonymousClass'); + } + private function updateAttributes(Node $node): void { // update Resolved name attribute if name is changed diff --git a/src/Rector/Architecture/DependencyInjection/AnnotatedPropertyInjectToConstructorInjectionRector.php b/src/Rector/Architecture/DependencyInjection/AnnotatedPropertyInjectToConstructorInjectionRector.php index fbc33e5a9785..b46de1ab8ae4 100644 --- a/src/Rector/Architecture/DependencyInjection/AnnotatedPropertyInjectToConstructorInjectionRector.php +++ b/src/Rector/Architecture/DependencyInjection/AnnotatedPropertyInjectToConstructorInjectionRector.php @@ -92,13 +92,8 @@ private function shouldSkipProperty(Node $node): bool if (! $this->docBlockManipulator->hasTag($node, self::INJECT_ANNOTATION)) { return true; } - // it needs @var tag as well, to get the type - if (! $this->docBlockManipulator->hasTag($node, 'var')) { - return true; - } - - return false; + return ! $this->docBlockManipulator->hasTag($node, 'var'); } private function addPropertyToCollector(Property $property): void diff --git a/src/Rector/MethodCall/MethodCallToReturnRector.php b/src/Rector/MethodCall/MethodCallToReturnRector.php index e6b1bfe5be72..aec56e4e0a25 100644 --- a/src/Rector/MethodCall/MethodCallToReturnRector.php +++ b/src/Rector/MethodCall/MethodCallToReturnRector.php @@ -6,6 +6,7 @@ use PhpParser\Node; use PhpParser\Node\Expr\MethodCall; +use PhpParser\Node\Stmt\Expression; use PhpParser\Node\Stmt\Return_; use Rector\NodeTypeResolver\Node\AttributeKey; use Rector\Rector\AbstractRector; @@ -77,7 +78,7 @@ public function deny() */ public function getNodeTypes(): array { - return [Node\Stmt\Expression::class]; + return [Expression::class]; } /** diff --git a/src/Rector/Psr4/MultipleClassFileToPsr4ClassesRector.php b/src/Rector/Psr4/MultipleClassFileToPsr4ClassesRector.php index dab87754cc58..23dd9a670bb9 100644 --- a/src/Rector/Psr4/MultipleClassFileToPsr4ClassesRector.php +++ b/src/Rector/Psr4/MultipleClassFileToPsr4ClassesRector.php @@ -87,7 +87,7 @@ public function refactor(SmartFileInfo $smartFileInfo): void /** @var Namespace_[] $namespaceNodes */ $namespaceNodes = $this->betterNodeFinder->findInstanceOf($nodes, Namespace_::class); - if (count($namespaceNodes)) { + if (count($namespaceNodes) > 0) { $this->processNamespaceNodes($smartFileInfo, $namespaceNodes, $nodes, $shouldDelete); } else { $this->processNodesWithoutNamespace($nodes, $smartFileInfo, $shouldDelete); @@ -184,11 +184,7 @@ private function processNodesWithoutNamespace(array $nodes, SmartFileInfo $smart $fileDestination = $this->createClassLikeFileDestination($node, $smartFileInfo); - if ($declareNode) { - $nodes = [$declareNode, $node]; - } else { - $nodes = [$node]; - } + $nodes = $declareNode !== null ? [$declareNode, $node] : [$node]; // has file changed? if ($shouldDelete) { diff --git a/src/Rector/Typehint/ParentTypehintedArgumentRector.php b/src/Rector/Typehint/ParentTypehintedArgumentRector.php index 220925b72e5b..09ae71c65bcd 100644 --- a/src/Rector/Typehint/ParentTypehintedArgumentRector.php +++ b/src/Rector/Typehint/ParentTypehintedArgumentRector.php @@ -136,11 +136,7 @@ private function processClassMethodNodeWithTypehints(ClassMethod $classMethod, a continue; } - if ($type === '') { // remove type - $param->type = null; - } else { - $param->type = $this->staticTypeMapper->mapStringToPhpParserNode($type); - } + $param->type = $type === '' ? null : $this->staticTypeMapper->mapStringToPhpParserNode($type); } } } diff --git a/src/Standalone/RectorStandaloneRunner.php b/src/Standalone/RectorStandaloneRunner.php index 7908ce68f38e..cb699b144558 100644 --- a/src/Standalone/RectorStandaloneRunner.php +++ b/src/Standalone/RectorStandaloneRunner.php @@ -75,7 +75,7 @@ public function processSourceWithSet( $phpFileInfos = $this->findFilesInSource($source); $this->runRectorOnFileInfos($phpFileInfos); - if ($isQuietMode === false) { + if (! $isQuietMode) { $this->reportErrors(); }