Completed
Pull Request — master (#16)
by Frank
02:46
created

DelegatingUpcaster   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 43
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A upcaster() 0 12 3
A upcast() 0 10 3
A canUpcast() 0 4 1
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
}