Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PHPStan] Add NoInstanceOfStaticReflectionRule #5937

Merged
merged 3 commits into from
Mar 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/NodeTypeResolver/NodeTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,9 @@ public function isPropertyBoolean(Property $property): bool
return $this->isStaticType($defaultNodeValue, BooleanType::class);
}

/**
* @return class-string
*/
public function getFullyQualifiedClassName(TypeWithClassName $typeWithClassName): string
{
if ($typeWithClassName instanceof ShortenedObjectType) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@

interface TypeMapperInterface
{
/**
* @return class-string<Type>
*/
public function getNodeClass(): string;

public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

interface PhpDocTypeMapperInterface
{
/**
* @return class-string<TypeNode>
*/
public function getNodeType(): string;

public function mapToPHPStanType(TypeNode $typeNode, Node $node, NameScope $nameScope): Type;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public function __construct(
$this->parentClassScopeResolver = $parentClassScopeResolver;
}

/**
* @return class-string<TypeNode>
*/
public function getNodeType(): string
{
return IdentifierTypeNode::class;
Expand Down
3 changes: 3 additions & 0 deletions packages/StaticTypeMapper/PhpDocParser/UnionTypeMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public function __construct(TypeFactory $typeFactory)
$this->typeFactory = $typeFactory;
}

/**
* @return class-string<TypeNode>
*/
public function getNodeType(): string
{
return UnionTypeNode::class;
Expand Down
7 changes: 7 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -519,3 +519,10 @@ parameters:

# known types
- '#Parameter \#1 \$node of method Rector\\Naming\\Naming\\VariableNaming\:\:resolveFromMethodCall\(\) expects PhpParser\\Node\\Expr\\MethodCall\|PhpParser\\Node\\Expr\\NullsafeMethodCall\|PhpParser\\Node\\Expr\\StaticCall, PhpParser\\Node given#'

-
message: '#Do not inherit from abstract class, better use composition#'
path: utils/phpstan-extensions/src/Rule/NoInstanceOfStaticReflectionRule.php

# first wave resolved, merge PR
- '#Instead of "(.*?)" use ReflectionProvider service (.*?) for static reflection to work#'
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Type\ObjectType;
use Rector\Autodiscovery\Analyzer\ValueObjectClassAnalyzer;
use Rector\Core\Contract\Rector\ConfigurableRectorInterface;
use Rector\Core\PhpParser\Node\CustomNode\FileNode;
Expand Down Expand Up @@ -55,7 +56,7 @@ final class MoveValueObjectsToValueObjectDirectoryRector extends AbstractRector
private $enableValueObjectGuessing = true;

/**
* @var string[]
* @var class-string[]
*/
private $types = [];

Expand Down Expand Up @@ -169,6 +170,9 @@ public function refactor(Node $node): ?Node
return null;
}

/**
* @param array<string, mixed> $configuration
*/
public function configure(array $configuration): void
{
$this->types = $configuration[self::TYPES] ?? [];
Expand All @@ -187,8 +191,11 @@ private function isValueObjectMatch(Class_ $class): bool
return false;
}

$classObjectType = new ObjectType($className);

foreach ($this->types as $type) {
if (is_a($className, $type, true)) {
$desiredObjectType = new ObjectType($type);
if ($desiredObjectType->isSuperTypeOf($classObjectType)->yes()) {
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,12 @@ private function createArgFromSpreadArrayItem(Scope $nodeScope, ArrayItem $array
*/
private function isIterableType(Type $type): bool
{
return $type instanceof IterableType || ($type instanceof ObjectType && is_a(
$type->getClassName(),
Traversable::class,
true
));
if ($type instanceof IterableType) {
return true;
}

$traversableObjectType = new ObjectType('Traversable');
return $traversableObjectType->isSuperTypeOf($type)
->yes();
}
}
8 changes: 4 additions & 4 deletions src/NodeManipulator/BinaryOpManipulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public function __construct(AssignAndBinaryMap $assignAndBinaryMap)
* Tries to match left or right parts (xor),
* returns null or match on first condition and then second condition. No matter what the origin order is.
*
* @param callable|string $firstCondition callable or Node to instanceof
* @param callable|string $secondCondition callable or Node to instanceof
* @param callable|class-string<Node> $firstCondition
* @param callable|class-string<Node> $secondCondition
*/
public function matchFirstAndSecondConditionNode(
BinaryOp $binaryOp,
Expand Down Expand Up @@ -114,7 +114,7 @@ public function inverseNode(Expr $expr): Node
}

/**
* @param string|callable $firstCondition
* @param callable|class-string<Node> $firstCondition
*/
private function validateCondition($firstCondition): void
{
Expand All @@ -130,7 +130,7 @@ private function validateCondition($firstCondition): void
}

/**
* @param callable|string $condition
* @param callable|class-string<Node> $condition
*/
private function normalizeCondition($condition): callable
{
Expand Down
14 changes: 0 additions & 14 deletions stubs/Kdyby/Events/Subscriber.php

This file was deleted.

12 changes: 0 additions & 12 deletions stubs/Twig/Twig_Extension.php

This file was deleted.

12 changes: 0 additions & 12 deletions stubs/Twig/Twig_Filter_Method.php

This file was deleted.

12 changes: 0 additions & 12 deletions stubs/Twig/Twig_Function_Method.php

This file was deleted.

12 changes: 0 additions & 12 deletions stubs/Twig/Twig_SimpleFilter.php

This file was deleted.

12 changes: 0 additions & 12 deletions stubs/Twig/Twig_SimpleFunction.php

This file was deleted.

2 changes: 2 additions & 0 deletions utils/compiler/src/PhpScoper/StaticEasyPrefixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ final class StaticEasyPrefixer
'Doctrine\Inflector\Inflector',
// for ocramius versions - https://github.com/rectorphp/rector/runs/2089178426
'Composer\InstalledVersions',
// for SmartFileInfo
'Symplify\SmartFileSystem\SmartFileInfo',
];

/**
Expand Down
1 change: 1 addition & 0 deletions utils/phpstan-extensions/config/phpstan-extensions.neon
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
services:
- Rector\PHPStanExtensions\TypeAnalyzer\AllowedAutoloadedTypeAnalyzer
- Rector\PHPStanExtensions\TypeResolver\GetNameMethodCallTypeResolver

# $nodeFinder->findInstanceOf()
Expand Down
8 changes: 5 additions & 3 deletions utils/phpstan-extensions/config/rector-rules.neon
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
services:
-
class: Rector\PHPStanExtensions\Rule\NoInstanceOfStaticReflectionRule
tags: [phpstan.rules.rule]

-
class: Symplify\PHPStanRules\ObjectCalisthenics\Rules\NoChainMethodCallRule
tags: [phpstan.rules.rule]
Expand All @@ -13,9 +17,7 @@ services:
allowedParentTypes:
- Rector\Utils\DoctrineAnnotationParserSyncer\FileSyncer\AbstractClassSyncer
- PhpParser\NodeAbstract
- PHPStan\Type\BooleanType
- PHPStan\Type\ObjectType
- PHPStan\Type\StaticType
- PHPStan\Type\Type
- Rector\BetterPhpDocParser\PhpDocNodeFactory\AbstractPhpDocNodeFactory
- PHPStan\PhpDocParser\Parser\PhpDocParser
- Rector\PostRector\Rector\AbstractPostRector
Expand Down
113 changes: 113 additions & 0 deletions utils/phpstan-extensions/src/Rule/NoInstanceOfStaticReflectionRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

declare(strict_types=1);

namespace Rector\PHPStanExtensions\Rule;

use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Instanceof_;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\Type;
use Rector\PHPStanExtensions\TypeAnalyzer\AllowedAutoloadedTypeAnalyzer;
use Symplify\Astral\Naming\SimpleNameResolver;
use Symplify\PHPStanRules\Rules\AbstractSymplifyRule;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\PHPStanExtensions\Tests\Rule\NoInstanceOfStaticReflectionRule\NoInstanceOfStaticReflectionRuleTest
*/
final class NoInstanceOfStaticReflectionRule extends AbstractSymplifyRule implements Rule
{
/**
* @var string
*/
public const ERROR_MESSAGE = 'Instead of "instanceof/is_a()" use ReflectionProvider service or "(new ObjectType(<desired_type>))->isSuperTypeOf(<element_type>)" for static reflection to work';

/**
* @var AllowedAutoloadedTypeAnalyzer
*/
private $allowedAutoloadedTypeAnalyzer;

/**
* @var SimpleNameResolver
*/
private $simpleNameResolver;

public function __construct(
SimpleNameResolver $simpleNameResolver,
AllowedAutoloadedTypeAnalyzer $allowedAutoloadedTypeAnalyzer
) {
$this->allowedAutoloadedTypeAnalyzer = $allowedAutoloadedTypeAnalyzer;
$this->simpleNameResolver = $simpleNameResolver;
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Instanceof_::class, FuncCall::class];
}

/**
* @param Instanceof_|FuncCall $node
* @return string[]
*/
public function process(Node $node, Scope $scope): array
{
$exprStaticType = $this->resolveExprStaticType($node, $scope);
if ($exprStaticType === null) {
return [];
}

if ($this->allowedAutoloadedTypeAnalyzer->isAllowedType($exprStaticType)) {
return [];
}

return [self::ERROR_MESSAGE];
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(self::ERROR_MESSAGE, [
new CodeSample(
<<<'CODE_SAMPLE'
return is_a($node, 'Command', true);
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
$nodeType = $scope->getType($node);
$commandObjectType = new ObjectType('Command');

return $commandObjectType->isSuperTypeOf($nodeType)->yes();
CODE_SAMPLE
),
]);
}

/**
* @param FuncCall|Instanceof_ $node
*/
private function resolveExprStaticType(Node $node, Scope $scope): ?Type
{
if ($node instanceof Instanceof_) {
if ($node->class instanceof Name) {
return new ConstantStringType($node->class->toString());
}

return $scope->getType($node->class);
}

if (! $this->simpleNameResolver->isName($node, 'is_a')) {
return null;
}

$typeArgValue = $node->args[1]->value;
return $scope->getType($typeArgValue);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Rules\Rule;
use Rector\Core\Contract\Rector\RectorInterface;
use Rector\Core\Exception\ShouldNotHappenException;

/**
Expand Down Expand Up @@ -78,6 +79,10 @@ private function resolveRectorClassReflection(ClassMethod $classMethod, Scope $s
return null;
}

if (! $classReflection->isSubclassOf(RectorInterface::class)) {
return null;
}

if ($classReflection->isInterface()) {
return null;
}
Expand Down
Loading