Passed
Pull Request — master (#84)
by Frank
10:46 queued 47s
created

AggregateAppliesKnownEvents   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 16
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 9
c 1
b 0
f 1
dl 0
loc 16
rs 10
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A apply() 0 12 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing;
6
7
/**
8
 * This trait calls the apply[EventClassName] method
9
 * only for the events it has an apply function for.
10
 * Use this trait when you have many events that you
11
 * do not have an apply method for. This is common
12
 * for when you record many events for analytics.
13
 */
14
trait AggregateAppliesKnownEvents
15
{
16
    private int $aggregateRootVersion = 0;
17
18
    public function apply(object $event): void
19
    {
20
        static $hasMethodCache = [];
21
        $parts = explode('\\', get_class($event));
22
        $methodName = 'apply' . end($parts);
23
        $shouldApply = $hasMethodCache[$methodName] ?? method_exists($this, $methodName);
24
25
        if ($shouldApply) {
26
            $this->{$methodName}($event);
27
        }
28
29
        ++$this->aggregateRootVersion;
30
    }
31
}
32