|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Rules\Doctrine\ORM; |
| 4 | + |
| 5 | +use Doctrine\ORM\EntityManagerInterface; |
| 6 | +use PhpParser\Node; |
| 7 | +use PHPStan\Analyser\Scope; |
| 8 | +use PHPStan\Rules\Rule; |
| 9 | +use PHPStan\ShouldNotHappenException; |
| 10 | +use PHPStan\Type\Constant\ConstantStringType; |
| 11 | +use PHPStan\Type\Doctrine\ObjectMetadataResolver; |
| 12 | +use PHPStan\Type\ObjectType; |
| 13 | + |
| 14 | +class DqlRule implements Rule |
| 15 | +{ |
| 16 | + |
| 17 | + /** @var ObjectMetadataResolver */ |
| 18 | + private $objectMetadataResolver; |
| 19 | + |
| 20 | + public function __construct(ObjectMetadataResolver $objectMetadataResolver) |
| 21 | + { |
| 22 | + $this->objectMetadataResolver = $objectMetadataResolver; |
| 23 | + } |
| 24 | + |
| 25 | + public function getNodeType(): string |
| 26 | + { |
| 27 | + return Node\Expr\MethodCall::class; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * @param \PhpParser\Node\Expr\MethodCall $node |
| 32 | + * @param \PHPStan\Analyser\Scope $scope |
| 33 | + * @return string[] |
| 34 | + */ |
| 35 | + public function processNode(Node $node, Scope $scope): array |
| 36 | + { |
| 37 | + if (!$node->name instanceof Node\Identifier) { |
| 38 | + return []; |
| 39 | + } |
| 40 | + |
| 41 | + if (count($node->args) === 0) { |
| 42 | + return []; |
| 43 | + } |
| 44 | + |
| 45 | + $dqlType = $scope->getType($node->args[0]->value); |
| 46 | + if (!$dqlType instanceof ConstantStringType) { |
| 47 | + return []; |
| 48 | + } |
| 49 | + |
| 50 | + $methodName = $node->name->toLowerString(); |
| 51 | + if ($methodName !== 'createquery') { |
| 52 | + return []; |
| 53 | + } |
| 54 | + |
| 55 | + $calledOnType = $scope->getType($node->var); |
| 56 | + $entityManagerInterface = 'Doctrine\ORM\EntityManagerInterface'; |
| 57 | + if (!(new ObjectType($entityManagerInterface))->isSuperTypeOf($calledOnType)->yes()) { |
| 58 | + return []; |
| 59 | + } |
| 60 | + |
| 61 | + $objectManager = $this->objectMetadataResolver->getObjectManager(); |
| 62 | + if ($objectManager === null) { |
| 63 | + throw new ShouldNotHappenException('Please provide the "objectManagerLoader" setting for the DQL validation.'); |
| 64 | + } |
| 65 | + if (!$objectManager instanceof $entityManagerInterface) { |
| 66 | + return []; |
| 67 | + } |
| 68 | + |
| 69 | + /** @var EntityManagerInterface $objectManager */ |
| 70 | + $objectManager = $objectManager; |
| 71 | + |
| 72 | + $dql = $dqlType->getValue(); |
| 73 | + $query = $objectManager->createQuery($dql); |
| 74 | + |
| 75 | + try { |
| 76 | + $query->getSQL(); |
| 77 | + } catch (\Doctrine\ORM\Query\QueryException $e) { |
| 78 | + return [sprintf('DQL: %s', $e->getMessage())]; |
| 79 | + } |
| 80 | + |
| 81 | + return []; |
| 82 | + } |
| 83 | + |
| 84 | +} |
0 commit comments