ArrayNode.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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\DuplicateKeyException;
  13. use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
  14. use Symfony\Component\Config\Definition\Exception\UnsetKeyException;
  15. use Symfony\Component\DependencyInjection\Extension\Extension;
  16. /**
  17. * Represents an ARRAY node in the config tree.
  18. *
  19. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  20. */
  21. class ArrayNode extends BaseNode implements PrototypeNodeInterface
  22. {
  23. protected $xmlRemappings;
  24. protected $children;
  25. protected $prototype;
  26. protected $keyAttribute;
  27. protected $removeKeyAttribute;
  28. protected $allowFalse;
  29. protected $allowNewKeys;
  30. protected $addIfNotSet;
  31. protected $minNumberOfElements;
  32. protected $performDeepMerging;
  33. protected $defaultValue;
  34. protected $preventExtraKeys;
  35. /**
  36. * Constructor.
  37. *
  38. * @param string $name The Node's name
  39. * @param NodeInterface $parent The node parent
  40. */
  41. public function __construct($name, NodeInterface $parent = null)
  42. {
  43. parent::__construct($name, $parent);
  44. $this->children = array();
  45. $this->xmlRemappings = array();
  46. $this->removeKeyAttribute = true;
  47. $this->allowFalse = false;
  48. $this->addIfNotSet = false;
  49. $this->allowNewKeys = true;
  50. $this->performDeepMerging = true;
  51. $this->minNumberOfElements = 0;
  52. $this->preventExtraKeys = true;
  53. }
  54. /**
  55. * Sets the xml remappings that should be performed.
  56. *
  57. * @param array $remappings an array of the form array(array(string, string))
  58. * @return void
  59. */
  60. public function setXmlRemappings(array $remappings)
  61. {
  62. $this->xmlRemappings = $remappings;
  63. }
  64. /**
  65. * Sets the minimum number of elements that a prototype based node must
  66. * contain. By default this is zero, meaning no elements.
  67. *
  68. * @param integer $number
  69. * @return void
  70. */
  71. public function setMinNumberOfElements($number)
  72. {
  73. $this->minNumberOfElements = $number;
  74. }
  75. /**
  76. * The name of the attribute that should be used as key.
  77. *
  78. * This is only relevant for XML configurations, and only in combination
  79. * with a prototype based node.
  80. *
  81. * For example, if "id" is the keyAttribute, then:
  82. *
  83. * array('id' => 'my_name', 'foo' => 'bar')
  84. *
  85. * becomes
  86. *
  87. * 'id' => array('foo' => 'bar')
  88. *
  89. * If $remove is false, the resulting array will still have the
  90. * "'id' => 'my_name'" item in it.
  91. *
  92. * @param string $attribute The name of the attribute to use as a key
  93. * @param Boolean $remove Whether or not to remove the key
  94. * @return void
  95. */
  96. public function setKeyAttribute($attribute, $remove = true)
  97. {
  98. $this->keyAttribute = $attribute;
  99. $this->removeKeyAttribute = $remove;
  100. }
  101. /**
  102. * Sets whether to add default values for this array if it has not been
  103. * defined in any of the configuration files.
  104. *
  105. * @param Boolean $boolean
  106. * @return void
  107. */
  108. public function setAddIfNotSet($boolean)
  109. {
  110. $this->addIfNotSet = (Boolean) $boolean;
  111. }
  112. /**
  113. * Sets whether false is allowed as value indicating that the array should
  114. * be unset.
  115. *
  116. * @param Boolean $allow
  117. * @return void
  118. */
  119. public function setAllowFalse($allow)
  120. {
  121. $this->allowFalse = (Boolean) $allow;
  122. }
  123. /**
  124. * Sets whether new keys can be defined in subsequent configurations.
  125. *
  126. * @param Boolean $allow
  127. * @return void
  128. */
  129. public function setAllowNewKeys($allow)
  130. {
  131. $this->allowNewKeys = (Boolean) $allow;
  132. }
  133. /**
  134. * Sets if deep merging should occur.
  135. *
  136. * @param boolean $boolean
  137. */
  138. public function setPerformDeepMerging($boolean)
  139. {
  140. $this->performDeepMerging = (Boolean) $boolean;
  141. }
  142. /**
  143. * Sets the node Name.
  144. *
  145. * @param string $name The node's name
  146. */
  147. public function setName($name)
  148. {
  149. $this->name = $name;
  150. }
  151. /**
  152. * Sets the default value of this node.
  153. *
  154. * @param string $value
  155. * @throws \InvalidArgumentException if the default value is not an array
  156. * @throws \RuntimeException if the node does not have a prototype
  157. */
  158. public function setDefaultValue($value)
  159. {
  160. if (!is_array($value)) {
  161. throw new \InvalidArgumentException($this->getPath().': the default value of an array node has to be an array.');
  162. }
  163. if (null === $this->prototype) {
  164. throw new \RuntimeException($this->getPath().': An ARRAY node can have a specified default value only when using a prototype');
  165. }
  166. $this->defaultValue = $value;
  167. }
  168. /**
  169. * Checks if the node has a default value.
  170. *
  171. * @return boolean
  172. */
  173. public function hasDefaultValue()
  174. {
  175. if (null !== $this->prototype) {
  176. return true;
  177. }
  178. return $this->addIfNotSet;
  179. }
  180. /**
  181. * Retrieves the default value.
  182. *
  183. * @return array The default value
  184. * @throws \RuntimeException if the node has no default value
  185. */
  186. public function getDefaultValue()
  187. {
  188. if (!$this->hasDefaultValue()) {
  189. throw new \RuntimeException(sprintf('The node at path "%s" has no default value.', $this->getPath()));
  190. }
  191. if (null !== $this->prototype) {
  192. return $this->defaultValue ?: array();
  193. }
  194. $defaults = array();
  195. foreach ($this->children as $name => $child) {
  196. if (!$child->hasDefaultValue()) {
  197. continue;
  198. }
  199. $defaults[$name] = $child->getDefaultValue();
  200. }
  201. return $defaults;
  202. }
  203. /**
  204. * Sets the node prototype.
  205. *
  206. * @param PrototypeNodeInterface $node
  207. * @throws \RuntimeException if the node doesnt have concrete children
  208. */
  209. public function setPrototype(PrototypeNodeInterface $node)
  210. {
  211. if (count($this->children) > 0) {
  212. throw new \RuntimeException($this->getPath().': An ARRAY node must either have concrete children, or a prototype node.');
  213. }
  214. $this->prototype = $node;
  215. }
  216. /**
  217. * Adds a child node.
  218. *
  219. * @param NodeInterface $node The child node to add
  220. * @throws \InvalidArgumentException when the child node has no name
  221. * @throws \InvalidArgumentException when the child node's name is not unique
  222. * @throws \RuntimeException if this array node is not a prototype
  223. */
  224. public function addChild(NodeInterface $node)
  225. {
  226. $name = $node->getName();
  227. if (empty($name)) {
  228. throw new \InvalidArgumentException('Node name cannot be empty.');
  229. }
  230. if (isset($this->children[$name])) {
  231. throw new \InvalidArgumentException(sprintf('The node "%s" already exists.', $name));
  232. }
  233. if (null !== $this->prototype) {
  234. throw new \RuntimeException('An ARRAY node must either have a prototype, or concrete children.');
  235. }
  236. $this->children[$name] = $node;
  237. }
  238. /**
  239. * Finalises the value of this node.
  240. *
  241. * @param mixed $value
  242. * @return mixed The finalised value
  243. * @throws UnsetKeyException
  244. * @throws InvalidConfigurationException if the node doesnt have enough children
  245. */
  246. protected function finalizeValue($value)
  247. {
  248. if (false === $value) {
  249. throw new UnsetKeyException(sprintf(
  250. 'Unsetting key for path "%s", value: %s',
  251. $this->getPath(),
  252. json_encode($value)
  253. ));
  254. }
  255. if (null !== $this->prototype) {
  256. foreach ($value as $k => $v) {
  257. try {
  258. $value[$k] = $this->prototype->finalize($v);
  259. } catch (UnsetKeyException $unset) {
  260. unset($value[$k]);
  261. }
  262. }
  263. if (count($value) < $this->minNumberOfElements) {
  264. throw new InvalidConfigurationException(sprintf(
  265. 'You must define at least %d element(s) for path "%s".',
  266. $this->minNumberOfElements,
  267. $this->getPath()
  268. ));
  269. }
  270. return $value;
  271. }
  272. foreach ($this->children as $name => $child) {
  273. if (!array_key_exists($name, $value)) {
  274. if ($child->isRequired()) {
  275. throw new InvalidConfigurationException(sprintf(
  276. 'The node at path "%s" must be configured.',
  277. $this->getPath().'.'.$name
  278. ));
  279. }
  280. if ($child->hasDefaultValue()) {
  281. $value[$name] = $child->getDefaultValue();
  282. }
  283. continue;
  284. }
  285. try {
  286. $value[$name] = $child->finalize($value[$name]);
  287. } catch (UnsetKeyException $unset) {
  288. unset($value[$name]);
  289. }
  290. }
  291. return $value;
  292. }
  293. /**
  294. * Validates the type of the value.
  295. *
  296. * @param mixed $value
  297. * @throws InvalidTypeException
  298. */
  299. protected function validateType($value)
  300. {
  301. if (!is_array($value) && (!$this->allowFalse || false !== $value)) {
  302. throw new InvalidTypeException(sprintf(
  303. 'Invalid type for path "%s". Expected array, but got %s',
  304. $this->getPath(),
  305. json_encode($value)
  306. ));
  307. }
  308. }
  309. /**
  310. * Normalises the value.
  311. *
  312. * @param mixed $value The value to normalise
  313. * @return mixed The normalised value
  314. */
  315. protected function normalizeValue($value)
  316. {
  317. if (false === $value) {
  318. return $value;
  319. }
  320. foreach ($this->xmlRemappings as $transformation) {
  321. list($singular, $plural) = $transformation;
  322. if (!isset($value[$singular])) {
  323. continue;
  324. }
  325. $value[$plural] = Extension::normalizeConfig($value, $singular, $plural);
  326. unset($value[$singular]);
  327. }
  328. if (null !== $this->prototype) {
  329. $normalized = array();
  330. foreach ($value as $k => $v) {
  331. if (null !== $this->keyAttribute && is_array($v)) {
  332. if (!isset($v[$this->keyAttribute]) && is_int($k)) {
  333. throw new InvalidConfigurationException(sprintf(
  334. 'You must set a "%s" attribute for path "%s".',
  335. $this->keyAttribute,
  336. $this->getPath()
  337. ));
  338. } else if (isset($v[$this->keyAttribute])) {
  339. $k = $v[$this->keyAttribute];
  340. // remove the key attribute if configured to
  341. if ($this->removeKeyAttribute) {
  342. unset($v[$this->keyAttribute]);
  343. }
  344. }
  345. if (array_key_exists($k, $normalized)) {
  346. throw new DuplicateKeyException(sprintf(
  347. 'Duplicate key "%s" for path "%s".',
  348. $k,
  349. $this->getPath()
  350. ));
  351. }
  352. }
  353. $this->prototype->setName($k);
  354. if (null !== $this->keyAttribute) {
  355. $normalized[$k] = $this->prototype->normalize($v);
  356. } else {
  357. $normalized[] = $this->prototype->normalize($v);
  358. }
  359. }
  360. return $normalized;
  361. }
  362. // note that this purposefully does not exclude unrecognized child keys.
  363. // unrecognized keys are just added in - validation takes place in finalize
  364. foreach ($this->children as $name => $child) {
  365. if (!array_key_exists($name, $value)) {
  366. continue;
  367. }
  368. $value[$name] = $child->normalize($value[$name]);
  369. }
  370. // if extra fields are present and preventExtraKeys is true, throw exception
  371. if ($this->preventExtraKeys && $diff = array_diff(array_keys($value), array_keys($this->children))) {
  372. $msg = sprintf('Unrecognized options "%s" under "%s"', implode(', ', $diff), $this->getPath());
  373. throw new InvalidConfigurationException($msg);
  374. }
  375. return $value;
  376. }
  377. /**
  378. * Merges values together.
  379. *
  380. * @param mixed $leftSide The left side to merge.
  381. * @param mixed $rightSide The right side to merge.
  382. * @return mixed The merged values
  383. * @throws InvalidConfigurationException
  384. * @throws \RuntimeException
  385. */
  386. protected function mergeValues($leftSide, $rightSide)
  387. {
  388. if (false === $rightSide) {
  389. // if this is still false after the last config has been merged the
  390. // finalization pass will take care of removing this key entirely
  391. return false;
  392. }
  393. if (false === $leftSide || !$this->performDeepMerging) {
  394. return $rightSide;
  395. }
  396. foreach ($rightSide as $k => $v) {
  397. // prototype, and key is irrelevant, so simply append the element
  398. if (null !== $this->prototype && null === $this->keyAttribute) {
  399. $leftSide[] = $v;
  400. continue;
  401. }
  402. // no conflict
  403. if (!array_key_exists($k, $leftSide)) {
  404. if (!$this->allowNewKeys) {
  405. throw new InvalidConfigurationException(sprintf(
  406. 'You are not allowed to define new elements for path "%s". '
  407. .'Please define all elements for this path in one config file.',
  408. $this->getPath()
  409. ));
  410. }
  411. $leftSide[$k] = $v;
  412. continue;
  413. }
  414. if (null !== $this->prototype) {
  415. $this->prototype->setName($k);
  416. $leftSide[$k] = $this->prototype->merge($leftSide[$k], $v);
  417. } else {
  418. if (!isset($this->children[$k])) {
  419. throw new \RuntimeException('merge() expects a normalized config array.');
  420. }
  421. $leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v);
  422. }
  423. }
  424. return $leftSide;
  425. }
  426. /**
  427. * Set whether or not this array should just prevent child values from
  428. * keys that have no corresponding child nodes.
  429. *
  430. * If true (default), an exception will be thrown if unrecognized options
  431. * are introduced. If false, extra keys are allowed in and included in
  432. * the final array.
  433. *
  434. * An example would be an "options" array node, where its children
  435. * could be any key of any form. In this case, no children are placed
  436. * on the node, but child values must be allowed.
  437. *
  438. * @param Boolean $v Whether to allow unnamed children
  439. */
  440. public function setPreventExtraKeys($v)
  441. {
  442. $this->preventExtraKeys = $v;
  443. }
  444. }