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

InMemoryStateManager   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 37
c 0
b 0
f 0
ccs 16
cts 16
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A loadState() 0 10 2
A updateState() 0 10 1
A getStateClass() 0 10 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
}