Passed
Push — master ( efe3fd...6bd5d7 )
by Peter
06:06
created

YamlInlineChecker   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 86.36%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 20
c 1
b 0
f 0
dl 0
loc 49
ccs 19
cts 22
cp 0.8636
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A removeComments() 0 3 1
A check() 0 26 3
A removeCommentLine() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace YamlStandards\Model\YamlInline;
6
7
use SebastianBergmann\Diff\Differ;
8
use Symfony\Component\Yaml\Yaml;
9
use YamlStandards\Command\ProcessOutput;
10
use YamlStandards\Model\CheckerInterface;
11
use YamlStandards\Model\Component\YamlService;
12
use YamlStandards\Model\Config\StandardParametersData;
13
use YamlStandards\Result\Result;
14
15
/**
16
 * Check yaml file complies inline standards
17
 */
18
class YamlInlineChecker implements CheckerInterface
19
{
20
    /**
21
     * @inheritDoc
22
     */
23 3
    public function check(string $pathToYamlFile, StandardParametersData $standardParametersData): Result
24
    {
25 3
        $yamlArrayData = YamlService::getYamlData($pathToYamlFile);
26 3
        $yamlStringData = Yaml::dump($yamlArrayData, 3);
27
28 3
        $yamlContent = file_get_contents($pathToYamlFile);
29 3
        $yamlContent = str_replace("\r", '', $yamlContent); // remove carriage returns
30 3
        $yamlLines = explode("\n", $yamlContent);
31 3
        $lastYamlElement = end($yamlLines);
32 3
        $filteredYamlLines = array_filter($yamlLines, [YamlService::class, 'isLineNotBlank']);
33 3
        $filteredYamlLines = array_filter($filteredYamlLines, ['self', 'removeCommentLine']);
34 3
        $filteredYamlLines = array_map(['self', 'removeComments'], $filteredYamlLines);
35 3
        if (trim($lastYamlElement) === '') {
36 3
            $filteredYamlLines[] = '';
37
        }
38
39 3
        $filteredYamlFile = implode("\n", $filteredYamlLines);
40
41 3
        if ($yamlStringData === $filteredYamlFile) {
42 3
            return new Result($pathToYamlFile, Result::RESULT_CODE_OK, ProcessOutput::STATUS_CODE_OK);
43
        }
44
45
        $differ = new Differ();
46
        $diffBetweenStrings = $differ->diff($filteredYamlFile, $yamlStringData);
47
48
        return new Result($pathToYamlFile, Result::RESULT_CODE_INVALID_FILE_SYNTAX, ProcessOutput::STATUS_CODE_INVALID_FILE_SYNTAX, $diffBetweenStrings);
49
    }
50
51
    /**
52
     * @param string $yamlLine
53
     * @return bool
54
     */
55 3
    private function removeCommentLine(string $yamlLine): bool
56
    {
57 3
        return preg_match('/^\s*#/', $yamlLine) === 0;
58
    }
59
60
    /**
61
     * @param string $yamlLine
62
     * @return string
63
     */
64 3
    private function removeComments(string $yamlLine): string
65
    {
66 3
        return preg_replace('/\s#.+/', '', $yamlLine);
67
    }
68
}
69