vendor/symfony/config/Definition/Builder/ArrayNodeDefinition.php line 126

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