EventHandlerTrait::applyEvent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 2
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of the daikon-cqrs/read-model project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Daikon\ReadModel\Projection;
10
11
use Daikon\EventSourcing\Aggregate\Event\DomainEventInterface;
12
use Daikon\Interop\RuntimeException;
13
use ReflectionClass;
14
15
trait EventHandlerTrait
16
{
17
    /** @return static */
18
    public function applyEvent(DomainEventInterface $event): self
19
    {
20
        $projection = clone $this;
21
        return $projection->invokeEventHandler($event);
22
    }
23
24
    protected function invokeEventHandler(DomainEventInterface $event): self
25
    {
26
        $handlerName = (new ReflectionClass($event))->getShortName();
27
        $handlerMethod = 'when'.ucfirst($handlerName);
28
        $handler = [$this, $handlerMethod];
29
        if (!is_callable($handler)) {
30
            throw new RuntimeException(
31
                sprintf("Handler '%s' is not callable on '%s'.", $handlerMethod, static::class)
32
            );
33
        }
34
        return $handler($event);
35
    }
36
}
37