YamlInlineChecker::removeComments()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace YamlStandards\Model\YamlInline;
6
7
use SebastianBergmann\Diff\Differ;
8
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
9
use Symfony\Component\Yaml\Yaml;
10
use YamlStandards\Model\AbstractChecker;
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 extends AbstractChecker
19
{
20
    /**
21
     * @inheritDoc
22
     */
23 5
    public function check(string $pathToFile, StandardParametersData $standardParametersData): Result
24
    {
25 5
        $yamlArrayData = YamlService::getYamlData($pathToFile);
26 5
        $yamlStringData = Yaml::dump($yamlArrayData, 3);
27
28 5
        $yamlContent = file_get_contents($pathToFile);
29 5
        $yamlContent = str_replace("\r", '', $yamlContent); // remove carriage returns
30 5
        $yamlLines = explode("\n", $yamlContent);
31 5
        $lastYamlElement = end($yamlLines);
32 5
        $filteredYamlLines = array_filter($yamlLines, [YamlService::class, 'isLineNotBlank']);
33 5
        $filteredYamlLines = array_filter($filteredYamlLines, [__CLASS__, 'removeCommentLine']);
34 5
        $filteredYamlLines = array_map([__CLASS__, 'removeComments'], $filteredYamlLines);
35 5
        if (YamlService::isLineBlank($lastYamlElement)) {
36 5
            $filteredYamlLines[] = '';
37
        }
38
39 5
        $filteredYamlFile = implode("\n", $filteredYamlLines);
40
41 5
        if ($yamlStringData === $filteredYamlFile) {
42 4
            return new Result($pathToFile, Result::RESULT_CODE_OK);
43
        }
44
45 1
        $differ = new Differ(new UnifiedDiffOutputBuilder());
46 1
        $diffBetweenStrings = $differ->diff($filteredYamlFile, $yamlStringData);
47
48 1
        return new Result($pathToFile, Result::RESULT_CODE_INVALID_FILE_SYNTAX, $diffBetweenStrings);
49
    }
50
51
    /**
52
     * @param string $yamlLine
53
     * @return bool
54
     */
55 5
    private function removeCommentLine(string $yamlLine): bool
56
    {
57 5
        return preg_match('/^\s*#/', $yamlLine) === 0;
58
    }
59
60
    /**
61
     * @param string $yamlLine
62
     * @return string
63
     */
64 5
    private function removeComments(string $yamlLine): string
65
    {
66 5
        return preg_replace('/\s#.+/', '', $yamlLine);
67
    }
68
}
69