|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Cake\Upgrade\Rector\Cake6; |
| 5 | + |
| 6 | +use PhpParser\Node; |
| 7 | +use PhpParser\Node\Expr\MethodCall; |
| 8 | +use PhpParser\Node\Identifier; |
| 9 | +use PHPStan\Type\ObjectType; |
| 10 | +use Rector\Rector\AbstractRector; |
| 11 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 12 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 13 | + |
| 14 | +/** |
| 15 | + * Renames translation() to getOrCreateTranslation() for entities using TranslateTrait. |
| 16 | + * |
| 17 | + * In CakePHP 6.0, translation() became a pure getter that returns null if no translation exists. |
| 18 | + * The old create-on-access behavior is now in getOrCreateTranslation(). |
| 19 | + * |
| 20 | + * @see https://github.com/cakephp/cakephp/pull/19251 |
| 21 | + */ |
| 22 | +final class TranslationToGetOrCreateTranslationRector extends AbstractRector |
| 23 | +{ |
| 24 | + public function getRuleDefinition(): RuleDefinition |
| 25 | + { |
| 26 | + return new RuleDefinition( |
| 27 | + 'Rename $entity->translation() to $entity->getOrCreateTranslation() to preserve create-on-access behavior', |
| 28 | + [ |
| 29 | + new CodeSample( |
| 30 | + <<<'CODE_SAMPLE' |
| 31 | +$article->translation('fra'); |
| 32 | +CODE_SAMPLE |
| 33 | + , |
| 34 | + <<<'CODE_SAMPLE' |
| 35 | +$article->getOrCreateTranslation('fra'); |
| 36 | +CODE_SAMPLE, |
| 37 | + ), |
| 38 | + ], |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @return array<class-string<\PhpParser\Node>> |
| 44 | + */ |
| 45 | + public function getNodeTypes(): array |
| 46 | + { |
| 47 | + return [MethodCall::class]; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * @param \PhpParser\Node\Expr\MethodCall $node |
| 52 | + */ |
| 53 | + public function refactor(Node $node): ?Node |
| 54 | + { |
| 55 | + if (!$node->name instanceof Identifier) { |
| 56 | + return null; |
| 57 | + } |
| 58 | + |
| 59 | + if ($node->name->toString() !== 'translation') { |
| 60 | + return null; |
| 61 | + } |
| 62 | + |
| 63 | + if (!$this->isObjectType($node->var, new ObjectType('Cake\ORM\Entity'))) { |
| 64 | + return null; |
| 65 | + } |
| 66 | + |
| 67 | + $node->name = new Identifier('getOrCreateTranslation'); |
| 68 | + |
| 69 | + return $node; |
| 70 | + } |
| 71 | +} |
0 commit comments