YamlSpacesBetweenGroupsFixer::fix()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 25
ccs 16
cts 16
cp 1
rs 9.7666
cc 3
nc 4
nop 3
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace YamlStandards\Model\YamlSpacesBetweenGroups;
6
7
use SebastianBergmann\Diff\Differ;
8
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
9
use YamlStandards\Model\AbstractFixer;
10
use YamlStandards\Model\Component\YamlService;
11
use YamlStandards\Model\Config\StandardParametersData;
12
use YamlStandards\Result\Result;
13
14
/**
15
 * Fix yaml file have space between groups
16
 */
17
class YamlSpacesBetweenGroupsFixer extends AbstractFixer
18
{
19
    /**
20
     * @inheritDoc
21
     */
22 2
    public function fix(string $pathToFile, string $pathToDumpFixedFile, StandardParametersData $standardParametersData): Result
23
    {
24 2
        $yamlContent = file_get_contents($pathToFile);
25 2
        $yamlContent = str_replace("\r", '', $yamlContent); // remove carriage returns
26 2
        $yamlLines = explode("\n", $yamlContent);
27 2
        $lastYamlElement = end($yamlLines);
28 2
        $filteredYamlLines = array_values(array_filter($yamlLines, [YamlService::class, 'isLineNotBlank']));
29 2
        $yamlSpacesBetweenGroupsDataFactory = new YamlSpacesBetweenGroupsDataFactory();
30
31 2
        $correctYamlContent = $yamlSpacesBetweenGroupsDataFactory->getCorrectYamlContentWithSpacesBetweenGroups($filteredYamlLines, $standardParametersData->getLevel());
32
33 2
        if (YamlService::isLineBlank($lastYamlElement)) {
34 2
            $correctYamlContent .= "\n";
35
        }
36
37 2
        if ($yamlContent === $correctYamlContent) {
38 1
            return new Result($pathToFile, Result::RESULT_CODE_OK);
39
        }
40
41 1
        file_put_contents($pathToDumpFixedFile, $correctYamlContent);
42
43 1
        $differ = new Differ(new UnifiedDiffOutputBuilder());
44 1
        $diffBetweenStrings = $differ->diff($yamlContent, $correctYamlContent);
45
46 1
        return new Result($pathToFile, Result::RESULT_CODE_FIXED_INVALID_FILE_SYNTAX, $diffBetweenStrings);
47
    }
48
}
49