Graph::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace JMGQ\AStar\Example\Graph;
4
5
class Graph
6
{
7
    /** @var Link[] */
8
    private array $links = [];
9
10
    /**
11
     * @param Link[] $links
12
     */
13 15
    public function __construct(iterable $links = [])
14
    {
15 15
        foreach ($links as $link) {
16 11
            $this->addLink($link);
17
        }
18 15
    }
19
20 14
    public function addLink(Link $link): void
21
    {
22 14
        $linkId = $this->getLinkId($link->getSource(), $link->getDestination());
23
24 14
        $this->links[$linkId] = $link;
25 14
    }
26
27 8
    public function getLink(Coordinate $source, Coordinate $destination): ?Link
28
    {
29 8
        if ($this->hasLink($source, $destination)) {
30 8
            $linkId = $this->getLinkId($source, $destination);
31
32 8
            return $this->links[$linkId];
33
        }
34
35 3
        return null;
36
    }
37
38 9
    public function hasLink(Coordinate $source, Coordinate $destination): bool
39
    {
40 9
        $linkId = $this->getLinkId($source, $destination);
41
42 9
        return isset($this->links[$linkId]);
43
    }
44
45
    /**
46
     * @param Coordinate $node
47
     * @return Coordinate[]
48
     */
49 5
    public function getDirectSuccessors(Coordinate $node): array
50
    {
51 5
        $successors = [];
52
53 5
        foreach ($this->links as $link) {
54 4
            if ($node->getId() === $link->getSource()->getId()) {
55 4
                $successors[] = $link->getDestination();
56
            }
57
        }
58
59 5
        return $successors;
60
    }
61
62 14
    private function getLinkId(Coordinate $source, Coordinate $destination): string
63
    {
64 14
        return $source->getId() . '|' . $destination->getId();
65
    }
66
}
67