AbstractFactory::addLoader()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

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
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Finite\Factory;
4
5
use Finite\Loader\LoaderInterface;
6
use Finite\StateMachine\StateMachineInterface;
7
8
/**
9
 * The abstract base class for state machine factories.
10
 *
11
 * @author Yohan Giarelli <[email protected]>
12
 */
13
abstract class AbstractFactory implements FactoryInterface
14
{
15
    /**
16
     * @var StateMachineInterface[]
17
     */
18
    protected $stateMachines = array();
19
20
    /**
21
     * @var LoaderInterface[]
22
     */
23
    protected $loaders = array();
24
25
    /**
26
     * {@inheritdoc}
27
     */
28 70
    public function get($object, $graph = 'default')
29
    {
30 70
        $hash = spl_object_hash($object).'.'.$graph;
31 70
        if (!isset($this->stateMachines[$hash])) {
32 70
            $stateMachine = $this->createStateMachine();
33 70
            if (null !== ($loader = $this->getLoader($object, $graph))) {
34 5
                $loader->load($stateMachine);
35 3
            }
36 70
            $stateMachine->setObject($object);
37 70
            $stateMachine->initialize();
38
39 70
            $this->stateMachines[$hash] = $stateMachine;
40 42
        }
41
42 70
        return $this->stateMachines[$hash];
43
    }
44
45
    /**
46
     * @param LoaderInterface $loader
47
     */
48 5
    public function addLoader(LoaderInterface $loader)
49
    {
50 5
        $this->loaders[] = $loader;
51 5
    }
52
53
    /**
54
     * @param object $object
55
     * @param string $graph
56
     *
57
     * @return LoaderInterface|null
58
     */
59 70
    protected function getLoader($object, $graph)
60
    {
61 70
        foreach ($this->loaders as $loader) {
62 5
            if ($loader->supports($object, $graph)) {
63 5
                return $loader;
64
            }
65 42
        }
66
67 65
        return;
68
    }
69
70
    /**
71
     * Creates an instance of StateMachine.
72
     *
73
     * @return StateMachineInterface
74
     */
75
    abstract protected function createStateMachine();
76
}
77