Skip to content
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
2 changes: 1 addition & 1 deletion build/PHPStan/Build/InlineCallCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@
$receivers = [$declaringClass];
} elseif ($call->var instanceof Expr\Variable && is_string($call->var->name) && isset($paramNames[$call->var->name])) {
$parameter = $parameters[$paramNames[$call->var->name]] ?? null;
$receivers = $parameter === null ? null : $parameter->getType()->getObjectClassReflections();
$receivers = $parameter?->getType()->getObjectClassReflections();
} elseif ($call->var instanceof Expr\PropertyFetch && $call->var->var instanceof Expr\Variable && $call->var->var->name === 'this' && $call->var->name instanceof Node\Identifier) {
$propertyName = $call->var->name->toString();
$receivers = $declaringClass->hasNativeProperty($propertyName)
Expand All @@ -301,7 +301,7 @@
}
if ($receivers === null || $receivers === []) {
return false;
}

Check failure on line 304 in build/PHPStan/Build/InlineCallCollector.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 304 in build/PHPStan/Build/InlineCallCollector.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
foreach ($receivers as $receiver) {
$name = $call->name->toString();
if (!$receiver->hasNativeMethod($name) || !$receiver->getNativeMethod($name)->isPublic()) {
Expand Down
2 changes: 1 addition & 1 deletion build/PHPStan/Build/NoScopeTypeReadInEngineRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
}

$function = $scope->getFunction();
$functionName = $function !== null ? $function->getName() : null;
$functionName = $function?->getName();

Check failure on line 96 in build/PHPStan/Build/NoScopeTypeReadInEngineRule.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 96 in build/PHPStan/Build/NoScopeTypeReadInEngineRule.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
if (
array_key_exists($namespace, self::ALLOWED_SEAMS)
&& $functionName !== null
Expand Down
223 changes: 223 additions & 0 deletions build/PHPStan/Build/NullsafeOperatorRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
<?php declare(strict_types = 1);

namespace PHPStan\Build;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\NullsafeMethodCall;
use PhpParser\Node\Expr\NullsafePropertyFetch;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
use PhpParser\Node\Expr\Ternary;
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\Node\Printer\ExprPrinter;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use function count;
use function is_string;

/**
* Reports null checks that the nullsafe operator replaces:
* `$a !== null ? $a->b->c() : null` and `if ($a !== null) { $a->b(); }`.
*
* Only expressions that can be evaluated twice without side effects are considered,
* so that the replacement does not change how many times anything is called.
*
* @implements Rule<Node>
*/
final class NullsafeOperatorRule implements Rule
{

public function __construct(private ExprPrinter $printer)
{
}

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

public function processNode(Node $node, Scope $scope): array
{
$replacement = $this->createReplacement($node);
if ($replacement === null) {
return [];
}

$errorBuilder = RuleErrorBuilder::message('This null check can be replaced with the nullsafe operator (?->).')
->identifier('phpstan.nullsafeOperator');

// the printer puts the arguments of the new nullsafe call on one line
if (!$this->hasMultilineArgs($replacement)) {
$errorBuilder->fixNode($node, fn (Node $node): Node => $this->createReplacement($node) ?? $node);
}

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

private function createReplacement(Node $node): Expr|Expression|null
{
if ($node instanceof Ternary) {
if ($node->if === null) {
return null;
}

if ($this->isNull($node->else)) {
$subject = $this->getComparedWithNull($node->cond, NotIdentical::class);
$chain = $node->if;
} elseif ($this->isNull($node->if)) {
$subject = $this->getComparedWithNull($node->cond, Identical::class);
$chain = $node->else;
} else {
return null;
}

if ($subject === null) {
return null;
}

return $this->createNullsafeChain($chain, $this->printer->printExpr($subject));
}

if (
!$node instanceof If_
|| count($node->elseifs) > 0
|| $node->else !== null
|| count($node->stmts) !== 1
|| !$node->stmts[0] instanceof Expression
|| count($node->stmts[0]->getComments()) > 0
) {
return null;
}

$expr = $node->stmts[0]->expr;
if (!$expr instanceof MethodCall && !$expr instanceof NullsafeMethodCall) {
return null;
}

$subject = $this->getComparedWithNull($node->cond, NotIdentical::class);
if ($subject === null) {
return null;
}

$chain = $this->createNullsafeChain($expr, $this->printer->printExpr($subject));
if ($chain === null) {
return null;
}

return new Expression($chain, ['comments' => $node->getComments()]);
}

/**
* @param class-string<Identical|NotIdentical> $comparisonClass
*/
private function getComparedWithNull(Expr $cond, string $comparisonClass): ?Expr
{
if (!$cond instanceof $comparisonClass) {
return null;
}

if ($this->isNull($cond->right)) {
$subject = $cond->left;
} elseif ($this->isNull($cond->left)) {
$subject = $cond->right;
} else {
return null;
}

return $this->isFreeOfSideEffects($subject) ? $subject : null;
}

private function isFreeOfSideEffects(Expr $expr): bool
{
if ($expr instanceof Variable) {
return is_string($expr->name);
}

if ($expr instanceof PropertyFetch) {
return $expr->name instanceof Identifier && $this->isFreeOfSideEffects($expr->var);
}

return $expr instanceof StaticPropertyFetch && $expr->class instanceof Name && $expr->name instanceof VarLikeIdentifier;
}

/**
* Replaces the first -> on $subjectString in the chain with ?->, which also short-circuits the rest of the chain.
*/
private function createNullsafeChain(Expr $chain, string $subjectString): ?Expr
{
if ($chain instanceof MethodCall && $chain->isFirstClassCallable()) {
return null;
}

if (
($chain instanceof PropertyFetch || $chain instanceof MethodCall)
&& $this->printer->printExpr($chain->var) === $subjectString
) {
if ($chain instanceof PropertyFetch) {
return new NullsafePropertyFetch($chain->var, $chain->name);
}

return new NullsafeMethodCall($chain->var, $chain->name, $chain->args);
}

if (
!$chain instanceof PropertyFetch
&& !$chain instanceof MethodCall
&& !$chain instanceof NullsafePropertyFetch
&& !$chain instanceof NullsafeMethodCall
&& !$chain instanceof ArrayDimFetch
) {
return null;
}

$var = $this->createNullsafeChain($chain->var, $subjectString);
if ($var === null) {
return null;
}

$chain = clone $chain;
$chain->var = $var;

return $chain;
}

private function hasMultilineArgs(Node $node): bool
{
while ($node instanceof Expression || $node instanceof ArrayDimFetch || $node instanceof PropertyFetch || $node instanceof MethodCall || $node instanceof NullsafePropertyFetch || $node instanceof NullsafeMethodCall) {
if ($node instanceof Expression) {
$node = $node->expr;
continue;
}

if ($node instanceof NullsafeMethodCall) {
foreach ($node->getArgs() as $arg) {
if ($arg->getStartLine() !== $node->name->getStartLine()) {
return true;
}
}
}

$node = $node->var;
}

return false;
}

private function isNull(?Expr $expr): bool
{
return $expr instanceof ConstFetch && $expr->name->toLowerString() === 'null';
}

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

services:
Expand Down
2 changes: 1 addition & 1 deletion compiler/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"require": {
"php": "^8.2",
"nette/neon": "^3.0.0",
"ondrejmirtes/simple-downgrader": "^2.3.0",
"ondrejmirtes/simple-downgrader": "^2.4.0",
"seld/phar-utils": "^1.2",
"symfony/console": "^5.4.43",
"symfony/filesystem": "^5.4.43",
Expand Down
16 changes: 8 additions & 8 deletions compiler/composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/Analyser/ArgumentsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@
) {
$writebackAcceptor = $resolvedAcceptor;
}
$writebackParameters = $writebackAcceptor !== null ? $writebackAcceptor->getParameters() : null;
$writebackParameters = $writebackAcceptor?->getParameters();
if ($writebackParameters !== null) {
foreach ($args as $i => $arg) {
$assignByReference = false;
Expand Down Expand Up @@ -813,7 +813,7 @@
}
}

$scope = $this->assignHandler->processVirtualAssign(

Check failure on line 816 in src/Analyser/ArgumentsHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 816 in src/Analyser/ArgumentsHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
$nodeScopeResolver,
$scope,
$storage,
Expand Down
2 changes: 1 addition & 1 deletion src/Analyser/ExprHandler/ArrayDimFetchHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ private static function offsetRead(ArrayDimFetch $expr, ?ExpressionResult $dimRe
return null;
}
$target = $context->getValueFlowTarget();
return VariableFlow::read($expr->var->name, $target !== null ? $target->getId() : null, offset: $dimResult !== null ? VariableWriteOffset::fromType($dimResult->getType()) : null);
return VariableFlow::read($expr->var->name, $target?->getId(), offset: $dimResult !== null ? VariableWriteOffset::fromType($dimResult->getType()) : null);
}

}
4 changes: 2 additions & 2 deletions src/Analyser/ExprHandler/AssignHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@
targetReadResult: $targetReadResult,
targetChainResults: $targetChainResults,
variableNameResult: $variableNameResult,
dependencies: $variableNameResult !== null ? $variableNameResult->getDependencies() : null,
dependencies: $variableNameResult?->getDependencies(),
);
}

Expand Down Expand Up @@ -766,7 +766,7 @@
while ($chainVar instanceof ArrayDimFetch) {
$varForSetOffsetValue = $chainVar->var;
if ($varForSetOffsetValue instanceof PropertyFetch || $varForSetOffsetValue instanceof StaticPropertyFetch) {
$varForSetOffsetValue = new TypeExpr($this->getOriginalPropertyType($nodeScopeResolver, $varForSetOffsetValue, $scope));

Check failure on line 769 in src/Analyser/ExprHandler/AssignHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 769 in src/Analyser/ExprHandler/AssignHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
}

if (
Expand Down Expand Up @@ -1819,7 +1819,7 @@
$throwPoints = array_merge($throwPoints, $result->getThrowPoints());
$impurePoints = array_merge($impurePoints, $result->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || $result->isAlwaysTerminating();
$writeDependencies[] = $keyResult !== null ? $keyResult->getDependencies() : null;
$writeDependencies[] = $keyResult?->getDependencies();
$writeDependencies[] = $result->getDependencies();
}
} elseif ($kind === PreparedAssignTarget::KIND_EXISTING_ARRAY_DIM_FETCH) {
Expand Down Expand Up @@ -1884,7 +1884,7 @@
$beforeScope,
$var,
$hasYield,
$isAlwaysTerminating,

Check failure on line 1887 in src/Analyser/ExprHandler/AssignHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 1887 in src/Analyser/ExprHandler/AssignHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
$throwPoints,
$impurePoints,
typeCallback: static fn () => new MixedType(),
Expand Down
6 changes: 3 additions & 3 deletions src/Analyser/ExprHandler/ClassConstFetchHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: VariableFlow::sequence($classResult !== null ? $classResult->getVariableFlow() : null, $nameResult !== null ? $nameResult->getVariableFlow() : null),
variableFlow: VariableFlow::sequence($classResult?->getVariableFlow(), $nameResult?->getVariableFlow()),
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: $throwPoints,
Expand Down Expand Up @@ -120,18 +120,18 @@
);

return $result->withDependencies(Dependencies::merge(
$classResult !== null ? $classResult->getDependencies() : null,
$nameResult !== null ? $nameResult->getDependencies() : null,
$classResult?->getDependencies(),
$nameResult?->getDependencies(),
$this->getDependencies($beforeScope, $expr, $classResult, $result),
));
}

/**

Check failure on line 129 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 129 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 129 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 129 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
* The class the constant is fetched from, the class declaring it, and the classes in its type.
*/
private function getDependencies(MutatingScope $scope, ClassConstFetch $expr, ?ExpressionResult $classResult, ExpressionResult $result): ?Dependencies
{

Check failure on line 133 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 133 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
$types = [$result->getType()];

Check failure on line 134 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, ubuntu-latest)

This null check can be replaced with the nullsafe operator (?->).

Check failure on line 134 in src/Analyser/ExprHandler/ClassConstFetchHandler.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, windows-latest)

