|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Mkusher\PadawanDi; |
| 4 | + |
| 5 | +use Symfony\Component\EventDispatcher\EventDispatcher; |
| 6 | +use Complete\Resolver\NodeTypeResolver; |
| 7 | +use Complete\Resolver\TypeResolveEvent; |
| 8 | +use Entity\FQCN; |
| 9 | +use PhpParser\Node\Arg; |
| 10 | +use PhpParser\Node\Scalar\String_; |
| 11 | +use Parser\UseParser; |
| 12 | + |
| 13 | +class Plugin |
| 14 | +{ |
| 15 | + public function __construct( |
| 16 | + EventDispatcher $dispatcher, |
| 17 | + UseParser $useParser |
| 18 | + ) { |
| 19 | + $this->dispatcher = $dispatcher; |
| 20 | + $this->useParser = $useParser; |
| 21 | + } |
| 22 | + |
| 23 | + public function load() |
| 24 | + { |
| 25 | + if ($this->isLoaded) { |
| 26 | + return; |
| 27 | + } |
| 28 | + $this->isLoaded = true; |
| 29 | + $plugin = $this; |
| 30 | + $this->dispatcher->addListener( |
| 31 | + NodeTypeResolver::BLOCK_START, |
| 32 | + function (TypeResolveEvent $e) use ($plugin) { |
| 33 | + $plugin->parentType = $e->getType(); |
| 34 | + } |
| 35 | + ); |
| 36 | + $this->dispatcher->addListener( |
| 37 | + NodeTypeResolver::BLOCK_END, |
| 38 | + function (TypeResolveEvent $e) use ($plugin) { |
| 39 | + $parentType = $plugin->parentType; |
| 40 | + if ($parentType instanceof FQCN |
| 41 | + && $parentType->toString() === 'DI\\Container' |
| 42 | + ) { |
| 43 | + /** @var \Entity\Chain\MethodCall */ |
| 44 | + $chain = $e->getChain(); |
| 45 | + if ($chain->getType() === 'method' && count($chain->getArgs()) > 0) { |
| 46 | + $firstArg = array_pop($chain->getArgs())->value; |
| 47 | + if ($firstArg instanceof String_) { |
| 48 | + $className = $firstArg->value; |
| 49 | + $fqcn = $plugin->useParser->parseFQCN($className); |
| 50 | + $e->setType($fqcn); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + private $parentType; |
| 59 | + /** @var EventDispatcher */ |
| 60 | + private $dispatcher; |
| 61 | + private $useParser; |
| 62 | + private $isLoaded = false; |
| 63 | +} |
0 commit comments