Passed
Push — main ( 28fe2f...804823 )
by mikhail
03:26
created

ComToLoc::prepareComToLoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 5
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SavinMikhail\CommentsDensity\Metrics;
6
7
use SavinMikhail\CommentsDensity\DTO\Output\ComToLocDTO;
0 ignored issues
show
Bug introduced by
The type SavinMikhail\CommentsDen...\DTO\Output\ComToLocDTO was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
use function array_sum;
10
use function round;
11
12
final class ComToLoc
13
{
14
    private bool $exceedThreshold = false;
15
16
    public function __construct(private readonly array $thresholds)
17
    {
18
    }
19
20
    public function prepareComToLoc(array $commentStatistics, int $linesOfCode): ComToLocDTO
21
    {
22
        $ratio = $this->getRatio($commentStatistics, $linesOfCode);
23
        return new ComToLocDTO(
24
            $ratio,
25
            $this->getColorForRatio($ratio)
26
        );
27
    }
28
29
    public function hasExceededThreshold(): bool
30
    {
31
        return $this->exceedThreshold;
32
    }
33
34
    private function getRatio(array $commentStatistics, int $linesOfCode): float
35
    {
36
        if ($linesOfCode === 0) {
37
            return 0;
38
        }
39
40
        $totalComments = 0;
41
42
        foreach ($commentStatistics as $stat) {
43
            $totalComments += $stat['lines'];
44
        }
45
46
        return round($totalComments / $linesOfCode, 2);
47
    }
48
49
    private function getColorForRatio(float $ratio): string
50
    {
51
        if (! isset($this->thresholds['Com/LoC'])) {
52
            return 'white';
53
        }
54
        if ($ratio >= $this->thresholds['Com/LoC']) {
55
            return 'green';
56
        }
57
        $this->exceedThreshold = true;
58
        return 'red';
59
    }
60
}
61