4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Config\Definition\Builder;
14 use Symfony\Component\Config\Definition\ArrayNode;
15 use Symfony\Component\Config\Definition\PrototypedArrayNode;
16 use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
19 * This class provides a fluent interface for defining an array node.
21 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
23 class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinitionInterface
25 protected $performDeepMerging = true;
26 protected $ignoreExtraKeys = false;
27 protected $removeExtraKeys = true;
28 protected $children = array();
30 protected $atLeastOne = false;
31 protected $allowNewKeys = true;
33 protected $removeKeyItem;
34 protected $addDefaults = false;
35 protected $addDefaultChildren = false;
36 protected $nodeBuilder;
37 protected $normalizeKeys = true;
42 public function __construct($name, NodeParentInterface $parent = null)
44 parent::__construct($name, $parent);
46 $this->nullEquivalent = array();
47 $this->trueEquivalent = array();
51 * Sets a custom children builder.
53 * @param NodeBuilder $builder A custom NodeBuilder
55 public function setBuilder(NodeBuilder $builder)
57 $this->nodeBuilder = $builder;
61 * Returns a builder to add children nodes.
65 public function children()
67 return $this->getNodeBuilder();
71 * Sets a prototype for child nodes.
73 * @param string $type the type of node
75 * @return NodeDefinition
77 public function prototype($type)
79 return $this->prototype = $this->getNodeBuilder()->node(null, $type)->setParent($this);
83 * Adds the default value if the node is not set in the configuration.
85 * This method is applicable to concrete nodes only (not to prototype nodes).
86 * If this function has been called and the node is not set during the finalization
87 * phase, it's default value will be derived from its children default values.
91 public function addDefaultsIfNotSet()
93 $this->addDefaults = true;
99 * Adds children with a default value when none are defined.
101 * @param int|string|array|null $children The number of children|The child name|The children names to be added
103 * This method is applicable to prototype nodes only.
107 public function addDefaultChildrenIfNoneSet($children = null)
109 $this->addDefaultChildren = $children;
115 * Requires the node to have at least one element.
117 * This method is applicable to prototype nodes only.
121 public function requiresAtLeastOneElement()
123 $this->atLeastOne = true;
129 * Disallows adding news keys in a subsequent configuration.
131 * If used all keys have to be defined in the same configuration file.
135 public function disallowNewKeysInSubsequentConfigs()
137 $this->allowNewKeys = false;
143 * Sets a normalization rule for XML configurations.
145 * @param string $singular The key to remap
146 * @param string $plural The plural of the key for irregular plurals
150 public function fixXmlConfig($singular, $plural = null)
152 $this->normalization()->remap($singular, $plural);
158 * Sets the attribute which value is to be used as key.
160 * This is useful when you have an indexed array that should be an
161 * associative array. You can select an item from within the array
162 * to be the key of the particular item. For example, if "id" is the
166 * array('id' => 'my_name', 'foo' => 'bar'),
172 * 'my_name' => array('foo' => 'bar'),
175 * If you'd like "'id' => 'my_name'" to still be present in the resulting
176 * array, then you can set the second argument of this method to false.
178 * This method is applicable to prototype nodes only.
180 * @param string $name The name of the key
181 * @param bool $removeKeyItem Whether or not the key item should be removed
185 public function useAttributeAsKey($name, $removeKeyItem = true)
188 $this->removeKeyItem = $removeKeyItem;
194 * Sets whether the node can be unset.
200 public function canBeUnset($allow = true)
202 $this->merge()->allowUnset($allow);
208 * Adds an "enabled" boolean to enable the current section.
210 * By default, the section is disabled. If any configuration is specified then
211 * the node will be automatically enabled:
213 * enableableArrayNode: {enabled: true, ...} # The config is enabled & default values get overridden
214 * enableableArrayNode: ~ # The config is enabled & use the default values
215 * enableableArrayNode: true # The config is enabled & use the default values
216 * enableableArrayNode: {other: value, ...} # The config is enabled & default values get overridden
217 * enableableArrayNode: {enabled: false, ...} # The config is disabled
218 * enableableArrayNode: false # The config is disabled
222 public function canBeEnabled()
225 ->addDefaultsIfNotSet()
226 ->treatFalseLike(array('enabled' => false))
227 ->treatTrueLike(array('enabled' => true))
228 ->treatNullLike(array('enabled' => true))
229 ->beforeNormalization()
231 ->then(function ($v) {
232 $v['enabled'] = isset($v['enabled']) ? $v['enabled'] : true;
238 ->booleanNode('enabled')
246 * Adds an "enabled" boolean to enable the current section.
248 * By default, the section is enabled.
252 public function canBeDisabled()
255 ->addDefaultsIfNotSet()
256 ->treatFalseLike(array('enabled' => false))
257 ->treatTrueLike(array('enabled' => true))
258 ->treatNullLike(array('enabled' => true))
260 ->booleanNode('enabled')
268 * Disables the deep merging of the node.
272 public function performNoDeepMerging()
274 $this->performDeepMerging = false;
280 * Allows extra config keys to be specified under an array without
281 * throwing an exception.
283 * Those config values are simply ignored and removed from the
284 * resulting array. This should be used only in special cases where
285 * you want to send an entire configuration array through a special
286 * tree that processes only part of the array.
288 * @param bool $remove Whether to remove the extra keys
292 public function ignoreExtraKeys($remove = true)
294 $this->ignoreExtraKeys = true;
295 $this->removeExtraKeys = $remove;
301 * Sets key normalization.
303 * @param bool $bool Whether to enable key normalization
307 public function normalizeKeys($bool)
309 $this->normalizeKeys = (bool) $bool;
315 * Appends a node definition.
317 * $node = new ArrayNodeDefinition()
319 * ->scalarNode('foo')->end()
320 * ->scalarNode('baz')->end()
322 * ->append($this->getBarNodeDefinition())
325 * @param NodeDefinition $node A NodeDefinition instance
329 public function append(NodeDefinition $node)
331 $this->children[$node->name] = $node->setParent($this);
337 * Returns a node builder to be used to add children and prototype.
339 * @return NodeBuilder The node builder
341 protected function getNodeBuilder()
343 if (null === $this->nodeBuilder) {
344 $this->nodeBuilder = new NodeBuilder();
347 return $this->nodeBuilder->setParent($this);
353 protected function createNode()
355 if (null === $this->prototype) {
356 $node = new ArrayNode($this->name, $this->parent);
358 $this->validateConcreteNode($node);
360 $node->setAddIfNotSet($this->addDefaults);
362 foreach ($this->children as $child) {
363 $child->parent = $node;
364 $node->addChild($child->getNode());
367 $node = new PrototypedArrayNode($this->name, $this->parent);
369 $this->validatePrototypeNode($node);
371 if (null !== $this->key) {
372 $node->setKeyAttribute($this->key, $this->removeKeyItem);
375 if (true === $this->atLeastOne) {
376 $node->setMinNumberOfElements(1);
379 if ($this->default) {
380 $node->setDefaultValue($this->defaultValue);
383 if (false !== $this->addDefaultChildren) {
384 $node->setAddChildrenIfNoneSet($this->addDefaultChildren);
385 if ($this->prototype instanceof static && null === $this->prototype->prototype) {
386 $this->prototype->addDefaultsIfNotSet();
390 $this->prototype->parent = $node;
391 $node->setPrototype($this->prototype->getNode());
394 $node->setAllowNewKeys($this->allowNewKeys);
395 $node->addEquivalentValue(null, $this->nullEquivalent);
396 $node->addEquivalentValue(true, $this->trueEquivalent);
397 $node->addEquivalentValue(false, $this->falseEquivalent);
398 $node->setPerformDeepMerging($this->performDeepMerging);
399 $node->setRequired($this->required);
400 $node->setIgnoreExtraKeys($this->ignoreExtraKeys, $this->removeExtraKeys);
401 $node->setNormalizeKeys($this->normalizeKeys);
403 if (null !== $this->normalization) {
404 $node->setNormalizationClosures($this->normalization->before);
405 $node->setXmlRemappings($this->normalization->remappings);
408 if (null !== $this->merge) {
409 $node->setAllowOverwrite($this->merge->allowOverwrite);
410 $node->setAllowFalse($this->merge->allowFalse);
413 if (null !== $this->validation) {
414 $node->setFinalValidationClosures($this->validation->rules);
421 * Validate the configuration of a concrete node.
423 * @param ArrayNode $node The related node
425 * @throws InvalidDefinitionException
427 protected function validateConcreteNode(ArrayNode $node)
429 $path = $node->getPath();
431 if (null !== $this->key) {
432 throw new InvalidDefinitionException(
433 sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s"', $path)
437 if (true === $this->atLeastOne) {
438 throw new InvalidDefinitionException(
439 sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s"', $path)
443 if ($this->default) {
444 throw new InvalidDefinitionException(
445 sprintf('->defaultValue() is not applicable to concrete nodes at path "%s"', $path)
449 if (false !== $this->addDefaultChildren) {
450 throw new InvalidDefinitionException(
451 sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s"', $path)
457 * Validate the configuration of a prototype node.
459 * @param PrototypedArrayNode $node The related node
461 * @throws InvalidDefinitionException
463 protected function validatePrototypeNode(PrototypedArrayNode $node)
465 $path = $node->getPath();
467 if ($this->addDefaults) {
468 throw new InvalidDefinitionException(
469 sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s"', $path)
473 if (false !== $this->addDefaultChildren) {
474 if ($this->default) {
475 throw new InvalidDefinitionException(
476 sprintf('A default value and default children might not be used together at path "%s"', $path)
480 if (null !== $this->key && (null === $this->addDefaultChildren || is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
481 throw new InvalidDefinitionException(
482 sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s"', $path)
486 if (null === $this->key && (is_string($this->addDefaultChildren) || is_array($this->addDefaultChildren))) {
487 throw new InvalidDefinitionException(
488 sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s"', $path)