|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Rules\Doctrine; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Stmt\Class_; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Node\InClassNode; |
| 11 | +use PHPStan\Rules\Rule; |
| 12 | +use PHPStan\Rules\RuleErrorBuilder; |
| 13 | +use Symplify\PHPStanRules\Doctrine\DoctrineEventSubscriberAnalyzer; |
| 14 | +use Symplify\PHPStanRules\Enum\DoctrineRuleIdentifier; |
| 15 | + |
| 16 | +/** |
| 17 | + * Based on https://tomasvotruba.com/blog/2019/07/22/how-to-convert-listeners-to-subscribers-and-reduce-your-configs |
| 18 | + * Subscribers have much better PHP support - IDE, PHPStan + Rector - than simple yaml files |
| 19 | + * |
| 20 | + * @implements Rule<InClassNode> |
| 21 | + * |
| 22 | + * @see \Symplify\PHPStanRules\Tests\Rules\Doctrine\NoDoctrineListenerWithoutContractRule\NoDoctrineListenerWithoutContractRuleTest |
| 23 | + */ |
| 24 | +final class NoDoctrineListenerWithoutContractRule implements Rule |
| 25 | +{ |
| 26 | + /** |
| 27 | + * @var string |
| 28 | + */ |
| 29 | + public const ERROR_MESSAGE = 'There should be no Doctrine listeners modified in config. Implement "Document\Event\EventSubscriber" to provide events in the class itself'; |
| 30 | + |
| 31 | + public function getNodeType(): string |
| 32 | + { |
| 33 | + return InClassNode::class; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param InClassNode $node |
| 38 | + */ |
| 39 | + public function processNode(Node $node, Scope $scope): array |
| 40 | + { |
| 41 | + if (! $scope->isInClass()) { |
| 42 | + return []; |
| 43 | + } |
| 44 | + |
| 45 | + $classReflection = $scope->getClassReflection(); |
| 46 | + if (! str_ends_with($classReflection->getName(), 'Listener')) { |
| 47 | + return []; |
| 48 | + } |
| 49 | + |
| 50 | + $classLike = $node->getOriginalNode(); |
| 51 | + if (! $classLike instanceof Class_) { |
| 52 | + return []; |
| 53 | + } |
| 54 | + |
| 55 | + if ($classLike->implements !== []) { |
| 56 | + return []; |
| 57 | + } |
| 58 | + |
| 59 | + if (! DoctrineEventSubscriberAnalyzer::detect($classLike)) { |
| 60 | + return []; |
| 61 | + } |
| 62 | + |
| 63 | + $identifierRuleError = RuleErrorBuilder::message(self::ERROR_MESSAGE) |
| 64 | + ->identifier(DoctrineRuleIdentifier::NO_LISTENER_WITHOUT_CONTRACT) |
| 65 | + ->build(); |
| 66 | + |
| 67 | + return [$identifierRuleError]; |
| 68 | + } |
| 69 | +} |
0 commit comments