|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tempest\Upgrade\Tempest3; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Identifier; |
| 7 | +use PhpParser\Node\Name; |
| 8 | +use PhpParser\Node\NullableType; |
| 9 | +use PhpParser\Node\Stmt\ClassMethod; |
| 10 | +use PhpParser\Node\Stmt\Interface_; |
| 11 | +use Rector\Rector\AbstractRector; |
| 12 | + |
| 13 | +final class UpdateBindableResolveReturnTypeRector extends AbstractRector |
| 14 | +{ |
| 15 | + public function getNodeTypes(): array |
| 16 | + { |
| 17 | + return [ |
| 18 | + Node\Stmt\Class_::class, |
| 19 | + Interface_::class, |
| 20 | + ]; |
| 21 | + } |
| 22 | + |
| 23 | + public function refactor(Node $node): ?int |
| 24 | + { |
| 25 | + if ($node instanceof Interface_) { |
| 26 | + if (! $this->hasBindableName($node->extends)) { |
| 27 | + return null; |
| 28 | + } |
| 29 | + |
| 30 | + $this->refactorMethods($node->getMethods()); |
| 31 | + |
| 32 | + return null; |
| 33 | + } |
| 34 | + |
| 35 | + if (! $node instanceof Node\Stmt\Class_) { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + if (! $this->hasBindableName($node->implements)) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + $this->refactorMethods($node->getMethods()); |
| 44 | + |
| 45 | + return null; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @param Name[] $names |
| 50 | + */ |
| 51 | + private function hasBindableName(array $names): bool |
| 52 | + { |
| 53 | + foreach ($names as $name) { |
| 54 | + $value = ltrim($name->toString(), '\\'); |
| 55 | + |
| 56 | + if ($value === 'Tempest\\Router\\Bindable' || $value === 'Bindable') { |
| 57 | + return true; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return false; |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @param ClassMethod[] $methods |
| 66 | + */ |
| 67 | + private function refactorMethods(array $methods): void |
| 68 | + { |
| 69 | + foreach ($methods as $method) { |
| 70 | + if ($method->name->toString() !== 'resolve' || ! $method->isStatic()) { |
| 71 | + continue; |
| 72 | + } |
| 73 | + |
| 74 | + if ($method->returnType instanceof NullableType && $method->returnType->type instanceof Identifier && $method->returnType->type->toString() === 'static') { |
| 75 | + continue; |
| 76 | + } |
| 77 | + |
| 78 | + $method->returnType = new NullableType(new Identifier('static')); |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments