AbstractAggregateRoot::executeEvent()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 19
rs 9.4285
cc 2
eloc 12
nc 2
nop 1
1
<?php
2
3
namespace PhpDDD\DomainDrivenDesign\Domain;
4
5
use PhpDDD\DomainDrivenDesign\Event\AbstractEvent;
6
use PhpDDD\DomainDrivenDesign\Exception\BadMethodCallException;
7
use PhpDDD\Utils\ClassUtils;
8
9
abstract class AbstractAggregateRoot
10
{
11
    /**
12
     * List of non published events.
13
     *
14
     * @var AbstractEvent[]
15
     */
16
    private $events = [];
17
18
    /**
19
     * Get the unique identifier of this aggregate root.
20
     *
21
     * @return mixed
22
     */
23
    abstract public function getId();
24
25
    public function pullEvents()
26
    {
27
        $events       = $this->events;
28
        $this->events = [];
29
30
        return $events;
31
    }
32
33
    /**
34
     * @param AbstractEvent $event
35
     */
36
    protected function apply(AbstractEvent $event)
37
    {
38
        $event->aggregateRoot = $this;
39
        $this->executeEvent($event);
40
        $this->events[] = $event;
41
    }
42
43
    /**
44
     * @param AbstractEvent $event
45
     *
46
     * @throws BadMethodCallException
47
     */
48
    private function executeEvent(AbstractEvent $event)
49
    {
50
        $eventName = ClassUtils::getShortName($event);
51
        $method    = sprintf('apply%s', (string) $eventName);
52
53
        if (!method_exists($this, $method)) {
54
            throw new BadMethodCallException(
55
                sprintf(
56
                    'You must define the %s::%s(%s $event) method in order to apply event named "%s".',
57
                    get_class($this),
58
                    $method,
59
                    get_class($event),
60
                    $eventName
61
                )
62
            );
63
        }
64
65
        $this->$method($event);
66
    }
67
}
68