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

InMemoryStateManager::hasState()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 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
}