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

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