This null check can be replaced with the nullsafe operator (?->).
$classNames = [];
if ($classResult !== null) {
$types[] = $classResult->getType();
Expand Down
8 changes: 4 additions & 4 deletions src/Analyser/ExprHandler/FuncCallHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
&& in_array($expr->name->toLowerString(), ['array_key_exists', 'key_exists', 'in_array', 'is_subclass_of'], true)
) {
$callStorage = $storageRef->get();
$callResult = $callStorage === null ? null : $callStorage->findExpressionResult($expr);
$callResult = $callStorage?->findExpressionResult($expr);
if ($callResult !== null) {
$isAlways = $this->impossibleCheckTypeHelper->findSpecifiedType($beforeScope, $expr, $callResult, $argsResult);
if ($isAlways !== null) {
Expand Down Expand Up @@ -587,16 +587,16 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
}
$byRefFlow = $byRefFlows === [] ? null : VariableFlow::sequence(...$byRefFlows);
$variableFlow = VariableFlow::sequence(
$nameResult !== null ? $nameResult->getVariableFlow() : null,
$nameResult?->getVariableFlow(),
VariableFlowBuilder::arguments($expr, $argsResult, $storage),
self::getCallVariableFlow($functionReflection !== null ? $functionReflection->getName() : null, $normalizedExpr, $argsResult, $scope),
self::getCallVariableFlow($functionReflection?->getName(), $normalizedExpr, $argsResult, $scope),
VariableFlowBuilder::throws($expr, $throwPoints),
$byRefFlow,
$isAlwaysTerminating ? VariableFlow::exit(VariableFlow::STOP) : null,
);

$dependencies = Dependencies::merge(
$nameResult !== null ? $nameResult->getDependencies() : null,
$nameResult?->getDependencies(),
$argsResult->getDependencies(),
$this->getDependencies($beforeScope, $functionReflection, $nameResult, $preliminaryResult),
);
Expand Down
Loading
Loading