Passed
Push — master ( 95c142...58f956 )
by Beau
02:43
created

GraphCollection::for()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 9.9
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dflydev\FiniteStateMachine\Graph;
6
7
class GraphCollection
8
{
9
    /**
10
     * @var array<int, Graph>
11
     */
12
    private array $graphs = [];
13
14
    /**
15
     * @var array<string, array<string, Graph>>
16
     */
17
    private array $graphsByName = [];
18
19 21
    public function __construct(Graph ...$graphs)
20
    {
21 21
        foreach ($graphs as $graph) {
22
            $this->add($graph);
23
        }
24 21
    }
25
26 21
    public function add(Graph $graph): void
27
    {
28 21
        $this->graphs[] = $graph;
29
30 21
        if (!array_key_exists($graph->className(), $this->graphsByName)) {
31 21
            $this->graphsByName[$graph->className()] = [];
32
        }
33
34 21
        $this->graphsByName[$graph->className()][$graph->graph()] = $graph;
35 21
    }
36
37 21
    public function for(object $object, string $graph = 'default'): Graph
38
    {
39 21
        $className = get_class($object);
40
41 21
        foreach ($this->graphsByName as $classNameForGraph => $graphs) {
42 21
            if (! $object instanceof $classNameForGraph) {
43 1
                continue;
44
            }
45
46 20
            if (isset($graphs[$graph])) {
47 19
                return $graphs[$graph];
48
            }
49
        }
50
51 2
        throw new \RuntimeException(sprintf(
52 2
            'No graph named "%s" for class named "%s"',
53
            $graph,
54
            $className
55
        ));
56
    }
57
}
58