Skip to content

Simplify property memoization for Flyweight pattern by replacing it with ??= #4084

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

Open
wants to merge 8 commits into
base: 2.1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
182 changes: 182 additions & 0 deletions build/PHPStan/Build/MemoizationPropertyRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<?php declare(strict_types = 1);

namespace PHPStan\Build;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignOp\Coalesce;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\VarLikeIdentifier;
use PHPStan\Analyser\Scope;
use PHPStan\File\FileHelper;
use PHPStan\Node\InClassMethodNode;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function count;
use function dirname;
use function is_string;
use function sprintf;
use function str_starts_with;
use function strcasecmp;

/**
* @implements Rule<InClassMethodNode>
*/
final class MemoizationPropertyRule implements Rule
{

public function __construct(private FileHelper $fileHelper, private bool $skipTests = true)
{
}

public function getNodeType(): string
{
return InClassMethodNode::class;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the rule should apply to If_, not to a method body.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, it has been reflected in the rule.

}

public function processNode(Node $node, Scope $scope): array
{
$methodNode = $node->getOriginalNode();
if (count($methodNode->params) !== 0) {
return [];
}

$stmts = $methodNode->getStmts();
if ($stmts === null || count($stmts) !== 2) {
return [];
}

[$ifNode, $returnNode] = $stmts;
if (!$returnNode instanceof Return_ || !$this->isSupportedFetchNode($returnNode->expr)) {
return [];
}

if (!$ifNode instanceof If_
|| count($ifNode->stmts) !== 1
|| !$ifNode->stmts[0] instanceof Expression
|| count($ifNode->elseifs) !== 0
|| $ifNode->else !== null
|| !$ifNode->cond instanceof Identical
|| !$this->isSupportedFetchNode($ifNode->cond->left)
|| !$ifNode->cond->right instanceof ConstFetch
|| strcasecmp($ifNode->cond->right->name->name, 'null') !== 0
) {
return [];
}

$ifThenNode = $ifNode->stmts[0]->expr;
if (!$ifThenNode instanceof Assign || !$this->isSupportedFetchNode($ifThenNode->var)) {
return [];
}

if ($this->areNodesNotEqual($returnNode->expr, [$ifNode->cond->left, $ifThenNode->var])) {
return [];
}

if ($this->skipTests && str_starts_with($this->fileHelper->normalizePath($scope->getFile()), $this->fileHelper->normalizePath(dirname(__DIR__, 3) . '/tests'))) {
return [];
}

$classReflection = $node->getClassReflection();
$methodReflection = $node->getMethodReflection();
$methodName = $methodNode->name->name;
$errorBuilder = RuleErrorBuilder::message(
sprintf(
'%s %s::%s() for memoization can be simplified.',
$methodReflection->isStatic() ? 'Static method' : 'Method',
$classReflection->getDisplayName(),
$methodName,
),
)->fixNode($node->getOriginalNode(), static function (Node\Stmt\ClassMethod $method) use ($ifThenNode) {
$method->stmts = [
new Return_(
new Coalesce($ifThenNode->var, $ifThenNode->expr),
),
];

return $method;
})->identifier('phpstan.memoizationProperty');

return [
$errorBuilder->build(),
];
}

/**
* @phpstan-assert-if-true PropertyFetch|StaticPropertyFetch $node
*/
private function isSupportedFetchNode(?Expr $node): bool
{
return $node instanceof PropertyFetch || $node instanceof StaticPropertyFetch;
}

/**
* @param list<PropertyFetch|StaticPropertyFetch> $otherNodes
*/
private function areNodesNotEqual(PropertyFetch|StaticPropertyFetch $node, array $otherNodes): bool
{
if ($node instanceof PropertyFetch) {
if (!$node->var instanceof Variable
|| !is_string($node->var->name)
|| !$node->name instanceof Identifier
) {
return true;
}

foreach ($otherNodes as $otherNode) {
if (!$otherNode instanceof PropertyFetch) {
return true;
}
if (!$otherNode->var instanceof Variable
|| !is_string($otherNode->var->name)
|| !$otherNode->name instanceof Identifier
) {
return true;
}

if ($node->var->name !== $otherNode->var->name
|| $node->name->name !== $otherNode->name->name
) {
return true;
}
}

return false;
}

if (!$node->class instanceof Name || !$node->name instanceof VarLikeIdentifier) {
return true;
}

foreach ($otherNodes as $otherNode) {
if (!$otherNode instanceof StaticPropertyFetch) {
return true;
}

if (!$otherNode->class instanceof Name
|| !$otherNode->name instanceof VarLikeIdentifier
) {
return true;
}

if ($node->class->toLowerString() !== $otherNode->class->toLowerString()
|| $node->name->toString() !== $otherNode->name->toString()
) {
return true;
}
}

return false;
}

}
1 change: 1 addition & 0 deletions build/phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ rules:
- PHPStan\Build\NamedArgumentsRule
- PHPStan\Build\OverrideAttributeThirdPartyMethodRule
- PHPStan\Build\SkipTestsWithRequiresPhpAttributeRule
- PHPStan\Build\MemoizationPropertyRule

