Test Failed
Push — master ( deb397...eab8d5 )
by Mr
01:40
created

ProjectionTrait::invokeEventHandler()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
3
namespace Daikon\Dbal\Projection;
4
5
use Daikon\Cqrs\Aggregate\DomainEventInterface;
6
use Daikon\Dbal\Exception\DbalException;
7
8
trait ProjectionTrait
9
{
10
    private $state;
11
12
    public static function fromArray(array $state = [])
13
    {
14
        return new self($state);
15
    }
16
17
    public function getAggregateId(): string
18
    {
19
        return $this->state['aggregateId'];
20
    }
21
22
    public function getAggregateRevision(): int
23
    {
24
        return $this->state['aggregateRevision'];
25
    }
26
27
    public function toArray(): array
28
    {
29
        return $this->state;
30
    }
31
32
    public function applyEvent(DomainEventInterface $domainEvent): ProjectionInterface
33
    {
34
        return $this->invokeEventHandler($domainEvent);
35
    }
36
37
    private function invokeEventHandler(DomainEventInterface $event): ProjectionInterface
38
    {
39
        $handlerName = preg_replace('/Event$/', '', (new \ReflectionClass($event))->getShortName());
40
        $handlerMethod = 'when'.ucfirst($handlerName);
41
        $handler = [$this, $handlerMethod];
42
        if (!is_callable($handler)) {
43
            throw new DbalException("Handler '$handlerMethod' is not callable on ".self::class);
44
        }
45
        return call_user_func($handler, $event);
46
    }
47
48
    private function __construct(array $state = [])
49
    {
50
        $this->state = $state;
51
    }
52
}
53