1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19:
20: final class ConfigAdapterNeon implements IConfigAdapter
21: {
22:
23: public static $sectionSeparator = ' < ';
24:
25:
26: public static $keySeparator = '.';
27:
28:
29: 30: 31:
32: final public function __construct()
33: {
34: throw new LogicException("Cannot instantiate static class " . get_class($this));
35: }
36:
37:
38:
39: 40: 41: 42: 43: 44:
45: public static function load($file)
46: {
47: if (!is_file($file) || !is_readable($file)) {
48: throw new FileNotFoundException("File '$file' is missing or is not readable.");
49: }
50:
51: $neon = Neon::decode(file_get_contents($file));
52:
53: $separator = trim(self::$sectionSeparator);
54: $data = array();
55: foreach ($neon as $secName => $secData) {
56: if ($secData === NULL) { 57: $secData = array();
58: }
59:
60: if (is_array($secData)) {
61: 62: $parts = $separator ? explode($separator, $secName) : array($secName);
63:
64: if (count($parts) > 1) {
65: $parent = trim($parts[1]);
66: $cursor = & $data;
67:
68: foreach (self::$keySeparator ? explode(self::$keySeparator, $parent) : array($parent) as $part) {
69: if (isset($cursor[$part]) && is_array($cursor[$part])) {
70: $cursor = & $cursor[$part];
71: } else {
72: throw new InvalidStateException("Missing parent section $parent in '$file'.");
73: }
74: }
75: $secData = ArrayTools::mergeTree($secData, $cursor);
76: }
77:
78: $secName = trim($parts[0]);
79: if ($secName === '') {
80: throw new InvalidStateException("Invalid empty section name in '$file'.");
81: }
82: }
83:
84: if (self::$keySeparator) {
85: $cursor = & $data;
86: foreach (explode(self::$keySeparator, $secName) as $part) {
87: if (!isset($cursor[$part]) || is_array($cursor[$part])) {
88: $cursor = & $cursor[$part];
89: } else {
90: throw new InvalidStateException("Invalid section [$secName] in '$file'.");
91: }
92: }
93: } else {
94: $cursor = & $data[$secName];
95: }
96:
97: if (is_array($secData) && is_array($cursor)) {
98: $secData = ArrayTools::mergeTree($secData, $cursor);
99: }
100:
101: $cursor = $secData;
102: }
103:
104: return $data;
105: }
106:
107:
108:
109: 110: 111: 112: 113: 114:
115: public static function save($config, $file)
116: {
117: if (!file_put_contents($file, "# generated by Nette\n\n" . Neon::encode($config, Neon::BLOCK))) {
118: throw new IOException("Cannot write file '$file'.");
119: }
120: }
121:
122: }
123: