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

YamlInlineChecker::removeComments()   A

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 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