|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Symfony; |
| 4 | + |
| 5 | +use PhpParser\Node; |
| 6 | +use PhpParser\Node\Expr\MethodCall; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\ShouldNotHappenException; |
| 10 | +use PHPStan\Symfony\UrlGeneratingRoutesMap; |
| 11 | +use PHPStan\Type\ObjectType; |
| 12 | + |
| 13 | +/** |
| 14 | + * @implements Rule<MethodCall> |
| 15 | + */ |
| 16 | +final class UrlGeneratorInterfaceUnknownRouteRule implements Rule |
| 17 | +{ |
| 18 | + |
| 19 | + /** @var UrlGeneratingRoutesMap */ |
| 20 | + private $urlGeneratingRoutesMap; |
| 21 | + |
| 22 | + public function __construct(UrlGeneratingRoutesMap $urlGeneratingRoutesMap) |
| 23 | + { |
| 24 | + $this->urlGeneratingRoutesMap = $urlGeneratingRoutesMap; |
| 25 | + } |
| 26 | + |
| 27 | + public function getNodeType(): string |
| 28 | + { |
| 29 | + return MethodCall::class; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @param \PhpParser\Node $node |
| 34 | + * @param \PHPStan\Analyser\Scope $scope |
| 35 | + * @return (string|\PHPStan\Rules\RuleError)[] errors |
| 36 | + */ |
| 37 | + public function processNode(Node $node, Scope $scope): array |
| 38 | + { |
| 39 | + if (!$node instanceof MethodCall) { |
| 40 | + throw new ShouldNotHappenException(); |
| 41 | + } |
| 42 | + |
| 43 | + if (!$node->name instanceof Node\Identifier) { |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + if (in_array($node->name->name, ['generate', 'generateUrl'], true) === false || !isset($node->getArgs()[0])) { |
| 48 | + return []; |
| 49 | + } |
| 50 | + |
| 51 | + $argType = $scope->getType($node->var); |
| 52 | + $isControllerType = (new ObjectType('Symfony\Bundle\FrameworkBundle\Controller\Controller'))->isSuperTypeOf($argType); |
| 53 | + $isAbstractControllerType = (new ObjectType('Symfony\Bundle\FrameworkBundle\Controller\AbstractController'))->isSuperTypeOf($argType); |
| 54 | + $isUrlGeneratorInterface = (new ObjectType('Symfony\Component\Routing\Generator\UrlGeneratorInterface'))->isSuperTypeOf($argType); |
| 55 | + if ( |
| 56 | + $isControllerType->no() |
| 57 | + && $isAbstractControllerType->no() |
| 58 | + && $isUrlGeneratorInterface->no() |
| 59 | + ) { |
| 60 | + return []; |
| 61 | + } |
| 62 | + |
| 63 | + $routeName = $this->urlGeneratingRoutesMap::getRouteNameFromNode($node->getArgs()[0]->value, $scope); |
| 64 | + if ($routeName === null) { |
| 65 | + return []; |
| 66 | + } |
| 67 | + |
| 68 | + if ($this->urlGeneratingRoutesMap->hasRouteName($routeName) === false) { |
| 69 | + return [sprintf('Route with name "%s" does not exist.', $routeName)]; |
| 70 | + } |
| 71 | + |
| 72 | + return []; |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments