|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* cqrs-symfony-messenger (https://github.com/phpgears/cqrs-symfony-messenger). |
|
5
|
|
|
* CQRS implementation with Symfony's Messenger. |
|
6
|
|
|
* |
|
7
|
|
|
* @license MIT |
|
8
|
|
|
* @link https://github.com/phpgears/cqrs-symfony-messenger |
|
9
|
|
|
* @author Julián Gutiérrez <[email protected]> |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Gears\CQRS\Symfony\Messenger; |
|
15
|
|
|
|
|
16
|
|
|
use Gears\CQRS\Exception\InvalidQueryHandlerException; |
|
17
|
|
|
use Gears\CQRS\Query; |
|
18
|
|
|
use Gears\CQRS\QueryHandler; |
|
19
|
|
|
use Psr\Container\ContainerInterface; |
|
20
|
|
|
use Symfony\Component\Messenger\Envelope; |
|
21
|
|
|
use Symfony\Component\Messenger\Handler\HandlerDescriptor; |
|
22
|
|
|
|
|
23
|
|
|
class ContainerAwareQueryHandlerLocator extends QueryHandlerLocator |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* PSR container. |
|
27
|
|
|
* |
|
28
|
|
|
* @var ContainerInterface |
|
29
|
|
|
*/ |
|
30
|
|
|
private $container; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* ContainerAwareCommandHandlerLocator constructor. |
|
34
|
|
|
* |
|
35
|
|
|
* @param ContainerInterface $container |
|
36
|
|
|
* @param mixed[] $handlers |
|
37
|
|
|
*/ |
|
38
|
|
|
public function __construct(ContainerInterface $container, array $handlers) |
|
39
|
|
|
{ |
|
40
|
|
|
$this->container = $container; |
|
41
|
|
|
|
|
42
|
|
|
parent::__construct($handlers); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* {@inheritdoc} |
|
47
|
|
|
* |
|
48
|
|
|
* @throws InvalidQueryHandlerException |
|
49
|
|
|
*/ |
|
50
|
|
|
public function getHandlers(Envelope $envelope): iterable |
|
51
|
|
|
{ |
|
52
|
|
|
$seen = []; |
|
53
|
|
|
|
|
54
|
|
|
foreach ($this->getQueryMap($envelope) as $type) { |
|
55
|
|
|
foreach ($this->handlersMap[$type] ?? [] as $alias => $handler) { |
|
56
|
|
|
$handler = $this->container->get($handler); |
|
57
|
|
|
|
|
58
|
|
|
if (!$handler instanceof QueryHandler) { |
|
59
|
|
|
throw new InvalidQueryHandlerException(\sprintf( |
|
60
|
|
|
'Query handler must implement %s interface, %s given', |
|
61
|
|
|
QueryHandler::class, |
|
62
|
|
|
\is_object($handler) ? \get_class($handler) : \gettype($handler) |
|
63
|
|
|
)); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$handlerCallable = function (Query $query) use ($handler) { |
|
67
|
|
|
return $handler->handle($query); |
|
68
|
|
|
}; |
|
69
|
|
|
|
|
70
|
|
|
if (!\in_array($handlerCallable, $seen, true)) { |
|
71
|
|
|
$seen[] = $handlerCallable; |
|
72
|
|
|
|
|
73
|
|
|
yield $alias => new HandlerDescriptor($handlerCallable); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|