ArrayNodeDefinition.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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\Builder;
  11. use Symfony\Component\Config\Definition\ArrayNode;
  12. use Symfony\Component\Config\Definition\PrototypedArrayNode;
  13. use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
  14. /**
  15. * This class provides a fluent interface for defining an array node.
  16. *
  17. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  18. */
  19. class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinitionInterface
  20. {
  21. protected $performDeepMerging = true;
  22. protected $ignoreExtraKeys = false;
  23. protected $removeExtraKeys = true;
  24. protected $children = array();
  25. protected $prototype;
  26. protected $atLeastOne = false;
  27. protected $allowNewKeys = true;
  28. protected $key;
  29. protected $removeKeyItem;
  30. protected $addDefaults = false;
  31. protected $addDefaultChildren = false;
  32. protected $nodeBuilder;
  33. protected $normalizeKeys = true;
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function __construct($name, NodeParentInterface $parent = null)
  38. {
  39. parent::__construct($name, $parent);
  40. $this->nullEquivalent = array();
  41. $this->trueEquivalent = array();
  42. }
  43. /**
  44. * Sets a custom children builder.
  45. *
  46. * @param NodeBuilder $builder A custom NodeBuilder
  47. */
  48. public function setBuilder(NodeBuilder $builder)
  49. {
  50. $this->nodeBuilder = $builder;
  51. }
  52. /**
  53. * Returns a builder to add children nodes.
  54. *
  55. * @return NodeBuilder
  56. */
  57. public function children()
  58. {
  59. return $this->getNodeBuilder();
  60. }
  61. /**
  62. * Sets a prototype for child nodes.
  63. *
  64. * @param string $type the type of node
  65. *
  66. * @return NodeDefinition
  67. */
  68. public function prototype($type)
  69. {
  70. return $this->prototype = $this->getNodeBuilder()->node(null, $type)->setParent($this);
  71. }
  72. /**
  73. * Adds the default value if the node is not set in the configuration.
  74. *
  75. * This method is applicable to concrete nodes only (not to prototype nodes).
  76. * If this function has been called and the node is not set during the finalization
  77. * phase, it's default value will be derived from its children default values.
  78. *
  79. * @return $this
  80. */
  81. public function addDefaultsIfNotSet()
  82. {
  83. $this->addDefaults = true;
  84. return $this;
  85. }
  86. /**
  87. * Adds children with a default value when none are defined.
  88. *
  89. * @param int|string|array|null $children The number of children|The child name|The children names to be added
  90. *
  91. * This method is applicable to prototype nodes only.
  92. *
  93. * @return $this
  94. */
  95. public function addDefaultChildrenIfNoneSet($children = null)
  96. {
  97. $this->addDefaultChildren = $children;
  98. return $this;
  99. }
  100. /**
  101. * Requires the node to have at least one element.
  102. *
  103. * This method is applicable to prototype nodes only.
  104. *
  105. * @return $this
  106. */
  107. public function requiresAtLeastOneElement()
  108. {
  109. $this->atLeastOne = true;
  110. return $this;
  111. }
  112. /**
  113. * Disallows adding news keys in a subsequent configuration.
  114. *
  115. * If used all keys have to be defined in the same configuration file.
  116. *
  117. * @return $this
  118. */
  119. public function disallowNewKeysInSubsequentConfigs()
  120. {
  121. $this->allowNewKeys = false;
  122. return $this;
  123. }
  124. /**
  125. * Sets a normalization rule for XML configurations.
  126. *
  127. * @param string $singular The key to remap
  128. * @param string $plural The plural of the key for irregular plurals
  129. *
  130. * @return $this
  131. */
  132. public function fixXmlConfig($singular, $plural = null)
  133. {
  134. $this->normalization()->remap($singular, $plural);
  135. return $this;
  136. }
  137. /**
  138. * Sets the attribute which value is to be used as key.
  139. *
  140. * This is useful when you have an indexed array that should be an
  141. * associative array. You can select an item from within the array
  142. * to be the key of the particular item. For example, if "id" is the
  143. * "key", then:
  144. *
  145. * array(
  146. * array('id' => 'my_name', 'foo' => 'bar'),
  147. * );
  148. *
  149. * becomes
  150. *
  151. * array(
  152. * 'my_name' => array('foo' => 'bar'),
  153. * );
  154. *
  155. * If you'd like "'id' => 'my_name'" to still be present in the resulting
  156. * array, then you can set the second argument of this method to false.
  157. *
  158. * This method is applicable to prototype nodes only.
  159. *
  160. * @param string $name The name of the key
  161. * @param bool $removeKeyItem Whether or not the key item should be removed
  162. *
  163. * @return $this
  164. */
  165. public function useAttributeAsKey($name, $removeKeyItem = true)
  166. {
  167. $this->key = $name;
  168. $this->removeKeyItem = $removeKeyItem;
  169. return $this;
  170. }
  171. /**
  172. * Sets whether the node can be unset.
  173. *
  174. * @param bool $allow
  175. *
  176. * @return $this
  177. */
  178. public function canBeUnset($allow = true)
  179. {
  180. $this->merge()->allowUnset($allow);
  181. return $this;
  182. }
  183. /**
  184. * Adds an "enabled" boolean to enable the current section.
  185. *
  186. * By default, the section is disabled. If any configuration is specified then
  187. * the node will be automatically enabled:
  188. *
  189. * enableableArrayNode: {enabled: true, ...} # The config is enabled & default values get overridden
  190. * enableableArrayNode: ~ # The config is enabled & use the default values
  191. * enableableArrayNode: true # The config is enabled & use the default values
  192. * enableableArrayNode: {other: value, ...} # The config is enabled & default values get overridden
  193. * enableableArrayNode: {enabled: false, ...} # The config is disabled
  194. * enableableArrayNode: false # The config is disabled
  195. *
  196. * @return $this
  197. */
  198. public function canBeEnabled()
  199. {
  200. $this
  201. ->addDefaultsIfNotSet()
  202. ->treatFalseLike(array('enabled' => false))
  203. ->treatTrueLike(array('enabled' => true))
  204. ->treatNullLike(array('enabled' => true))
  205. ->beforeNormalization()
  206. ->ifArray()
  207. ->then(function ($v) {
  208. $v['enabled'] = isset($v['enabled']) ? $v['enabled'] : true;
  209. return $v;
  210. })
  211. ->end()
  212. ->children()
  213. ->booleanNode('enabled')
  214. ->defaultFalse()
  215. ;
  216. return $this;
  217. }
  218. /**
  219. * Adds an "enabled" boolean to enable the current section.
  220. *
  221. * By default, the section is enabled.
  222. *
  223. * @return $this
  224. */
  225. public function canBeDisabled()
  226. {
  227. $this
  228. ->addDefaultsIfNotSet()
  229. ->treatFalseLike(array('enabled' => false))
  230. ->treatTrueLike(array('enabled' => true))
  231. ->treatNullLike(array('enabled' => true))
  232. ->children()
  233. ->booleanNode('enabled')
  234. ->defaultTrue()
  235. ;
  236. return $this;
  237. }
  238. /**
  239. * Disables the deep merging of the node.
  240. *
  241. * @return $this
  242. */
  243. public function performNoDeepMerging()
  244. {
  245. $this->performDeepMerging = false;
  246. return $this;
  247. }
  248. /**
  249. * Allows extra config keys to be specified under an array without
  250. * throwing an exception.
  251. *
  252. * Those config values are simply ignored and removed from the
  253. * resulting array. This should be used only in special cases where
  254. * you want to send an entire configuration array through a special
  255. * tree that processes only part of the array.
  256. *
  257. * @param bool $remove Whether to remove the extra keys
  258. *
  259. * @return $this
  260. */
  261. public function ignoreExtraKeys($remove = true)
  262. {
  263. $this->ignoreExtraKeys = true;
  264. $this->removeExtraKeys = $remove;
  265. return $this;
  266. }
  267. /**
  268. * Sets key normalization.
  269. *
  270. * @param bool $bool Whether to enable key normalization
  271. *
  272. * @return $this
  273. */
  274. public function normalizeKeys($bool)
  275. {
  276. $this->normalizeKeys = (bool) $bool;
  277. return $this;
  278. }
  279. /**
  280. * Appends a node definition.
  281. *
  282. * $node = new ArrayNodeDefinition()
  283. * ->children()
  284. * ->scalarNode('foo')->end()
  285. * ->scalarNode('baz')->end()
  286. * ->end()
  287. * ->append($this->getBarNodeDefinition())
  288. * ;
  289. *
  290. * @param NodeDefinition $node A NodeDefinition instance
  291. *
  292. * @return $this
  293. */
  294. public function append(NodeDefinition $node)
  295. {
  296. $this->children[$node->name] = $node->setParent($this);
  297. return $this;
  298. }
  299. /**
  300. * Returns a node builder to be used to add children and prototype.
  301. *
  302. * @return NodeBuilder The node builder
  303. */
  304. protected function getNodeBuilder()
  305. {
  306. if (null === $this->nodeBuilder) {
  307. $this->nodeBuilder = new NodeBuilder();
  308. }
  309. return $this->nodeBuilder->setParent($this);
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. protected function createNode()
  315. {
  316. if (null === $this->prototype) {
  317. $node = new ArrayNode($this->name, $this->parent);
  318. $this->validateConcreteNode($node);
  319. $node->setAddIfNotSet($this->addDefaults);
  320. foreach ($this->children as $child) {
  321. $child->parent = $node;
  322. $node->addChild($child->getNode());
  323. }
  324. } else {
  325. $node = new PrototypedArrayNode($this->name, $this->parent);
  326. $this->validatePrototypeNode($node);
  327. if (null !== $this->key) {
  328. $node->setKeyAttribute($this->key, $this->removeKeyItem);
  329. }
  330. if (true === $this->atLeastOne) {
  331. $node->setMinNumberOfElements(1);
  332. }
  333. if ($this->default) {
  334. $node->setDefaultValue($this->defaultValue);
  335. }
  336. if (false !== $this->addDefaultChildren) {
  337. $node->setAddChildrenIfNoneSet($this->addDefaultChildren);
  338. if ($this->prototype instanceof static && null === $this->prototype->prototype) {
  339. $this->prototype->addDefaultsIfNotSet();
  340. }
  341. }
  342. $this->prototype->parent = $node;
  343. $node->setPrototype($this->prototype->getNode());
  344. }
  345. $node->setAllowNewKeys($this->allowNewKeys);
  346. $node->addEquivalentValue(null, $this->nullEquivalent);
  347. $node->addEquivalentValue(true, $this->trueEquivalent);
  348. $node->addEquivalentValue(false, $this->falseEquivalent);
  349. $node->setPerformDeepMerging($this->performDeepMerging);
  350. $node->setRequired($this->required);
  351. $node->setIgnoreExtraKeys($this->ignoreExtraKeys, $this->removeExtraKeys);
  352. $node->setNormalizeKeys($this->normalizeKeys);
  353. if (null !== $this->normalization) {
  354. $node->setNormalizationClosures($this->normalization->before);
  355. $node->setXmlRemappings($this->normalization->remappings);
  356. }
  357. if (null !== $this->merge) {
  358. $node->setAllowOverwrite($this->merge->allowOverwrite);
  359. $node->setAllowFalse($this->merge->allowFalse);
  360. }
  361. if (null !== $this->validation) {
  362. $node->setFinalValidationClosures($this->validation->rules);
  363. }
  364. return $node;
  365. }
  366. /**
  367. * Validate the configuration of a concrete node.
  368. *
  369. * @param ArrayNode $node The related node
  370. *
  371. * @throws InvalidDefinitionException
  372. */
  373. protected function validateConcreteNode(ArrayNode $node)
  374. {
  375. $path = $node->getPath();
  376. if (null !== $this->key) {
  377. throw new InvalidDefinitionException(
  378. sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path)
  379. );
  380. }
  381. if (true === $this->atLeastOne) {
  382. throw new InvalidDefinitionException(
  383. sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path)
  384. );
  385. }
  386. if ($this->default) {
  387. throw new InvalidDefinitionException(
  388. sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path)
  389. );
  390. }
  391. if (false !== $this->addDefaultChildren) {
  392. throw new InvalidDefinitionException(
  393. sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path)
  394. );
  395. }
  396. }
  397. /**
  398. * Validate the configuration of a prototype node.
  399. *
  400. * @param PrototypedArrayNode $node The related node
  401. *
  402. * @throws InvalidDefinitionException
  403. */
  404. protected function validatePrototypeNode(PrototypedArrayNode $node)
  405. {
  406. $path = $node->getPath();
  407. if ($this->addDefaults) {
  408. throw new InvalidDefinitionException(
  409. sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path)
  410. );
  411. }
  412. if (false !== $this->addDefaultChildren) {
  413. if ($this->default) {
  414. throw new InvalidDefinitionException(
  415. sprintf('A default value and default children might not be used together at path "%s"', $path)
  416. );
  417. }
  418. if (null !== $this->key && (null === $this->addDefaultChildren || is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
  419. throw new InvalidDefinitionException(
  420. sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path)
  421. );
  422. }
  423. if (null === $this->key && (is_string($this->addDefaultChildren) || is_array($this->addDefaultChildren))) {
  424. throw new InvalidDefinitionException(
  425. sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path)
  426. );
  427. }
  428. }
  429. }
  430. }