|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace RectorLaravel\Rector\MethodCall; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\MethodCall; |
| 9 | +use PhpParser\Node\Identifier; |
| 10 | +use PHPStan\Type\ObjectType; |
| 11 | +use RectorLaravel\AbstractRector; |
| 12 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 13 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 14 | + |
| 15 | +/** |
| 16 | + * @see \RectorLaravel\Tests\Rector\MethodCall\UnaliasCollectionMethodsRector\UnaliasCollectionMethodsRectorTest |
| 17 | + */ |
| 18 | +final class UnaliasCollectionMethodsRector extends AbstractRector |
| 19 | +{ |
| 20 | + public function getRuleDefinition(): RuleDefinition |
| 21 | + { |
| 22 | + return new RuleDefinition( |
| 23 | + 'Use the base collection methods instead of their aliases.', |
| 24 | + [ |
| 25 | + new CodeSample( |
| 26 | + <<<'CODE_SAMPLE' |
| 27 | +use Illuminate\Support\Collection; |
| 28 | +
|
| 29 | +$collection = new Collection([0, 1, null, -1]); |
| 30 | +$collection->average(); |
| 31 | +$collection->some(fn (?int $number): bool => is_null($number)); |
| 32 | +CODE_SAMPLE |
| 33 | + , |
| 34 | + <<<'CODE_SAMPLE' |
| 35 | +use Illuminate\Support\Collection; |
| 36 | +
|
| 37 | +$collection = new Collection([0, 1, null, -1]); |
| 38 | +$collection->avg(); |
| 39 | +$collection->contains(fn (?int $number): bool => is_null($number)); |
| 40 | +CODE_SAMPLE |
| 41 | + ), |
| 42 | + ] |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * @return array<class-string<Node>> |
| 48 | + */ |
| 49 | + public function getNodeTypes(): array |
| 50 | + { |
| 51 | + return [MethodCall::class]; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @param MethodCall $node |
| 56 | + */ |
| 57 | + public function refactor(Node $node): ?Node |
| 58 | + { |
| 59 | + return $this->updateMethodCall($node); |
| 60 | + } |
| 61 | + |
| 62 | + private function updateMethodCall(MethodCall $methodCall): ?MethodCall |
| 63 | + { |
| 64 | + if (! $this->isObjectType($methodCall->var, new ObjectType('Illuminate\Support\Enumerable'))) { |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + $name = $methodCall->name; |
| 69 | + if ($this->isName($name, 'some')) { |
| 70 | + $replacement = 'contains'; |
| 71 | + } elseif ($this->isName($name, 'average')) { |
| 72 | + $replacement = 'avg'; |
| 73 | + } else { |
| 74 | + return null; |
| 75 | + } |
| 76 | + |
| 77 | + $methodCall->name = new Identifier($replacement); |
| 78 | + |
| 79 | + return $methodCall; |
| 80 | + } |
| 81 | +} |
0 commit comments