Skip to content

Commit

Permalink
[CodeQuality] Handle crash on first class callable inside match on Op…
Browse files Browse the repository at this point in the history
…tionalParametersAfterRequiredRector (#6263)

* [CodeQuality] Handle crash on first class callable inside match on OptionalParametersAfterRequiredRector

* Fix

* Fix

* Fix

* Fix
  • Loading branch information
samsonasik authored Aug 28, 2024
1 parent 8073ee7 commit 816c733
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\OptionalParametersAfterRequiredRector\Fixture;

use Rector\Tests\CodeQuality\Rector\ClassMethod\OptionalParametersAfterRequiredRector\Source\SomeClass;

final class SkipMatchWithFirstClassCallable
{
public function run($type):void
{
match($type) {
'string' => SomeClass::fromString(...),
'int' => function () {
return SomeClass::fromInt(...);
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\OptionalParametersAfterRequiredRector\Source;

class SomeClass
{
public static function fromString(string $id) {}
public static function fromInt(int $id) {}
}
20 changes: 20 additions & 0 deletions src/NodeTypeResolver/PHPStan/Scope/PHPStanNodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\NullsafeMethodCall;
Expand Down Expand Up @@ -270,6 +271,11 @@ public function processNodes(
$this->processCallike($node, $mutatingScope);
return;
}

if ($node instanceof Match_) {
$this->processMatch($node, $mutatingScope);
return;
}
};

$this->nodeScopeResolverProcessNodes($stmts, $scope, $nodeCallback);
Expand All @@ -286,6 +292,20 @@ public function processNodes(
return $stmts;
}

private function processMatch(Match_ $match, MutatingScope $mutatingScope): void
{
$match->cond->setAttribute(AttributeKey::SCOPE, $mutatingScope);
foreach ($match->arms as $arm) {
if ($arm->conds !== null) {
foreach ($arm->conds as $cond) {
$cond->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}

$arm->body->setAttribute(AttributeKey::SCOPE, $mutatingScope);
}
}

/**
* @param Stmt[] $stmts
* @param callable(Node $node, MutatingScope $scope): void $nodeCallback
Expand Down

0 comments on commit 816c733

Please sign in to comment.