1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ayaml\Fixture; |
4
|
|
|
|
5
|
|
|
use Retry\Retry; |
6
|
|
|
use Symfony\Component\Yaml\Yaml as SymfonyYaml; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Yaml |
10
|
|
|
* |
11
|
|
|
* @package Ayaml\Fixture |
12
|
|
|
*/ |
13
|
|
|
class YamlData |
14
|
|
|
{ |
15
|
|
|
const SCHEMA_DELIMITER = '.'; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var array |
19
|
|
|
*/ |
20
|
|
|
private $rawData = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param array $rawData |
24
|
|
|
*/ |
25
|
|
|
public function __construct(array $rawData) |
26
|
|
|
{ |
27
|
|
|
$this->rawData = $rawData; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param string $schemaName |
32
|
|
|
* @return array |
33
|
|
|
*/ |
34
|
|
|
public function getSchema($schemaName) |
35
|
|
|
{ |
36
|
|
|
return $this->getSchemaRecursively($schemaName, $this->rawData); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function getRaw() |
40
|
|
|
{ |
41
|
|
|
return $this->rawData; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param string $schemaName |
46
|
|
|
* @param $rawData |
47
|
|
|
* @return array |
48
|
|
|
* @throws AyamlSchemaNotFoundException |
49
|
|
|
*/ |
50
|
|
|
private function getSchemaRecursively($schemaName, $rawData) |
51
|
|
|
{ |
52
|
|
|
$specifiedKey = preg_replace('/\\' . self::SCHEMA_DELIMITER . '.*$/', '', $schemaName); |
53
|
|
|
if (empty($rawData[$specifiedKey])) { |
54
|
|
|
throw new AyamlSchemaNotFoundException('specified schema: ' . $schemaName); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$pattern = '/^\w+\\' . self::SCHEMA_DELIMITER . '/'; |
58
|
|
|
if (preg_match($pattern, $schemaName)) { |
59
|
|
|
return $this->getSchemaRecursively(preg_replace($pattern, '', $schemaName), $rawData[$specifiedKey]); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $rawData[$specifiedKey]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param array $paths |
67
|
|
|
* @param $fileName |
68
|
|
|
* @return YamlData |
69
|
|
|
*/ |
70
|
|
|
public static function load(array $paths, $fileName) |
71
|
|
|
{ |
72
|
|
|
$rawData = (new Retry()) |
73
|
|
|
->retry(count($paths), function ($index) use ($paths, $fileName) { |
74
|
|
|
$basePath = $paths[$index]; |
75
|
|
|
if (file_exists($basePath. '/' . $fileName)) { |
76
|
|
|
$filePath = $basePath . '/' . $fileName; |
77
|
|
|
} elseif (file_exists($basePath . '/' . $fileName . '.yml')) { |
78
|
|
|
$filePath = $basePath . '/' . $fileName . '.yml'; |
79
|
|
|
} elseif (file_exists($basePath . '/' . $fileName . '.yaml')) { |
80
|
|
|
$filePath = $basePath . '/' . $fileName . '.yaml'; |
81
|
|
|
} else { |
82
|
|
|
throw new AyamlFixtureFileNotFoundException('base path: ' . $basePath . ' / file name:' . $fileName); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return SymfonyYaml::parse(file_get_contents($filePath), SymfonyYaml::PARSE_EXCEPTION_ON_INVALID_TYPE); |
86
|
|
|
}); |
87
|
|
|
|
88
|
|
|
return new self($rawData); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|