vendor/symfony/symfony/src/Symfony/Component/Config/Definition/Builder/ArrayNodeDefinition.php line 479

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