Completed
Push — master ( 16dc65...74e1a0 )
by Constantin
14:10
created

InMemoryStateManager::createStorage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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 2
    public function loadState(string $stateClass, $stateId)
14
    {
15 2
        $key = $stateClass . $stateId;
16
17 2
        if (isset($this->states[$key])) {
18 1
            return $this->states[$key];
19
        }
20
21 2
        return new $stateClass;
22
    }
23
24 3
    public function updateState($stateId, callable $updater)
25
    {
26 3
        $stateClass = $this->getStateClass($updater);
27
28 2
        $state = call_user_func($updater, $this->loadState($stateClass, $stateId));
29
30 2
        $key = $stateClass . $stateId;
31
32 2
        $this->states[$key] = $state;
33 2
    }
34
35 3
    private function getStateClass(callable $update): string
36
    {
37 3
        $reflection = new \ReflectionFunction($update);
38
39 3
        if ($reflection->getNumberOfParameters() <= 0) {
40 1
            throw new \Exception("Updater callback must have one type-hinted parameter");
41
        }
42
43 2
        return $reflection->getParameters()[0]->getClass()->name;
44
    }
45
46 1
    public function clearAllStates()
47
    {
48 1
        $this->states = [];
49 1
    }
50
51 1
    public function createStorage()
52
    {
53 1
        $this->states = [];
54
    }
55
}