Skip to content

Commit

Permalink
Home cleaning with Exacat 😎 (#2676)
Browse files Browse the repository at this point in the history
* cleanup unused normalized params

* remove unused createClosureFromClassMethod

* early return

* clean assign to array

* skip false postives in phpsta

* clean getTokens()

* remove unused FrameworkName class

* simplify RenameVariableToMatchMethodCallReturnTypeRector

* cleanup remove unused unwrapNullableType()

* apply new RenameVariableToMatchMethodCallReturnTypeRector

* apply new RenameVariableToMatchMethodCallReturnTypeRector

* union type juggling
  • Loading branch information
TomasVotruba committed Jul 18, 2022
1 parent d1f9150 commit 6d7404c
Show file tree
Hide file tree
Showing 58 changed files with 224 additions and 294 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,14 @@ public function parseTag(TokenIterator $tokenIterator): PhpDocTagNode
public function parseTagValue(TokenIterator $tokenIterator, string $tag): PhpDocTagValueNode
{
$startPosition = $tokenIterator->currentPosition();
$tagValueNode = parent::parseTagValue($tokenIterator, $tag);
$phpDocTagValueNode = parent::parseTagValue($tokenIterator, $tag);

$endPosition = $tokenIterator->currentPosition();

$startAndEnd = new StartAndEnd($startPosition, $endPosition);
$tagValueNode->setAttribute(PhpDocAttributeKey::START_AND_END, $startAndEnd);
$phpDocTagValueNode->setAttribute(PhpDocAttributeKey::START_AND_END, $startAndEnd);

return $tagValueNode;
return $phpDocTagValueNode;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@
use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\Php80\NodeAnalyzer\PhpAttributeAnalyzer;
use Rector\PhpAttribute\NodeFactory\PhpAttributeGroupFactory;
use Rector\PHPStanStaticTypeMapper\Utils\TypeUnwrapper;
use Rector\StaticTypeMapper\StaticTypeMapper;
use ReturnTypeWillChange;

Expand Down Expand Up @@ -56,7 +56,6 @@ public function __construct(
private readonly PhpDocInfoFactory $phpDocInfoFactory,
private readonly NodeNameResolver $nodeNameResolver,
private readonly PhpDocTypeChanger $phpDocTypeChanger,
private readonly TypeUnwrapper $typeUnwrapper,
private readonly BetterNodeFinder $betterNodeFinder,
private readonly PhpAttributeGroupFactory $phpAttributeGroupFactory,
private readonly PhpAttributeAnalyzer $phpAttributeAnalyzer
Expand Down Expand Up @@ -192,7 +191,7 @@ private function isTypeMatch(ComplexType|Identifier|Name $typeNode, Type $requir

// cover nullable union types
if ($returnType instanceof UnionType) {
$returnType = $this->typeUnwrapper->unwrapNullableType($returnType);
$returnType = TypeCombinator::removeNull($returnType);
}

if ($returnType instanceof ObjectType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ public function parseValue(
$tokenIterator->next();

// normalize value
$constantValue = $this->matchConstantValue($currentTokenValue);
if ($constantValue !== null) {
return $constantValue;
$constExprNode = $this->matchConstantValue($currentTokenValue);
if ($constExprNode !== null) {
return $constExprNode;
}

while ($tokenIterator->isCurrentTokenType(Lexer::TOKEN_DOUBLE_COLON) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public function currentPosition(): int
}

/**
* @return mixed[]
* @return array<array{0: string, 1: int}>
*/
public function getTokens(): array
{
Expand All @@ -144,18 +144,11 @@ public function count(): int
}

/**
* @return mixed[]
* @return array<array{0: string, 1: int}>
*/
public function partialTokens(int $start, int $end): array
{
$tokens = $this->getTokens();

$chunkTokens = [];
for ($i = $start; $i <= $end; ++$i) {
$chunkTokens[$i] = $tokens[$i];
}

return $chunkTokens;
return array_slice($this->getTokens(), $start, $end);
}

public function containsTokenType(int $type): bool
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ private function resolveClassConstFetchType(ClassConstFetch $classConstFetch): M
return new ObjectType($classConstantReference, null, $classReflection);
}

$methodReflection = $classReflection->getMethod(MethodName::CONSTRUCT, $scope);
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants());
$extendedMethodReflection = $classReflection->getMethod(MethodName::CONSTRUCT, $scope);
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($extendedMethodReflection->getVariants());

foreach ($parametersAcceptor->getParameters() as $parameterReflection) {
if ($parameterReflection->getDefaultValue() === null) {
Expand Down
4 changes: 2 additions & 2 deletions packages/NodeCollector/StaticAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ final class StaticAnalyzer
public function isStaticMethod(ClassReflection $classReflection, string $methodName): bool
{
if ($classReflection->hasNativeMethod($methodName)) {
$methodReflection = $classReflection->getNativeMethod($methodName);
if ($methodReflection->isStatic()) {
$extendedMethodReflection = $classReflection->getNativeMethod($methodName);
if ($extendedMethodReflection->isStatic()) {
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,9 @@ private function matchTypeForUnionedObjectTypes(UnionType $unionType, string $ty
return new Name('bool');
}

$compatibleObjectType = $this->processResolveCompatibleObjectCandidates($unionType);
if ($compatibleObjectType instanceof NullableType || $compatibleObjectType instanceof FullyQualified) {
return $compatibleObjectType;
$compatibleObjectTypeNode = $this->processResolveCompatibleObjectCandidates($unionType);
if ($compatibleObjectTypeNode instanceof NullableType || $compatibleObjectTypeNode instanceof FullyQualified) {
return $compatibleObjectTypeNode;
}

return $this->processResolveCompatibleStringCandidates($unionType);
Expand Down
9 changes: 0 additions & 9 deletions packages/PHPStanStaticTypeMapper/Utils/TypeUnwrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,11 @@
namespace Rector\PHPStanStaticTypeMapper\Utils;

use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\UnionType;

final class TypeUnwrapper
{
/**
* E.g. null|ClassType → ClassType
*/
public function unwrapNullableType(Type $type): Type
{
return TypeCombinator::removeNull($type);
}

public function unwrapFirstObjectTypeFromUnionType(Type $type): Type
{
if (! $type instanceof UnionType) {
Expand Down
6 changes: 3 additions & 3 deletions packages/PostRector/Collector/NodesToAddCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,15 +155,15 @@ private function resolveNearestStmtPosition(Node $node): string
return spl_object_hash($parent);
}

$foundNode = $this->betterNodeFinder->findParentType($node, Stmt::class);
$foundStmt = $this->betterNodeFinder->findParentType($node, Stmt::class);

if (! $foundNode instanceof Stmt) {
if (! $foundStmt instanceof Stmt) {
$printedNode = $this->nodePrinter->print($node);
$errorMessage = sprintf('Could not find parent Stmt of "%s" node', $printedNode);
throw new ShouldNotHappenException($errorMessage);
}

return spl_object_hash($foundNode);
return spl_object_hash($foundStmt);
}

private function wrapToExpression(Expr | Stmt $node): Stmt
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ public function getNodeType(): string
*/
public function mapToPHPStan(Node $node): Type
{
$types = [];
$types[] = $this->phpParserNodeMapper->mapToPHPStanType($node->type);
$types[] = new NullType();
$types = [$this->phpParserNodeMapper->mapToPHPStanType($node->type), new NullType()];

return $this->typeFactory->createMixedPassedOrUnionType($types);
}
Expand Down
13 changes: 0 additions & 13 deletions packages/Testing/PHPUnit/Behavior/MovingFilesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,18 @@
use Rector\Core\Application\FileSystem\RemovedAndAddedFilesCollector;
use Rector\Core\PhpParser\Printer\NodesWithFileDestinationPrinter;
use Rector\FileSystemRector\ValueObject\AddedFileWithContent;
use Symplify\SmartFileSystem\SmartFileInfo;
use Webmozart\Assert\Assert;

/**
* @property-read RemovedAndAddedFilesCollector $removedAndAddedFilesCollector
*/
trait MovingFilesTrait
{
protected function assertFileWasNotChanged(SmartFileInfo $smartFileInfo): void
{
$hasFileInfo = $this->removedAndAddedFilesCollector->isFileRemoved($smartFileInfo);
$this->assertFalse($hasFileInfo);
}

protected function assertFileWasAdded(AddedFileWithContent $addedFileWithContent): void
{
$this->assertFilesWereAdded([$addedFileWithContent]);
}

protected function assertFileWasRemoved(SmartFileInfo $smartFileInfo): void
{
$isFileRemoved = $this->removedAndAddedFilesCollector->isFileRemoved($smartFileInfo);
$this->assertTrue($isFileRemoved);
}

/**
* @param AddedFileWithContent[] $expectedAddedFileWithContents
*/
Expand Down
13 changes: 13 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,8 @@ parameters:
- rules/Composer/Application/FileProcessor/ComposerFileProcessor.php
- src/Contract/Processor/FileProcessorInterface.php
- packages/Parallel/Application/ParallelFileProcessor.php
# tokens
- packages/BetterPhpDocParser/ValueObject/Parser/BetterTokenIterator.php

# skipped on purpose, as ctor overrie
- '#Rector\\StaticTypeMapper\\ValueObject\\Type\\SimpleStaticType\:\:__construct\(\) does not call parent constructor from PHPStan\\Type\\StaticType#'
Expand Down Expand Up @@ -680,3 +682,14 @@ parameters:
- src/Bootstrap/RectorConfigsResolver.php
- src/ValueObject/StaticNonPhpFileSuffixes.php
- tests/FileSystem/FilesFinder/FilesFinderTest.php

-
message: '#Parameters should use "PhpParser\\Node\\Expr\\BinaryOp\|string" types as the only types passed to this method#'
path: packages/NodeCollector/BinaryOpTreeRootLocator.php
-
message: '#Parameters should use "string\|PhpParser\\Node\\Expr\\Variable" types as the only types passed to this method#'
path: src/PhpParser/Node/NodeFactory.php

# union booleans
- '#Method Rector\\Strict\\NodeFactory\\ExactCompareFactory\:\:createTruthyFromUnionType\(\) should return PhpParser\\Node\\Expr\\BinaryOp\\BooleanOr\|PhpParser\\Node\\Expr\\BinaryOp\\Identical\|PhpParser\\Node\\Expr\\BinaryOp\\NotIdentical\|PhpParser\\Node\\Expr\\BooleanNot\|PhpParser\\Node\\Expr\\Instanceof_\|null but returns PhpParser\\Node\\Expr\\BinaryOp\\BooleanAnd\|PhpParser\\Node\\Expr\\BinaryOp\\BooleanOr\|PhpParser\\Node\\Expr\\BinaryOp\\Identical\|PhpParser\\Node\\Expr\\BinaryOp\\NotIdentical\|PhpParser\\Node\\Expr\\Instanceof_\|null#'
- '#Parameter \#1 \$compareExprs of method Rector\\Strict\\NodeFactory\\ExactCompareFactory\:\:resolveTruthyExpr\(\) expects array<PhpParser\\Node\\Expr\\BinaryOp\\BooleanAnd\|PhpParser\\Node\\Expr\\BinaryOp\\BooleanOr\|PhpParser\\Node\\Expr\\BinaryOp\\Identical\|PhpParser\\Node\\Expr\\BinaryOp\\NotIdentical\|PhpParser\\Node\\Expr\\Instanceof_\|null>, array<PhpParser\\Node\\Expr\\BinaryOp\\BooleanOr\|PhpParser\\Node\\Expr\\BinaryOp\\Identical\|PhpParser\\Node\\Expr\\BinaryOp\\NotIdentical\|PhpParser\\Node\\Expr\\BooleanNot\|PhpParser\\Node\\Expr\\Instanceof_\|null> given#'
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use PhpParser\Node\Expr;
use PhpParser\Node\Scalar\LNumber;
use PhpParser\Node\Scalar\String_;

class SkipOverlyGeneric
final class SkipOverlyGeneric
{
public function run()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ private function resolveExceptionArgumentPosition(Name $exceptionName): ?int
return self::DEFAULT_EXCEPTION_ARGUMENT_POSITION;
}

$methodReflection = $classReflection->getConstructor();
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants());
$extendedMethodReflection = $classReflection->getConstructor();
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($extendedMethodReflection->getVariants());

foreach ($parametersAcceptor->getParameters() as $position => $parameterReflection) {
$parameterType = $parameterReflection->getType();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ private function shouldSkip(Foreach_ $foreach, Scope $scope): bool
return true;
}

$previousDeclaration = $this->nodeUsageFinder->findPreviousForeachNodeUsage($foreach, $assignVariable);
if (! $previousDeclaration instanceof Node) {
$node = $this->nodeUsageFinder->findPreviousForeachNodeUsage($foreach, $assignVariable);
if (! $node instanceof Node) {
return true;
}

$previousDeclarationParentNode = $previousDeclaration->getAttribute(AttributeKey::PARENT_NODE);
$previousDeclarationParentNode = $node->getAttribute(AttributeKey::PARENT_NODE);
if (! $previousDeclarationParentNode instanceof Assign) {
return true;
}
Expand Down
4 changes: 2 additions & 2 deletions rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ public function refactor(Node $node): ?Node
return null;
}

$comparedNode = $twoNodeMatch->getSecondExpr();
$comparedExpr = $twoNodeMatch->getSecondExpr();
if (! $this->isIfBodyABoolReturnNode($firstNodeInsideForeach)) {
return null;
}

$funcCall = $this->createInArrayFunction($comparedNode, $ifCondition, $node);
$funcCall = $this->createInArrayFunction($comparedExpr, $ifCondition, $node);

/** @var Return_ $returnToRemove */
$returnToRemove = $node->getAttribute(AttributeKey::NEXT_NODE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,9 @@ private function resolvePropertyFetchType(PropertyFetch $propertyFetch): Type
}

// set in constructor + changed in class
$propertyTypeFromConstructor = $this->resolvePropertyTypeAfterConstructor($classLike, $propertyName);
$propertyType = $this->resolvePropertyTypeAfterConstructor($classLike, $propertyName);

$resolvedTypes = [];
$resolvedTypes[] = $propertyTypeFromConstructor;
$resolvedTypes = [$propertyType];

$defaultValue = $property->props[0]->default;
if ($defaultValue !== null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,18 @@ public function refactor(Node $node): ?Node
/** @var ClassConstFetch|String_ $firstExpr */
$firstExpr = $twoNodeMatch->getFirstExpr();

/** @var FuncCall $funcCall */
$funcCall = $twoNodeMatch->getSecondExpr();
/** @var FuncCall $secondExpr */
$secondExpr = $twoNodeMatch->getSecondExpr();

if (! isset($funcCall->args[0])) {
if (! isset($secondExpr->args[0])) {
return null;
}

if (! $funcCall->args[0] instanceof Arg) {
if (! $secondExpr->args[0] instanceof Arg) {
return null;
}

$varNode = $funcCall->args[0]->value;
$varNode = $secondExpr->args[0]->value;

if ($firstExpr instanceof String_) {
$className = $this->valueResolver->getValue($firstExpr);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ function (Node $node): bool {
return null;
}

/** @var FuncCall $arraySearchFuncCall */
$arraySearchFuncCall = $twoNodeMatch->getFirstExpr();
/** @var FuncCall $funcCallExpr */
$funcCallExpr = $twoNodeMatch->getFirstExpr();

$inArrayFuncCall = $this->nodeFactory->createFuncCall('in_array', $arraySearchFuncCall->args);
$inArrayFuncCall = $this->nodeFactory->createFuncCall('in_array', $funcCallExpr->args);

if ($node instanceof Identical) {
return new BooleanNot($inArrayFuncCall);
Expand Down
12 changes: 6 additions & 6 deletions rules/CodeQuality/Rector/Identical/SimplifyConditionsRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,15 @@ private function processIdenticalAndNotIdentical(Identical $identical): ?Node
return $twoNodeMatch;
}

/** @var Identical|NotIdentical $subBinaryOp */
$subBinaryOp = $twoNodeMatch->getFirstExpr();
/** @var Identical|NotIdentical $firstExpr */
$firstExpr = $twoNodeMatch->getFirstExpr();

$otherNode = $twoNodeMatch->getSecondExpr();
if ($this->valueResolver->isFalse($otherNode)) {
return $this->createInversedBooleanOp($subBinaryOp);
$otherExpr = $twoNodeMatch->getSecondExpr();
if ($this->valueResolver->isFalse($otherExpr)) {
return $this->createInversedBooleanOp($firstExpr);
}

return $subBinaryOp;
return $firstExpr;
}

/**
Expand Down
8 changes: 4 additions & 4 deletions rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,18 +117,18 @@ public function refactor(Node $node): ?Node
return null;
}

$newConditionNode = $this->resolveNewConditionNode($conditionNode, $isNegated);
if (! $newConditionNode instanceof BinaryOp) {
$binaryOp = $this->resolveNewConditionNode($conditionNode, $isNegated);
if (! $binaryOp instanceof BinaryOp) {
return null;
}

$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
// avoid duplicated ifs when combined with ChangeOrIfReturnToEarlyReturnRector
if ($this->shouldSkip($conditionStaticType, $newConditionNode, $nextNode)) {
if ($this->shouldSkip($conditionStaticType, $binaryOp, $nextNode)) {
return null;
}

$node->cond = $newConditionNode;
$node->cond = $binaryOp;

return $node;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ public function refactor(Node $node): ?Return_
return null;
}

$comparedNode = $this->ifManipulator->matchIfValueReturnValue($node);
if (! $comparedNode instanceof Expr) {
$expr = $this->ifManipulator->matchIfValueReturnValue($node);
if (! $expr instanceof Expr) {
return null;
}

if (! $this->nodeComparator->areNodesEqual($comparedNode, $nextNode->expr)) {
if (! $this->nodeComparator->areNodesEqual($expr, $nextNode->expr)) {
return null;
}

Expand Down
Loading

0 comments on commit 6d7404c

Please sign in to comment.