rector/rules/Php81/Rector/MethodCall/MyCLabsMethodCallToEnumConstRector.php
Tomas Votruba 96112cb1f0 Updated Rector to commit 2da49992cc
2da49992cc [Downgrade] [PHP 7.2] Make DowngradeParameterTypeWideningRector always downgrade to phpdoc type (#390)
2021-07-05 22:50:18 +00:00

64 lines
2.1 KiB
PHP

<?php
declare (strict_types=1);
namespace Rector\Php81\Rector\MethodCall;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Type\ObjectType;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @changelog https://wiki.php.net/rfc/enumerations
* @changelog https://github.com/myclabs/php-enum
*
* @see \Rector\Tests\Php81\Rector\MethodCall\MyCLabsMethodCallToEnumConstRector\MyCLabsMethodCallToEnumConstRectorTest
*/
final class MyCLabsMethodCallToEnumConstRector extends \Rector\Core\Rector\AbstractRector
{
public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
{
return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Refactor MyCLabs enum fetch to Enum const', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
$name = SomeEnum::VALUE()->getKey();
CODE_SAMPLE
, <<<'CODE_SAMPLE'
$name = SomeEnum::VALUE;
CODE_SAMPLE
)]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [\PhpParser\Node\Expr\MethodCall::class];
}
/**
* @param MethodCall $node
*/
public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
{
if (!$this->isObjectType($node->var, new \PHPStan\Type\ObjectType('MyCLabs\\Enum\\Enum'))) {
return null;
}
if (!$this->isName($node->name, 'getKey')) {
return null;
}
if (!$node->var instanceof \PhpParser\Node\Expr\StaticCall) {
return null;
}
$staticCall = $node->var;
$className = $this->getName($staticCall->class);
if ($className === null) {
return null;
}
$enumCaseName = $this->getName($staticCall->name);
if ($enumCaseName === null) {
return null;
}
return $this->nodeFactory->createClassConstFetch($className, $enumCaseName);
}
}