ArrayNodeDefinition.php 14 KB

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