Passed
Pull Request — master (#16)
by Frank
02:29
created

DelegatingUpcaster::upcaster()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3
1
<?php
2
3
namespace EventSauce\EventSourcing\Upcasting;
4
5
use EventSauce\EventSourcing\Header;
6
use Generator;
7
8
final class DelegatingUpcaster implements Upcaster
9
{
10
    /**
11
     * @var DelegatableUpcaster[][]
12
     */
13
    private $upcasters;
14
15 3
    public function __construct(DelegatableUpcaster ... $upcasters)
16
    {
17 3
        foreach ($upcasters as $upcaster) {
18 2
            $this->upcasters[$upcaster->type()][] = $upcaster;
19
        }
20 3
    }
21
22 1
    public function upcaster(array $payload): ?Upcaster
23
    {
24 1
        $type = $payload['headers'][Header::EVENT_TYPE];
25
26 1
        foreach ($this->upcasters[$type] ?? [] as $upcaster) {
27 1
            if ($upcaster->canUpcast($type, $payload)) {
28 1
                return $upcaster;
29
            }
30
        }
31
32 1
        return null;
33
    }
34
35 1
    public function upcast(array $payload): Generator
36
    {
37 1
        if ($upcaster = $this->upcaster($payload)) {
38 1
            foreach ($upcaster->upcast($payload) as $upcasted) {
39 1
                yield from $this->upcast($upcasted);
40
            }
41
        } else {
42 1
            yield $payload;
43
        }
44 1
    }
45
46 2
    public function canUpcast(string $type, array $payload): bool
47
    {
48 2
        return isset($this->upcasters[$type]);
49
    }
50
}