|
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, string $namespace = 'global_namespace') |
|
14
|
|
|
{ |
|
15
|
3 |
|
$key = $stateClass . $stateId; |
|
16
|
|
|
|
|
17
|
3 |
|
if (isset($this->states[$namespace][$key])) { |
|
18
|
2 |
|
return $this->states[$namespace][$key]; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
3 |
|
return null; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
3 |
|
public function hasState(string $stateClass, $stateId, string $namespace) |
|
25
|
|
|
{ |
|
26
|
3 |
|
$key = $stateClass . $stateId; |
|
27
|
|
|
|
|
28
|
3 |
|
return isset($this->states[$namespace][$key]); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
4 |
|
public function updateState($stateId, callable $updater, string $namespace = 'global_namespace') |
|
32
|
|
|
{ |
|
33
|
4 |
|
list($stateClass, $isOptional) = $this->getStateClass($updater); |
|
34
|
|
|
|
|
35
|
3 |
|
$oldState = $this->loadState($stateClass, $stateId, $namespace); |
|
36
|
3 |
|
if (!$this->hasState($stateClass, $stateId, $namespace)) { |
|
37
|
3 |
|
if (!$isOptional) { |
|
38
|
1 |
|
$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[$namespace][$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(string $namespace = 'global_namespace') |
|
63
|
|
|
{ |
|
64
|
1 |
|
$this->states[$namespace] = []; |
|
65
|
1 |
|
} |
|
66
|
|
|
|
|
67
|
1 |
|
public function createStorage(string $namespace = 'global_namespace') |
|
68
|
|
|
{ |
|
69
|
1 |
|
$this->states[$namespace] = []; |
|
70
|
|
|
} |
|
71
|
|
|
} |