Completed
Push — master ( d038b0...9c4c41 )
by Constantin
03:11
created

InMemoryStateManager::loadState()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
/**
3
 * Copyright (c) 2017 Constantin Galbenu <[email protected]>
4
 */
5
6
namespace Gica\Cqrs\Saga\State;
7
8
9
class InMemoryStateManager implements ProcessStateLoader, ProcessStateUpdater
10
{
11
    private $states = [];
12
13 1
    public function loadState(string $stateClass, $stateId)
14
    {
15 1
        $key = $stateClass . $stateId;
16
17 1
        if (isset($this->states[$key])) {
18 1
            return $this->states[$key];
19
        }
20
21 1
        return new $stateClass;
22
    }
23
24 2
    public function updateState($stateId, callable $updater)
25
    {
26 2
        $stateClass = $this->getStateClass($updater);
27
28 1
        $state = call_user_func($updater, $this->loadState($stateClass, $stateId));
29
30 1
        $key = $stateClass . $stateId;
31
32 1
        $this->states[$key] = $state;
33 1
    }
34
35 2
    private function getStateClass(callable $update): string
36
    {
37 2
        $reflection = new \ReflectionFunction($update);
38
39 2
        if ($reflection->getNumberOfParameters() <= 0) {
40 1
            throw new \Exception("Updater callback must have one type-hinted parameter");
41
        }
42
43 1
        return $reflection->getParameters()[0]->getClass()->name;
44
    }
45
}