|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Utils\Rector; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Arg; |
| 9 | +use PhpParser\Node\Expr\ConstFetch; |
| 10 | +use PhpParser\Node\Expr\FuncCall; |
| 11 | +use PhpParser\Node\Name; |
| 12 | +use Rector\Core\Rector\AbstractRector; |
| 13 | +use Rector\Core\RectorDefinition\CodeSample; |
| 14 | +use Rector\Core\RectorDefinition\RectorDefinition; |
| 15 | + |
| 16 | +/** |
| 17 | + * Pass strict to function parameter on specific position argument when no value provided |
| 18 | + */ |
| 19 | +final class PassStrictParameterToFunctionParameterRector extends AbstractRector |
| 20 | +{ |
| 21 | + private const FUNCTION_WITH_ARG_POSITION = [ |
| 22 | + // position start from 0 |
| 23 | + 'in_array' => 2, |
| 24 | + ]; |
| 25 | + |
| 26 | + public function getDefinition(): RectorDefinition |
| 27 | + { |
| 28 | + return new RectorDefinition('Pass strict to function parameter on specific position argument when no value provided', [ |
| 29 | + new CodeSample( |
| 30 | + <<<'CODE_SAMPLE' |
| 31 | +in_array('a', $array); |
| 32 | +CODE_SAMPLE |
| 33 | +, |
| 34 | + <<<'CODE_SAMPLE' |
| 35 | +in_array('a', $array, true); |
| 36 | +CODE_SAMPLE |
| 37 | + ), |
| 38 | + ]); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * @return string[] |
| 43 | + */ |
| 44 | + public function getNodeTypes(): array |
| 45 | + { |
| 46 | + return [FuncCall::class]; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * @param FuncCall $node |
| 51 | + */ |
| 52 | + public function refactor(Node $node): ?Node |
| 53 | + { |
| 54 | + $name = $node->name; |
| 55 | + if (! method_exists($name, 'toString')) |
| 56 | + { |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | + $functions = array_keys(self::FUNCTION_WITH_ARG_POSITION); |
| 61 | + $currentFunctionName = $name->toString(); |
| 62 | + |
| 63 | + if (! in_array($currentFunctionName, $functions, true)) |
| 64 | + { |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + $position = self::FUNCTION_WITH_ARG_POSITION[$currentFunctionName]; |
| 69 | + |
| 70 | + if (isset($node->args[$position])) |
| 71 | + { |
| 72 | + return null; |
| 73 | + } |
| 74 | + |
| 75 | + $name = new Name('true'); |
| 76 | + $node->args[$position] = new Arg(new ConstFetch($name)); |
| 77 | + |
| 78 | + return $node; |
| 79 | + } |
| 80 | +} |
0 commit comments