Completed
Push — master ( ec3450...26ba82 )
by Hugues
45:59 queued 33:02
created

MonitorsDomainEvents::handle()   A

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
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 2
eloc 9
nc 2
nop 2
1
<?php
2
3
namespace HMLB\DDDBundle\MessageBus\Middleware;
4
5
use HMLB\DDD\Exception\Exception;
6
use HMLB\DDDBundle\EventListener\CollectsEventsFromEntities;
7
use Psr\Log\LoggerInterface;
8
use SimpleBus\Message\Bus\Middleware\MessageBusMiddleware;
9
10
/**
11
 * This subscribers throws an exception if DomainEvents have been collected and will not be notified.
12
 *
13
 * It should have High priority to check for Events after all Notifiers like "NotifiesDomainEvents" have been called.
14
 *
15
 * @author Hugues Maignol <[email protected]>
16
 */
17
class MonitorsDomainEvents implements MessageBusMiddleware
18
{
19
    /**
20
     * @var CollectsEventsFromEntities
21
     */
22
    private $collectsEventsFromEntities;
23
24
    /**
25
     * @var LoggerInterface
26
     */
27
    private $logger;
28
29
    /**
30
     * @param LoggerInterface            $logger
31
     * @param CollectsEventsFromEntities $collectsEventsFromEntities
32
     */
33
    public function __construct(
34
        LoggerInterface $logger,
35
        CollectsEventsFromEntities $collectsEventsFromEntities
36
    ) {
37
        $this->logger = $logger;
38
        $this->collectsEventsFromEntities = $collectsEventsFromEntities;
39
    }
40
41
    /**
42
     * @param object   $message
43
     * @param callable $next
44
     *
45
     * @throws Exception
46
     */
47
    public function handle($message, callable $next)
48
    {
49
        $next($message);
50
        $events = $this->collectsEventsFromEntities->recordedMessages();
51
        $count = count($events);
52
        $this->logger->debug('MonitorsDomainEvents saw '.$count.' events');
53
54
        if ($count) {
55
            throw new Exception(
56
                sprintf(
57
                    '%s Domain Events have been collected but will not be notified.
58
                    You should not raise domain event during the handling of a Event message but only for a Command.'
59
                )
60
            );
61
        }
62
    }
63
}
64