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

ProjectionTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 45
c 0
b 0
f 0
wmc 8
lcom 1
cbo 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A fromArray() 0 4 1
A getAggregateId() 0 4 1
A getAggregateRevision() 0 4 1
A toArray() 0 4 1
A applyEvent() 0 4 1
A invokeEventHandler() 0 10 2
A __construct() 0 4 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