-
Notifications
You must be signed in to change notification settings - Fork 74
/
AbstractFactory.php
104 lines (89 loc) · 2.6 KB
/
AbstractFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/*
* This file is part of the StateMachine package.
*
* (c) Alexandre Bacco
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SM\Factory;
use SM\SMException;
use SM\StateMachine\StateMachineInterface;
abstract class AbstractFactory implements ClearableFactoryInterface
{
/** @var array */
protected $configs = [];
/** @var StateMachineInterface[] */
protected $stateMachines = [];
/**
* @param array $configs Array of configs for the available state machines
*
* @throws SMException
*/
public function __construct(array $configs)
{
foreach ($configs as $graph => $config) {
$this->addConfig($config, $graph);
}
}
/**
* {@inheritDoc}
*/
public function get($object, string $graph = 'default'): StateMachineInterface
{
$hash = spl_object_hash($object);
if (isset($this->stateMachines[$hash][$graph])) {
return $this->stateMachines[$hash][$graph];
}
foreach ($this->configs as $config) {
if ($config['graph'] === $graph && $object instanceof $config['class']) {
return $this->stateMachines[$hash][$graph] = $this->createStateMachine($object, $config);
}
}
throw new SMException(sprintf(
'Cannot create a state machine because the configuration for object "%s" with graph "%s" does not exist.',
get_class($object),
$graph
));
}
/**
* {@inheritDoc}
*/
public function clear(): void
{
$this->stateMachines = array();
}
/**
* Adds a new config
*
* @param array $config
* @param string $graph
*
* @throws SMException If the index "class" is not configured
*/
public function addConfig(array $config, string $graph = 'default'): void
{
if (!isset($config['graph'])) {
$config['graph'] = $graph;
}
if (!isset($config['class'])) {
throw new SMException(sprintf(
'Index "class" needed for the state machine configuration of graph "%s"',
$config['graph']
));
}
$this->configs[] = $config;
}
/**
* Create a state machine for the given object and config
*
* @param $object
* @param array $config
*
* @return StateMachineInterface
*
* @throws SMException
*/
abstract protected function createStateMachine($object, array $config): StateMachineInterface;
}