Passed
Push — master ( 74e1a0...bfb274 )
by Constantin
02:59
created

InMemoryStateManager   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 63
ccs 30
cts 30
cp 1
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A loadState() 0 10 2
A hasState() 0 6 1
A updateState() 0 17 3
A getStateClass() 0 12 2
A clearAllStates() 0 4 1
A createStorage() 0 4 1
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 3
    public function loadState(string $stateClass, $stateId)
14
    {
15 3
        $key = $stateClass . $stateId;
16
17 3
        if (isset($this->states[$key])) {
18 2
            return $this->states[$key];
19
        }
20
21 3
        return null;
22
    }
23
24 3
    public function hasState(string $stateClass, $stateId)
25
    {
26 3
        $key = $stateClass . $stateId;
27
28 3
        return isset($this->states[$key]);
29
    }
30
31 4
    public function updateState($stateId, callable $updater)
32
    {
33 4
        list($stateClass, $isOptional) = $this->getStateClass($updater);
34
35 3
        $oldState = $this->loadState($stateClass, $stateId);
36 3
        if (!$this->hasState($stateClass, $stateId)) {
37 3
            if (!$isOptional) {
38 2
                $oldState = new $stateClass;
39
            }
40
        }
41
42 3
        $newState = call_user_func($updater, $oldState);
43
44 3
        $key = $stateClass . $stateId;
45
46 3
        $this->states[$key] = $newState;
47 3
    }
48
49 4
    private function getStateClass(callable $update)
50
    {
51 4
        $reflection = new \ReflectionFunction($update);
52
53 4
        if ($reflection->getNumberOfParameters() <= 0) {
54 1
            throw new \Exception("Updater callback must have one type-hinted parameter");
55
        }
56
57 3
        $parameter = $reflection->getParameters()[0];
58
59 3
        return [$parameter->getClass()->name, $parameter->isOptional()];
60
    }
61
62 1
    public function clearAllStates()
63
    {
64 1
        $this->states = [];
65 1
    }
66
67 1
    public function createStorage()
68
    {
69 1
        $this->states = [];
70
    }
71
}