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

GraphCollection   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

Changes 0
Metric Value
wmc 8
eloc 20
dl 0
loc 48
ccs 18
cts 19
cp 0.9474
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 9 2
A __construct() 0 4 2
A for() 0 18 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