Passed
Push — main ( ec2ade...f9de31 )
by mikhail
03:35
created

TreePhpBaselineStorage::addCommentToTree()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 9
c 1
b 1
f 0
dl 0
loc 13
ccs 10
cts 10
cp 1
rs 9.9666
cc 3
nc 4
nop 3
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SavinMikhail\CommentsDensity\Baseline\Storage;
6
7
final class TreePhpBaselineStorage implements BaselineStorageInterface
8
{
9
    private string $path;
10
    private array $baselineData = [];
11
12 5
    public function init(string $path): void
13
    {
14 5
        $this->path = $path;
15 5
        if (!file_exists($path)) {
16 5
            file_put_contents($path, "<?php return [];");
17
        }
18 5
        $this->baselineData = include $path;
19
    }
20
21 2
    public function setComments(array $comments): void
22
    {
23 2
        foreach ($comments as $comment) {
24 2
            $pathParts = explode(DIRECTORY_SEPARATOR, ltrim($comment->file, DIRECTORY_SEPARATOR));
25 2
            $this->addCommentToTree($this->baselineData, $pathParts, $comment);
26
        }
27 2
        file_put_contents($this->path, "<?php return " . var_export($this->baselineData, true) . ";");
28
    }
29
30 3
    private function addCommentToTree(array &$tree, array $pathParts, $comment): void
31
    {
32 3
        $currentPart = array_shift($pathParts);
33 3
        if (!isset($tree[$currentPart])) {
34 3
            $tree[$currentPart] = [];
35
        }
36 3
        if (empty($pathParts)) {
37 3
            $tree[$currentPart][$comment->line] = [
38 3
                'comment' => $comment->content,
39 3
                'type' => $comment->commentType,
40 3
            ];
41
        } else {
42 3
            $this->addCommentToTree($tree[$currentPart], $pathParts, $comment);
43
        }
44
    }
45
46 1
    public function filterComments(array $comments): array
47
    {
48 1
        $filteredComments = array_filter($comments, function ($comment): bool {
49 1
            $pathParts = explode(DIRECTORY_SEPARATOR, ltrim($comment['file'], DIRECTORY_SEPARATOR));
50 1
            return !$this->commentExistsInTree($this->baselineData, $pathParts, $comment['line']);
51 1
        });
52
53 1
        return array_values($filteredComments);
54
    }
55
56 2
    private function commentExistsInTree(array $tree, array $pathParts, int $line): bool
57
    {
58 2
        $currentPart = array_shift($pathParts);
59 2
        if (!isset($tree[$currentPart])) {
60 1
            return false;
61
        }
62 2
        if (empty($pathParts)) {
63 2
            return isset($tree[$currentPart][$line]);
64
        } else {
65 2
            return $this->commentExistsInTree($tree[$currentPart], $pathParts, $line);
66
        }
67
    }
68
}
69