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