|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\DowngradePhp86\Rector\FuncCall; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Arg; |
| 9 | +use PhpParser\Node\Expr\FuncCall; |
| 10 | +use Rector\Rector\AbstractRector; |
| 11 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 12 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 13 | + |
| 14 | +/** |
| 15 | + * @see https://wiki.php.net/rfc/clamp_v2 |
| 16 | + * @see \Rector\Tests\DowngradePhp86\Rector\FuncCall\DowngradeClampRector\DowngradeClampRectorTest |
| 17 | + */ |
| 18 | +final class DowngradeClampRector extends AbstractRector |
| 19 | +{ |
| 20 | + public function getRuleDefinition(): RuleDefinition |
| 21 | + { |
| 22 | + return new RuleDefinition( |
| 23 | + 'Replace clamp() with min()/max().', |
| 24 | + [ |
| 25 | + new CodeSample( |
| 26 | + <<<'CODE_SAMPLE' |
| 27 | +clamp($value, $min, $max); |
| 28 | +CODE_SAMPLE |
| 29 | + , |
| 30 | + <<<'CODE_SAMPLE' |
| 31 | +max($min, min($max, $value)); |
| 32 | +CODE_SAMPLE |
| 33 | + ), |
| 34 | + ] |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + public function getNodeTypes(): array |
| 39 | + { |
| 40 | + return [FuncCall::class]; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * @param FuncCall $node |
| 45 | + */ |
| 46 | + public function refactor(Node $node): ?Node |
| 47 | + { |
| 48 | + if (! $this->isName($node, 'clamp')) { |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + if ($node->isFirstClassCallable()) { |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + $valueArg = $node->getArg('value', 0); |
| 57 | + $minArg = $node->getArg('min', 1); |
| 58 | + $maxArg = $node->getArg('max', 2); |
| 59 | + |
| 60 | + if (! $valueArg instanceof Arg || ! $minArg instanceof Arg || ! $maxArg instanceof Arg) { |
| 61 | + return null; |
| 62 | + } |
| 63 | + |
| 64 | + return $this->nodeFactory->createFuncCall('max', [ |
| 65 | + $minArg->value, |
| 66 | + $this->nodeFactory->createFuncCall('min', [$maxArg->value, $valueArg->value]), |
| 67 | + ]); |
| 68 | + } |
| 69 | +} |
0 commit comments