2019-12-27 16:44:29 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Rector\CodeQuality\Rector\FuncCall;
|
|
|
|
|
|
|
|
use PhpParser\Node;
|
|
|
|
use PhpParser\Node\Expr\Cast\Int_;
|
|
|
|
use PhpParser\Node\Expr\FuncCall;
|
2020-02-06 21:48:18 +00:00
|
|
|
use Rector\Core\Rector\AbstractRector;
|
2020-11-16 17:50:38 +00:00
|
|
|
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
|
|
|
|
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
|
2019-12-27 16:44:29 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @see https://github.com/kalessil/phpinspectionsea/commit/25f53c8c7e08234c34b0d21f308f7c5cbd7a6c95
|
|
|
|
* @see https://www.php.net/manual/en/function.intval.php
|
|
|
|
*
|
|
|
|
* @see \Rector\CodeQuality\Tests\Rector\FuncCall\IntvalToTypeCastRector\IntvalToTypeCastRectorTest
|
|
|
|
*/
|
|
|
|
final class IntvalToTypeCastRector extends AbstractRector
|
|
|
|
{
|
2020-11-16 17:50:38 +00:00
|
|
|
public function getRuleDefinition(): RuleDefinition
|
2019-12-27 16:44:29 +00:00
|
|
|
{
|
2020-11-16 17:50:38 +00:00
|
|
|
return new RuleDefinition(
|
|
|
|
'Change intval() to faster and readable (int) $value',
|
|
|
|
[
|
|
|
|
new CodeSample(
|
|
|
|
<<<'CODE_SAMPLE'
|
2019-12-27 16:44:29 +00:00
|
|
|
class SomeClass
|
|
|
|
{
|
|
|
|
public function run($value)
|
|
|
|
{
|
|
|
|
return intval($value);
|
|
|
|
}
|
|
|
|
}
|
2020-09-15 08:23:13 +00:00
|
|
|
CODE_SAMPLE
|
2019-12-27 16:44:29 +00:00
|
|
|
,
|
2020-11-16 17:50:38 +00:00
|
|
|
<<<'CODE_SAMPLE'
|
2019-12-27 16:44:29 +00:00
|
|
|
class SomeClass
|
|
|
|
{
|
|
|
|
public function run($value)
|
|
|
|
{
|
|
|
|
return (int) $value;
|
|
|
|
}
|
|
|
|
}
|
2020-09-15 08:23:13 +00:00
|
|
|
CODE_SAMPLE
|
2020-11-16 17:50:38 +00:00
|
|
|
),
|
|
|
|
|
|
|
|
]);
|
2019-12-27 16:44:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return string[]
|
|
|
|
*/
|
|
|
|
public function getNodeTypes(): array
|
|
|
|
{
|
|
|
|
return [FuncCall::class];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param FuncCall $node
|
|
|
|
*/
|
|
|
|
public function refactor(Node $node): ?Node
|
|
|
|
{
|
|
|
|
if (! $this->isName($node, 'intval')) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isset($node->args[1])) {
|
2021-01-30 23:20:05 +00:00
|
|
|
$secondArgumentValue = $this->valueResolver->getValue($node->args[1]->value);
|
2019-12-27 16:44:29 +00:00
|
|
|
// default value
|
|
|
|
if ($secondArgumentValue !== 10) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Int_($node->args[0]->value);
|
|
|
|
}
|
|
|
|
}
|