services:
-
Expand Down
4 changes: 1 addition & 3 deletions src/Analyser/Ignore/IgnoreLexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ final class IgnoreLexer
*/
public function tokenize(string $input): array
{
if ($this->regexp === null) {
$this->regexp = $this->generateRegexp();
}
$this->regexp ??= $this->generateRegexp();

$matches = Strings::matchAll($input, $this->regexp, PREG_SET_ORDER);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,12 @@ public function __construct(private Container $container)

public function getRegistry(): DynamicReturnTypeExtensionRegistry
{
if ($this->registry === null) {
$this->registry = new DynamicReturnTypeExtensionRegistry(
$this->container->getByType(ReflectionProvider::class),
$this->container->getServicesByTag(BrokerFactory::DYNAMIC_METHOD_RETURN_TYPE_EXTENSION_TAG),
$this->container->getServicesByTag(BrokerFactory::DYNAMIC_STATIC_METHOD_RETURN_TYPE_EXTENSION_TAG),
$this->container->getServicesByTag(BrokerFactory::DYNAMIC_FUNCTION_RETURN_TYPE_EXTENSION_TAG),
);
}

return $this->registry;
return $this->registry ??= new DynamicReturnTypeExtensionRegistry(
$this->container->getByType(ReflectionProvider::class),
$this->container->getServicesByTag(BrokerFactory::DYNAMIC_METHOD_RETURN_TYPE_EXTENSION_TAG),
$this->container->getServicesByTag(BrokerFactory::DYNAMIC_STATIC_METHOD_RETURN_TYPE_EXTENSION_TAG),
$this->container->getServicesByTag(BrokerFactory::DYNAMIC_FUNCTION_RETURN_TYPE_EXTENSION_TAG),
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,9 @@ public function __construct(private Container $container)

public function getRegistry(): ExpressionTypeResolverExtensionRegistry
{
if ($this->registry === null) {
$this->registry = new ExpressionTypeResolverExtensionRegistry(
$this->container->getServicesByTag(BrokerFactory::EXPRESSION_TYPE_RESOLVER_EXTENSION_TAG),
);
}

return $this->registry;
return $this->registry ??= new ExpressionTypeResolverExtensionRegistry(
$this->container->getServicesByTag(BrokerFactory::EXPRESSION_TYPE_RESOLVER_EXTENSION_TAG),
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,9 @@ public function __construct(private Container $container)

public function getRegistry(): OperatorTypeSpecifyingExtensionRegistry
{
if ($this->registry === null) {
$this->registry = new OperatorTypeSpecifyingExtensionRegistry(
$this->container->getServicesByTag(BrokerFactory::OPERATOR_TYPE_SPECIFYING_EXTENSION_TAG),
);
}

return $this->registry;
return $this->registry ??= new OperatorTypeSpecifyingExtensionRegistry(
$this->container->getServicesByTag(BrokerFactory::OPERATOR_TYPE_SPECIFYING_EXTENSION_TAG),
);
}

}
12 changes: 4 additions & 8 deletions src/PhpDoc/LazyTypeNodeResolverExtensionRegistryProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,10 @@ public function __construct(private Container $container)

public function getRegistry(): TypeNodeResolverExtensionRegistry
{
if ($this->registry === null) {
$this->registry = new TypeNodeResolverExtensionAwareRegistry(
$this->container->getByType(TypeNodeResolver::class),
$this->container->getServicesByTag(TypeNodeResolverExtension::EXTENSION_TAG),
);
}

return $this->registry;
return $this->registry ??= new TypeNodeResolverExtensionAwareRegistry(
$this->container->getByType(TypeNodeResolver::class),
$this->container->getServicesByTag(TypeNodeResolverExtension::EXTENSION_TAG),
);
}

}
Loading
Loading