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 4 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
112 changes: 112 additions & 0 deletions build/PHPStan/Build/MemoizationPropertyRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php declare(strict_types = 1);

namespace PHPStan\Build;

use PhpParser\Node;
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\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
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 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_
|| !$returnNode->expr instanceof PropertyFetch
Copy link
Contributor

Choose a reason for hiding this comment

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

I think you can do the same for StaticPropertyFetch

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion, I implemented it.

|| !$returnNode->expr->var instanceof Variable
|| !$returnNode->expr->name instanceof Identifier
) {
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
|| !$ifNode->cond->left instanceof PropertyFetch
|| !$ifNode->cond->left->var instanceof Variable
|| !$ifNode->cond->left->name instanceof Identifier
|| !$ifNode->cond->right instanceof ConstFetch
|| strcasecmp($ifNode->cond->right->name->name, 'null') !== 0
) {
return [];
}

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

if ($returnNode->expr->var->name !== $ifNode->cond->left->var->name
|| $returnNode->expr->name->name !== $ifNode->cond->left->name->name
) {
return [];
}

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

$classReflection = $node->getClassReflection();
$methodName = $methodNode->name->name;
$errorBuilder = RuleErrorBuilder::message(
sprintf('Method %s::%s() for memoization can be simplified.', $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(),
];
}

}
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),
);
}

}
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
25 changes: 11 additions & 14 deletions src/Reflection/Annotations/AnnotationMethodReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,17 @@ public function getName(): string

public function getVariants(): array
{
if ($this->variants === null) {
$this->variants = [
new ExtendedFunctionVariant(
$this->templateTypeMap,
null,
$this->parameters,
$this->isVariadic,
$this->returnType,
$this->returnType,
new MixedType(),
),
];
}
return $this->variants;
return $this->variants ??= [
new ExtendedFunctionVariant(
$this->templateTypeMap,
null,
$this->parameters,
$this->isVariadic,
$this->returnType,
$this->returnType,
new MixedType(),
),
];
}

public function getOnlyVariant(): ExtendedParametersAcceptor
Expand Down
26 changes: 11 additions & 15 deletions src/Reflection/Php/PhpFunctionFromParserNodeReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,21 +105,17 @@ public function getName(): string

public function getVariants(): array
{
if ($this->variants === null) {
$this->variants = [
new ExtendedFunctionVariant(
$this->getTemplateTypeMap(),
$this->getResolvedTemplateTypeMap(),
$this->getParameters(),
$this->isVariadic(),
$this->getReturnType(),
$this->getPhpDocReturnType(),
$this->getNativeReturnType(),
),
];
}

return $this->variants;
return $this->variants ??= [
new ExtendedFunctionVariant(
$this->getTemplateTypeMap(),
$this->getResolvedTemplateTypeMap(),
$this->getParameters(),
$this->isVariadic(),
$this->getReturnType(),
$this->getPhpDocReturnType(),
$this->getNativeReturnType(),
),
];
}

public function getOnlyVariant(): ExtendedParametersAcceptor
Expand Down
Loading
Loading