Test Failed
Push — master ( 6bd5d7...53c755 )
by Peter
05:13
created

YamlEmptyLineAtEndChecker::check()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
c 2
b 0
f 0
dl 0
loc 27
rs 9.7333
cc 4
nc 6
nop 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace YamlStandards\Model\YamlEmptyLineAtEnd;
6
7
use SebastianBergmann\Diff\Differ;
8
use YamlStandards\Command\ProcessOutput;
9
use YamlStandards\Model\CheckerInterface;
10
use YamlStandards\Model\Component\YamlService;
11
use YamlStandards\Model\Config\StandardParametersData;
12
use YamlStandards\Result\Result;
13
14
/**
15
 * Check yaml file has empty line at end of file
16
 */
17
class YamlEmptyLineAtEndChecker implements CheckerInterface
18
{
19
    /**
20
     * @inheritDoc
21
     */
22
    public function check(string $pathToYamlFile, StandardParametersData $standardParametersData): Result
23
    {
24
        $yamlContent = file_get_contents($pathToYamlFile);
25
        $yamlContent = str_replace("\r", '', $yamlContent); // remove carriage returns
26
        $yamlLines = explode("\n", $yamlContent);
27
        $reversedYamlLines = array_reverse($yamlLines);
28
29
        foreach ($reversedYamlLines as $key => $yamlLine) {
30
            if (trim($yamlLine) === '') {
31
                continue;
32
            }
33
34
            $yamlLines = array_slice($reversedYamlLines, 0, $key);
35
            $yamlLines[] = '';
36
            break;
37
        }
38
39
        $correctYamlContent = implode("\n", $yamlLines);
40
41
        if ($yamlContent === $correctYamlContent) {
42
            return new Result($pathToYamlFile, Result::RESULT_CODE_OK, ProcessOutput::STATUS_CODE_OK);
43
        }
44
45
        $differ = new Differ();
46
        $diffBetweenStrings = $differ->diff($yamlContent, $correctYamlContent);
47
48
        return new Result($pathToYamlFile, Result::RESULT_CODE_INVALID_FILE_SYNTAX, ProcessOutput::STATUS_CODE_INVALID_FILE_SYNTAX, $diffBetweenStrings, true);
49
    }
50
}
51