1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\DI\Config;
9:
10: use Nette;
11: use Nette\Utils\Validators;
12:
13:
14: 15: 16: 17: 18: 19: 20:
21: class Loader extends Nette\Object
22: {
23:
24: const INCLUDES_KEY = 'includes';
25:
26: private $adapters = array(
27: 'php' => 'Nette\DI\Config\Adapters\PhpAdapter',
28: 'ini' => 'Nette\DI\Config\Adapters\IniAdapter',
29: 'neon' => 'Nette\DI\Config\Adapters\NeonAdapter',
30: );
31:
32: private $dependencies = array();
33:
34:
35: 36: 37: 38: 39: 40:
41: public function load($file, $section = NULL)
42: {
43: if (!is_file($file) || !is_readable($file)) {
44: throw new Nette\FileNotFoundException("File '$file' is missing or is not readable.");
45: }
46: $this->dependencies[] = realpath($file);
47: $data = $this->getAdapter($file)->load($file);
48:
49: if ($section) {
50: if (isset($data[self::INCLUDES_KEY])) {
51: throw new Nette\InvalidStateException("Section 'includes' must be placed under some top section in file '$file'.");
52: }
53: $data = $this->getSection($data, $section, $file);
54: }
55:
56:
57: $merged = array();
58: if (isset($data[self::INCLUDES_KEY])) {
59: Validators::assert($data[self::INCLUDES_KEY], 'list', "section 'includes' in file '$file'");
60: foreach ($data[self::INCLUDES_KEY] as $include) {
61: $merged = Helpers::merge($this->load(dirname($file) . '/' . $include), $merged);
62: }
63: }
64: unset($data[self::INCLUDES_KEY]);
65:
66: return Helpers::merge($data, $merged);
67: }
68:
69:
70: 71: 72: 73: 74: 75:
76: public function save($data, $file)
77: {
78: if (file_put_contents($file, $this->getAdapter($file)->dump($data)) === FALSE) {
79: throw new Nette\IOException("Cannot write file '$file'.");
80: }
81: }
82:
83:
84: 85: 86: 87:
88: public function getDependencies()
89: {
90: return array_unique($this->dependencies);
91: }
92:
93:
94: 95: 96: 97: 98: 99:
100: public function addAdapter($extension, $adapter)
101: {
102: $this->adapters[strtolower($extension)] = $adapter;
103: return $this;
104: }
105:
106:
107:
108: private function getAdapter($file)
109: {
110: $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
111: if (!isset($this->adapters[$extension])) {
112: throw new Nette\InvalidArgumentException("Unknown file extension '$file'.");
113: }
114: return is_object($this->adapters[$extension]) ? $this->adapters[$extension] : new $this->adapters[$extension];
115: }
116:
117:
118: private function getSection(array $data, $key, $file)
119: {
120: Validators::assertField($data, $key, 'array|null', "section '%' in file '$file'");
121: $item = $data[$key];
122: if ($parent = Helpers::takeParent($item)) {
123: $item = Helpers::merge($item, $this->getSection($data, $parent, $file));
124: }
125: return $item;
126: }
127:
128: }
129: