QueryBus::handle()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 16
rs 9.9666
c 1
b 0
f 0
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\QueryReturnException;
17
use Gears\CQRS\Query;
18
use Gears\CQRS\QueryBus as QueryBusInterface;
19
use Gears\DTO\DTO;
20
use Symfony\Component\Messenger\Envelope;
21
use Symfony\Component\Messenger\MessageBusInterface;
22
use Symfony\Component\Messenger\Stamp\HandledStamp;
23
24
final class QueryBus implements QueryBusInterface
25
{
26
    /**
27
     * Wrapped command bus.
28
     *
29
     * @var MessageBusInterface
30
     */
31
    private $wrappedMessageBus;
32
33
    /**
34
     * QueryBus constructor.
35
     *
36
     * @param MessageBusInterface $wrappedMessageBus
37
     */
38
    public function __construct(MessageBusInterface $wrappedMessageBus)
39
    {
40
        $this->wrappedMessageBus = $wrappedMessageBus;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     *
46
     * @throws QueryReturnException
47
     */
48
    public function handle(Query $query): DTO
49
    {
50
        /** @var HandledStamp $handlerResult */
51
        $handlerResult = $this->wrappedMessageBus->dispatch(new Envelope($query))
52
            ->last(HandledStamp::class);
53
        $dto = $handlerResult->getResult();
54
55
        if (!$dto instanceof DTO) {
56
            throw new QueryReturnException(\sprintf(
57
                'Query handler for %s should return an instance of %s',
58
                \get_class($query),
59
                DTO::class
60
            ));
61
        }
62
63
        return $dto;
64
    }
65
}
66