Ranking   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 69
ccs 33
cts 33
cp 1
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A calculateRankPerIteration() 0 20 3
A calculateRank() 0 26 3
A __construct() 0 6 1
A calculateInitialRank() 0 5 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpScience\PageRank\Service\PageRankAlgorithm;
6
7
use PhpScience\PageRank\Data\NodeCollectionInterface;
8
use PhpScience\PageRank\Strategy\NodeDataSourceStrategyInterface;
9
10 1
class Ranking implements RankingInterface
11
{
12
    private NodeDataSourceStrategyInterface $nodeDataStrategy;
13
    private RankComparatorInterface         $rankComparator;
14
15 6
    public function __construct(
16
        RankComparatorInterface $rankComparator,
17
        NodeDataSourceStrategyInterface $nodeDataStrategy
18
    ) {
19 6
        $this->nodeDataStrategy = $nodeDataStrategy;
20 6
        $this->rankComparator = $rankComparator;
21 6
    }
22
23 3
    public function calculateInitialRank(
24
        NodeCollectionInterface $nodeCollection
25
    ): void {
26 3
        foreach ($nodeCollection->getNodes() as $item) {
27 3
            $item->setRank(1 / $nodeCollection->getAllNodeCount());
28
        }
29 3
    }
30
31 5
    public function calculateRankPerIteration(
32
        NodeCollectionInterface $nodeCollection
33
    ): int {
34 5
        $nonRepresentableDifference = 0;
35
36 5
        foreach ($nodeCollection->getNodes() as $node) {
37 5
            $rank = $this->calculateRank($node->getId());
38 5
            $node->setRank($rank);
39
40 5
            $isEqual = $this->rankComparator->isEqual(
41 5
                $this->nodeDataStrategy->getPreviousRank($node->getId()),
42 5
                $node->getRank()
43
            );
44
45 5
            if ($isEqual) {
46 4
                $nonRepresentableDifference++;
47
            }
48
        }
49
50 5
        return $nonRepresentableDifference;
51
    }
52
53 5
    private function calculateRank(int $nodeId): float
54
    {
55 5
        $rank = .0;
56
57
        $incomingNodeIds = $this
58 5
            ->nodeDataStrategy
59 5
            ->getIncomingNodeIds($nodeId);
60
61 5
        foreach ($incomingNodeIds as $incomingNodeId) {
62
            $incomingNodePreviousRank = $this
63 5
                ->nodeDataStrategy
64 5
                ->getPreviousRank($incomingNodeId);
65
66
            $countOutgoingNodesOfIncomingNode = $this
67 5
                ->nodeDataStrategy
68 5
                ->countOutgoingNodes($incomingNodeId);
69
70 5
            if (0 === $countOutgoingNodesOfIncomingNode) {
71 2
                continue;
72
            }
73
74
            $rank += $incomingNodePreviousRank
75 3
                / $countOutgoingNodesOfIncomingNode;
76
        }
77
78 5
        return $rank;
79
    }
80
}
81