|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace CakeDC\PHPStan\Visitor; |
| 5 | + |
| 6 | +use CakeDC\PHPStan\Rule\Traits\ParseClassNameFromArgTrait; |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr; |
| 9 | +use PhpParser\Node\Expr\MethodCall; |
| 10 | +use PhpParser\NodeVisitorAbstract; |
| 11 | + |
| 12 | +class AddAssociationSetClassNameVisitor extends NodeVisitorAbstract |
| 13 | +{ |
| 14 | + use ParseClassNameFromArgTrait; |
| 15 | + |
| 16 | + public const ATTRIBUTE_NAME = 'addAssociationVisitorOptions'; |
| 17 | + |
| 18 | + /** |
| 19 | + * @param \PhpParser\Node\Expr|null $optionsSet |
| 20 | + */ |
| 21 | + public function __construct(protected ?Expr $optionsSet = null) |
| 22 | + { |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @param array<\PhpParser\Node> $nodes |
| 27 | + * @return array<\PhpParser\Node>|null |
| 28 | + */ |
| 29 | + public function beforeTraverse(array $nodes): ?array |
| 30 | + { |
| 31 | + $this->optionsSet = null; |
| 32 | + |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param \PhpParser\Node $node |
| 38 | + * @return \PhpParser\Node|null |
| 39 | + */ |
| 40 | + public function enterNode(Node $node): ?Node |
| 41 | + { |
| 42 | + if (!$node instanceof MethodCall || !$node->name instanceof Node\Identifier) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + if ($this->optionsSet === null && $node->name->name === 'setClassName') { |
| 46 | + $this->optionsSet = $node->args[0]->value ?? null; |
| 47 | + } |
| 48 | + if (in_array($node->name->name, ['load', 'belongsTo', 'belongsToMany', 'hasOne', 'hasMany'])) { |
| 49 | + $node->setAttribute(self::ATTRIBUTE_NAME, $this->optionsSet); |
| 50 | + } |
| 51 | + |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @inheritDoc |
| 57 | + */ |
| 58 | + public function leaveNode(Node $node) |
| 59 | + { |
| 60 | + $this->optionsSet = null; |
| 61 | + |
| 62 | + return null; |
| 63 | + } |
| 64 | +} |
0 commit comments