|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Cake\Upgrade\Rector\Rector\MethodCall; |
| 5 | + |
| 6 | +use Cake\ORM\Entity; |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\BooleanNot; |
| 9 | +use PhpParser\Node\Expr\MethodCall; |
| 10 | +use PhpParser\Node\Identifier; |
| 11 | +use PHPStan\Type\ObjectType; |
| 12 | +use Rector\Rector\AbstractRector; |
| 13 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 14 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 15 | + |
| 16 | +final class EntityIsEmptyRector extends AbstractRector |
| 17 | +{ |
| 18 | + public function getRuleDefinition(): RuleDefinition |
| 19 | + { |
| 20 | + return new RuleDefinition( |
| 21 | + 'Replace $entity->isEmpty() with !$entity->hasValue() for \Cake\ORM\Entity descendants', |
| 22 | + [ |
| 23 | + new CodeSample( |
| 24 | + '$entity->isEmpty();', |
| 25 | + '!$entity->hasValue();', |
| 26 | + ), |
| 27 | + ], |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + public function getNodeTypes(): array |
| 32 | + { |
| 33 | + return [MethodCall::class]; |
| 34 | + } |
| 35 | + |
| 36 | + public function refactor(Node $node): ?Node |
| 37 | + { |
| 38 | + if (!$node instanceof MethodCall) { |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + if (!$this->isName($node->name, 'isEmpty')) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + $objectType = $this->getType($node->var); |
| 47 | + if (!$objectType instanceof ObjectType) { |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + if (!$objectType->isInstanceOf(Entity::class)->yes()) { |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + // Replace with !$entity->hasValue() |
| 56 | + return new BooleanNot(new MethodCall($node->var, new Identifier('hasValue'))); |
| 57 | + } |
| 58 | +} |
0 commit comments