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 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
150 changes: 150 additions & 0 deletions build/PHPStan/Build/MemoizationPropertyRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
<?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\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 str_starts_with;
use function strcasecmp;

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

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

public function getNodeType(): string
{
return If_::class;
}

public function processNode(Node $node, Scope $scope): array
{
$ifNode = $node;

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($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 [];
}

$errorBuilder = RuleErrorBuilder::message('Memoization property can be simplified.')
->fixNode($node, static fn (If_ $node) => new Expression(new Coalesce($ifThenNode->var, $ifThenNode->expr)))
->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),
);
}

}
4 changes: 1 addition & 3 deletions src/Parser/VariadicFunctionsVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ public function beforeTraverse(array $nodes): ?array
#[Override]
public function enterNode(Node $node): ?Node
{
if ($this->topNode === null) {
$this->topNode = $node;
}
$this->topNode ??= $node;

if ($node instanceof Node\Stmt\Namespace_ && $node->name !== null) {
$this->inNamespace = $node->name->toString();
Expand Down
4 changes: 1 addition & 3 deletions src/Parser/VariadicMethodsVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,7 @@ public function beforeTraverse(array $nodes): ?array
#[Override]
public function enterNode(Node $node): ?Node
{
if ($this->topNode === null) {
$this->topNode = $node;
}
$this->topNode ??= $node;

if ($node instanceof Node\Stmt\Namespace_ && $node->name !== null) {
$this->inNamespace = $node->name->toString();
Expand Down
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),
);
}

}
82 changes: 27 additions & 55 deletions src/PhpDoc/ResolvedPhpDocBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -733,65 +733,47 @@ public function getDeprecatedTag(): ?DeprecatedTag

public function isDeprecated(): bool
{
if ($this->isDeprecated === null) {
$this->isDeprecated = $this->phpDocNodeResolver->resolveIsDeprecated(
$this->phpDocNode,
);
}
return $this->isDeprecated;
return $this->isDeprecated ??= $this->phpDocNodeResolver->resolveIsDeprecated(
$this->phpDocNode,
);
}

/**
* @internal
*/
public function isNotDeprecated(): bool
{
if ($this->isNotDeprecated === null) {
$this->isNotDeprecated = $this->phpDocNodeResolver->resolveIsNotDeprecated(
$this->phpDocNode,
);
}
return $this->isNotDeprecated;
return $this->isNotDeprecated ??= $this->phpDocNodeResolver->resolveIsNotDeprecated(
$this->phpDocNode,
);
}

public function isInternal(): bool
{
if ($this->isInternal === null) {
$this->isInternal = $this->phpDocNodeResolver->resolveIsInternal(
$this->phpDocNode,
);
}
return $this->isInternal;
return $this->isInternal ??= $this->phpDocNodeResolver->resolveIsInternal(
$this->phpDocNode,
);
}

public function isFinal(): bool
{
if ($this->isFinal === null) {
$this->isFinal = $this->phpDocNodeResolver->resolveIsFinal(
$this->phpDocNode,
);
}
return $this->isFinal;
return $this->isFinal ??= $this->phpDocNodeResolver->resolveIsFinal(
$this->phpDocNode,
);
}

public function hasConsistentConstructor(): bool
{
if ($this->hasConsistentConstructor === null) {
$this->hasConsistentConstructor = $this->phpDocNodeResolver->resolveHasConsistentConstructor(
$this->phpDocNode,
);
}
return $this->hasConsistentConstructor;
return $this->hasConsistentConstructor ??= $this->phpDocNodeResolver->resolveHasConsistentConstructor(
$this->phpDocNode,
);
}

public function acceptsNamedArguments(): bool
{
if ($this->acceptsNamedArguments === null) {
$this->acceptsNamedArguments = $this->phpDocNodeResolver->resolveAcceptsNamedArguments(
$this->phpDocNode,
);
}
return $this->acceptsNamedArguments;
return $this->acceptsNamedArguments ??= $this->phpDocNodeResolver->resolveAcceptsNamedArguments(
$this->phpDocNode,
);
}

public function getTemplateTypeMap(): TemplateTypeMap
Expand Down Expand Up @@ -826,33 +808,23 @@ public function isPure(): ?bool

public function isReadOnly(): bool
{
if ($this->isReadOnly === null) {
$this->isReadOnly = $this->phpDocNodeResolver->resolveIsReadOnly(
$this->phpDocNode,
);
}
return $this->isReadOnly;
return $this->isReadOnly ??= $this->phpDocNodeResolver->resolveIsReadOnly(
$this->phpDocNode,
);
}

public function isImmutable(): bool
{
if ($this->isImmutable === null) {
$this->isImmutable = $this->phpDocNodeResolver->resolveIsImmutable(
$this->phpDocNode,
);
}
return $this->isImmutable;
return $this->isImmutable ??= $this->phpDocNodeResolver->resolveIsImmutable(
$this->phpDocNode,
);
}

public function isAllowedPrivateMutation(): bool
{
if ($this->isAllowedPrivateMutation === null) {
$this->isAllowedPrivateMutation = $this->phpDocNodeResolver->resolveAllowPrivateMutation(
$this->phpDocNode,
);
}

return $this->isAllowedPrivateMutation;
return $this->isAllowedPrivateMutation ??= $this->phpDocNodeResolver->resolveAllowPrivateMutation(
$this->phpDocNode,
);
}

/**
Expand Down
Loading
Loading