ArrayNode.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Config\Definition;
  11. use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
  12. use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
  13. use Symfony\Component\Config\Definition\Exception\UnsetKeyException;
  14. /**
  15. * Represents an Array node in the config tree.
  16. *
  17. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  18. */
  19. class ArrayNode extends BaseNode implements PrototypeNodeInterface
  20. {
  21. protected $xmlRemappings;
  22. protected $children;
  23. protected $allowFalse;
  24. protected $allowNewKeys;
  25. protected $addIfNotSet;
  26. protected $performDeepMerging;
  27. protected $ignoreExtraKeys;
  28. protected $normalizeKeys;
  29. /**
  30. * Constructor.
  31. *
  32. * @param string $name The Node's name
  33. * @param NodeInterface $parent The node parent
  34. */
  35. public function __construct($name, NodeInterface $parent = null)
  36. {
  37. parent::__construct($name, $parent);
  38. $this->children = array();
  39. $this->xmlRemappings = array();
  40. $this->removeKeyAttribute = true;
  41. $this->allowFalse = false;
  42. $this->addIfNotSet = false;
  43. $this->allowNewKeys = true;
  44. $this->performDeepMerging = true;
  45. $this->normalizeKeys = true;
  46. }
  47. public function setNormalizeKeys($normalizeKeys)
  48. {
  49. $this->normalizeKeys = (Boolean) $normalizeKeys;
  50. }
  51. /**
  52. * Normalizes keys between the different configuration formats.
  53. *
  54. * Namely, you mostly have foo_bar in YAML while you have foo-bar in XML.
  55. * After running this method, all keys are normalized to foo_bar.
  56. *
  57. * If you have a mixed key like foo-bar_moo, it will not be altered.
  58. * The key will also not be altered if the target key already exists.
  59. *
  60. * @param mixed $value
  61. *
  62. * @return array The value with normalized keys
  63. */
  64. protected function preNormalize($value)
  65. {
  66. if (!$this->normalizeKeys || !is_array($value)) {
  67. return $value;
  68. }
  69. foreach ($value as $k => $v) {
  70. if (false !== strpos($k, '-') && false === strpos($k, '_') && !array_key_exists($normalizedKey = str_replace('-', '_', $k), $value)) {
  71. $value[$normalizedKey] = $v;
  72. unset($value[$k]);
  73. }
  74. }
  75. return $value;
  76. }
  77. /**
  78. * Retrieves the children of this node.
  79. *
  80. * @return array The children
  81. */
  82. public function getChildren()
  83. {
  84. return $this->children;
  85. }
  86. /**
  87. * Sets the xml remappings that should be performed.
  88. *
  89. * @param array $remappings an array of the form array(array(string, string))
  90. */
  91. public function setXmlRemappings(array $remappings)
  92. {
  93. $this->xmlRemappings = $remappings;
  94. }
  95. /**
  96. * Sets whether to add default values for this array if it has not been
  97. * defined in any of the configuration files.
  98. *
  99. * @param Boolean $boolean
  100. */
  101. public function setAddIfNotSet($boolean)
  102. {
  103. $this->addIfNotSet = (Boolean) $boolean;
  104. }
  105. /**
  106. * Sets whether false is allowed as value indicating that the array should be unset.
  107. *
  108. * @param Boolean $allow
  109. */
  110. public function setAllowFalse($allow)
  111. {
  112. $this->allowFalse = (Boolean) $allow;
  113. }
  114. /**
  115. * Sets whether new keys can be defined in subsequent configurations.
  116. *
  117. * @param Boolean $allow
  118. */
  119. public function setAllowNewKeys($allow)
  120. {
  121. $this->allowNewKeys = (Boolean) $allow;
  122. }
  123. /**
  124. * Sets if deep merging should occur.
  125. *
  126. * @param Boolean $boolean
  127. */
  128. public function setPerformDeepMerging($boolean)
  129. {
  130. $this->performDeepMerging = (Boolean) $boolean;
  131. }
  132. /**
  133. * Whether extra keys should just be ignore without an exception.
  134. *
  135. * @param Boolean $boolean To allow extra keys
  136. */
  137. public function setIgnoreExtraKeys($boolean)
  138. {
  139. $this->ignoreExtraKeys = (Boolean) $boolean;
  140. }
  141. /**
  142. * Sets the node Name.
  143. *
  144. * @param string $name The node's name
  145. */
  146. public function setName($name)
  147. {
  148. $this->name = $name;
  149. }
  150. /**
  151. * Checks if the node has a default value.
  152. *
  153. * @return Boolean
  154. */
  155. public function hasDefaultValue()
  156. {
  157. return $this->addIfNotSet;
  158. }
  159. /**
  160. * Retrieves the default value.
  161. *
  162. * @return array The default value
  163. *
  164. * @throws \RuntimeException if the node has no default value
  165. */
  166. public function getDefaultValue()
  167. {
  168. if (!$this->hasDefaultValue()) {
  169. throw new \RuntimeException(sprintf('The node at path "%s" has no default value.', $this->getPath()));
  170. }
  171. $defaults = array();
  172. foreach ($this->children as $name => $child) {
  173. if ($child->hasDefaultValue()) {
  174. $defaults[$name] = $child->getDefaultValue();
  175. }
  176. }
  177. return $defaults;
  178. }
  179. /**
  180. * Adds a child node.
  181. *
  182. * @param NodeInterface $node The child node to add
  183. *
  184. * @throws \InvalidArgumentException when the child node has no name
  185. * @throws \InvalidArgumentException when the child node's name is not unique
  186. */
  187. public function addChild(NodeInterface $node)
  188. {
  189. $name = $node->getName();
  190. if (empty($name)) {
  191. throw new \InvalidArgumentException('Child nodes must be named.');
  192. }
  193. if (isset($this->children[$name])) {
  194. throw new \InvalidArgumentException(sprintf('A child node named "%s" already exists.', $name));
  195. }
  196. $this->children[$name] = $node;
  197. }
  198. /**
  199. * Finalizes the value of this node.
  200. *
  201. * @param mixed $value
  202. *
  203. * @return mixed The finalised value
  204. *
  205. * @throws UnsetKeyException
  206. * @throws InvalidConfigurationException if the node doesn't have enough children
  207. */
  208. protected function finalizeValue($value)
  209. {
  210. if (false === $value) {
  211. $msg = sprintf('Unsetting key for path "%s", value: %s', $this->getPath(), json_encode($value));
  212. throw new UnsetKeyException($msg);
  213. }
  214. foreach ($this->children as $name => $child) {
  215. if (!array_key_exists($name, $value)) {
  216. if ($child->isRequired()) {
  217. $msg = sprintf('The child node "%s" at path "%s" must be configured.', $name, $this->getPath());
  218. $ex = new InvalidConfigurationException($msg);
  219. $ex->setPath($this->getPath());
  220. throw $ex;
  221. }
  222. if ($child->hasDefaultValue()) {
  223. $value[$name] = $child->getDefaultValue();
  224. }
  225. continue;
  226. }
  227. try {
  228. $value[$name] = $child->finalize($value[$name]);
  229. } catch (UnsetKeyException $unset) {
  230. unset($value[$name]);
  231. }
  232. }
  233. return $value;
  234. }
  235. /**
  236. * Validates the type of the value.
  237. *
  238. * @param mixed $value
  239. *
  240. * @throws InvalidTypeException
  241. */
  242. protected function validateType($value)
  243. {
  244. if (!is_array($value) && (!$this->allowFalse || false !== $value)) {
  245. $ex = new InvalidTypeException(sprintf(
  246. 'Invalid type for path "%s". Expected array, but got %s',
  247. $this->getPath(),
  248. gettype($value)
  249. ));
  250. $ex->setPath($this->getPath());
  251. throw $ex;
  252. }
  253. }
  254. /**
  255. * Normalizes the value.
  256. *
  257. * @param mixed $value The value to normalize
  258. *
  259. * @return mixed The normalized value
  260. *
  261. * @throws InvalidConfigurationException
  262. */
  263. protected function normalizeValue($value)
  264. {
  265. if (false === $value) {
  266. return $value;
  267. }
  268. $value = $this->remapXml($value);
  269. $normalized = array();
  270. foreach ($this->children as $name => $child) {
  271. if (array_key_exists($name, $value)) {
  272. $normalized[$name] = $child->normalize($value[$name]);
  273. unset($value[$name]);
  274. }
  275. }
  276. // if extra fields are present, throw exception
  277. if (count($value) && !$this->ignoreExtraKeys) {
  278. $msg = sprintf('Unrecognized options "%s" under "%s"', implode(', ', array_keys($value)), $this->getPath());
  279. $ex = new InvalidConfigurationException($msg);
  280. $ex->setPath($this->getPath());
  281. throw $ex;
  282. }
  283. return $normalized;
  284. }
  285. /**
  286. * Remaps multiple singular values to a single plural value.
  287. *
  288. * @param array $value The source values
  289. *
  290. * @return array The remapped values
  291. */
  292. protected function remapXml($value)
  293. {
  294. foreach ($this->xmlRemappings as $transformation) {
  295. list($singular, $plural) = $transformation;
  296. if (!isset($value[$singular])) {
  297. continue;
  298. }
  299. $value[$plural] = Processor::normalizeConfig($value, $singular, $plural);
  300. unset($value[$singular]);
  301. }
  302. return $value;
  303. }
  304. /**
  305. * Merges values together.
  306. *
  307. * @param mixed $leftSide The left side to merge.
  308. * @param mixed $rightSide The right side to merge.
  309. *
  310. * @return mixed The merged values
  311. *
  312. * @throws InvalidConfigurationException
  313. * @throws \RuntimeException
  314. */
  315. protected function mergeValues($leftSide, $rightSide)
  316. {
  317. if (false === $rightSide) {
  318. // if this is still false after the last config has been merged the
  319. // finalization pass will take care of removing this key entirely
  320. return false;
  321. }
  322. if (false === $leftSide || !$this->performDeepMerging) {
  323. return $rightSide;
  324. }
  325. foreach ($rightSide as $k => $v) {
  326. // no conflict
  327. if (!array_key_exists($k, $leftSide)) {
  328. if (!$this->allowNewKeys) {
  329. $ex = new InvalidConfigurationException(sprintf(
  330. 'You are not allowed to define new elements for path "%s". '
  331. .'Please define all elements for this path in one config file. '
  332. .'If you are trying to overwrite an element, make sure you redefine it '
  333. .'with the same name.',
  334. $this->getPath()
  335. ));
  336. $ex->setPath($this->getPath());
  337. throw $ex;
  338. }
  339. $leftSide[$k] = $v;
  340. continue;
  341. }
  342. if (!isset($this->children[$k])) {
  343. throw new \RuntimeException('merge() expects a normalized config array.');
  344. }
  345. $leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v);
  346. }
  347. return $leftSide;
  348. }
  349. }