|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SilverStripe\i18n\Messages; |
|
4
|
|
|
|
|
5
|
|
|
use SilverStripe\Dev\Debug; |
|
6
|
|
|
use Symfony\Component\Translation\Exception\InvalidResourceException; |
|
7
|
|
|
use Symfony\Component\Yaml\Exception\ParseException; |
|
8
|
|
|
use Symfony\Component\Yaml\Parser; |
|
9
|
|
|
|
|
10
|
|
|
class YamlReader implements Reader |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var Parser |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $parser = null; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @return Parser |
|
19
|
|
|
*/ |
|
20
|
|
|
protected function getParser() |
|
21
|
|
|
{ |
|
22
|
|
|
if (!$this->parser) { |
|
23
|
|
|
$this->parser = new Parser(); |
|
24
|
|
|
} |
|
25
|
|
|
return $this->parser; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function read($locale, $path) |
|
29
|
|
|
{ |
|
30
|
|
|
try { |
|
31
|
|
|
if (!file_exists($path)) { |
|
32
|
|
|
return []; |
|
33
|
|
|
} |
|
34
|
|
|
// Load |
|
35
|
|
|
$yaml = $this->getParser()->parse(file_get_contents($path)); |
|
36
|
|
|
if (empty($yaml[$locale])) { |
|
37
|
|
|
return []; |
|
38
|
|
|
} |
|
39
|
|
|
// Normalise messages |
|
40
|
|
|
return $this->normaliseMessages($yaml[$locale]); |
|
41
|
|
|
} catch (ParseException $exception) { |
|
42
|
|
|
var_dump($exception); |
|
|
|
|
|
|
43
|
|
|
throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $path), 0, $exception); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Flatten [class => [ key1 => value1, key2 => value2]] into [class.key1 => value1, class.key2 => value2] |
|
49
|
|
|
* |
|
50
|
|
|
* Inverse of YamlWriter::denormaliseMessages() |
|
51
|
|
|
* |
|
52
|
|
|
* @param array $entities |
|
53
|
|
|
* @return mixed |
|
54
|
|
|
*/ |
|
55
|
|
|
protected function normaliseMessages($entities) |
|
56
|
|
|
{ |
|
57
|
|
|
$messages = []; |
|
58
|
|
|
// Squash second and third levels together (class.key) |
|
59
|
|
|
foreach ($entities as $class => $keys) { |
|
60
|
|
|
// Check if namespace omits class |
|
61
|
|
|
if (!is_array($keys)) { |
|
62
|
|
|
$messages[$class] = $keys; |
|
63
|
|
|
} else { |
|
64
|
|
|
foreach ($keys as $key => $value) { |
|
65
|
|
|
$fullKey = "{$class}.{$key}"; |
|
66
|
|
|
$messages[$fullKey] = $value; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
ksort($messages); |
|
71
|
|
|
return $messages; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|