vendor/symfony/config/Definition/ArrayNode.php line 233

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  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;
  11. use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
  12. use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
  13. use Symfony\Component\Config\Definition\Exception\UnsetKeyException;
  14. /**
  15.  * Represents an Array node in the config tree.
  16.  *
  17.  * @author Johannes M. Schmitt <[email protected]>
  18.  */
  19. class ArrayNode extends BaseNode implements PrototypeNodeInterface
  20. {
  21.     protected $xmlRemappings = [];
  22.     protected $children = [];
  23.     protected $allowFalse false;
  24.     protected $allowNewKeys true;
  25.     protected $addIfNotSet false;
  26.     protected $performDeepMerging true;
  27.     protected $ignoreExtraKeys false;
  28.     protected $removeExtraKeys true;
  29.     protected $normalizeKeys true;
  30.     public function setNormalizeKeys(bool $normalizeKeys)
  31.     {
  32.         $this->normalizeKeys $normalizeKeys;
  33.     }
  34.     /**
  35.      * {@inheritdoc}
  36.      *
  37.      * Namely, you mostly have foo_bar in YAML while you have foo-bar in XML.
  38.      * After running this method, all keys are normalized to foo_bar.
  39.      *
  40.      * If you have a mixed key like foo-bar_moo, it will not be altered.
  41.      * The key will also not be altered if the target key already exists.
  42.      */
  43.     protected function preNormalize($value)
  44.     {
  45.         if (!$this->normalizeKeys || !\is_array($value)) {
  46.             return $value;
  47.         }
  48.         $normalized = [];
  49.         foreach ($value as $k => $v) {
  50.             if (str_contains($k'-') && !str_contains($k'_') && !\array_key_exists($normalizedKey str_replace('-''_'$k), $value)) {
  51.                 $normalized[$normalizedKey] = $v;
  52.             } else {
  53.                 $normalized[$k] = $v;
  54.             }
  55.         }
  56.         return $normalized;
  57.     }
  58.     /**
  59.      * Retrieves the children of this node.
  60.      *
  61.      * @return array<string, NodeInterface>
  62.      */
  63.     public function getChildren()
  64.     {
  65.         return $this->children;
  66.     }
  67.     /**
  68.      * Sets the xml remappings that should be performed.
  69.      *
  70.      * @param array $remappings An array of the form [[string, string]]
  71.      */
  72.     public function setXmlRemappings(array $remappings)
  73.     {
  74.         $this->xmlRemappings $remappings;
  75.     }
  76.     /**
  77.      * Gets the xml remappings that should be performed.
  78.      *
  79.      * @return array an array of the form [[string, string]]
  80.      */
  81.     public function getXmlRemappings()
  82.     {
  83.         return $this->xmlRemappings;
  84.     }
  85.     /**
  86.      * Sets whether to add default values for this array if it has not been
  87.      * defined in any of the configuration files.
  88.      */
  89.     public function setAddIfNotSet(bool $boolean)
  90.     {
  91.         $this->addIfNotSet $boolean;
  92.     }
  93.     /**
  94.      * Sets whether false is allowed as value indicating that the array should be unset.
  95.      */
  96.     public function setAllowFalse(bool $allow)
  97.     {
  98.         $this->allowFalse $allow;
  99.     }
  100.     /**
  101.      * Sets whether new keys can be defined in subsequent configurations.
  102.      */
  103.     public function setAllowNewKeys(bool $allow)
  104.     {
  105.         $this->allowNewKeys $allow;
  106.     }
  107.     /**
  108.      * Sets if deep merging should occur.
  109.      */
  110.     public function setPerformDeepMerging(bool $boolean)
  111.     {
  112.         $this->performDeepMerging $boolean;
  113.     }
  114.     /**
  115.      * Whether extra keys should just be ignored without an exception.
  116.      *
  117.      * @param bool $boolean To allow extra keys
  118.      * @param bool $remove  To remove extra keys
  119.      */
  120.     public function setIgnoreExtraKeys(bool $booleanbool $remove true)
  121.     {
  122.         $this->ignoreExtraKeys $boolean;
  123.         $this->removeExtraKeys $this->ignoreExtraKeys && $remove;
  124.     }
  125.     /**
  126.      * {@inheritdoc}
  127.      */
  128.     public function setName(string $name)
  129.     {
  130.         $this->name $name;
  131.     }
  132.     /**
  133.      * {@inheritdoc}
  134.      */
  135.     public function hasDefaultValue()
  136.     {
  137.         return $this->addIfNotSet;
  138.     }
  139.     /**
  140.      * {@inheritdoc}
  141.      */
  142.     public function getDefaultValue()
  143.     {
  144.         if (!$this->hasDefaultValue()) {
  145.             throw new \RuntimeException(sprintf('The node at path "%s" has no default value.'$this->getPath()));
  146.         }
  147.         $defaults = [];
  148.         foreach ($this->children as $name => $child) {
  149.             if ($child->hasDefaultValue()) {
  150.                 $defaults[$name] = $child->getDefaultValue();
  151.             }
  152.         }
  153.         return $defaults;
  154.     }
  155.     /**
  156.      * Adds a child node.
  157.      *
  158.      * @throws \InvalidArgumentException when the child node has no name
  159.      * @throws \InvalidArgumentException when the child node's name is not unique
  160.      */
  161.     public function addChild(NodeInterface $node)
  162.     {
  163.         $name $node->getName();
  164.         if ('' === $name) {
  165.             throw new \InvalidArgumentException('Child nodes must be named.');
  166.         }
  167.         if (isset($this->children[$name])) {
  168.             throw new \InvalidArgumentException(sprintf('A child node named "%s" already exists.'$name));
  169.         }
  170.         $this->children[$name] = $node;
  171.     }
  172.     /**
  173.      * {@inheritdoc}
  174.      *
  175.      * @throws UnsetKeyException
  176.      * @throws InvalidConfigurationException if the node doesn't have enough children
  177.      */
  178.     protected function finalizeValue($value)
  179.     {
  180.         if (false === $value) {
  181.             throw new UnsetKeyException(sprintf('Unsetting key for path "%s", value: %s.'$this->getPath(), json_encode($value)));
  182.         }
  183.         foreach ($this->children as $name => $child) {
  184.             if (!\array_key_exists($name$value)) {
  185.                 if ($child->isRequired()) {
  186.                     $message sprintf('The child config "%s" under "%s" must be configured'$name$this->getPath());
  187.                     if ($child->getInfo()) {
  188.                         $message .= sprintf(': %s'$child->getInfo());
  189.                     } else {
  190.                         $message .= '.';
  191.                     }
  192.                     $ex = new InvalidConfigurationException($message);
  193.                     $ex->setPath($this->getPath());
  194.                     throw $ex;
  195.                 }
  196.                 if ($child->hasDefaultValue()) {
  197.                     $value[$name] = $child->getDefaultValue();
  198.                 }
  199.                 continue;
  200.             }
  201.             if ($child->isDeprecated()) {
  202.                 $deprecation $child->getDeprecation($name$this->getPath());
  203.                 trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
  204.             }
  205.             try {
  206.                 $value[$name] = $child->finalize($value[$name]);
  207.             } catch (UnsetKeyException $e) {
  208.                 unset($value[$name]);
  209.             }
  210.         }
  211.         return $value;
  212.     }
  213.     /**
  214.      * {@inheritdoc}
  215.      */
  216.     protected function validateType($value)
  217.     {
  218.         if (!\is_array($value) && (!$this->allowFalse || false !== $value)) {
  219.             $ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected "array", but got "%s"'$this->getPath(), get_debug_type($value)));
  220.             if ($hint $this->getInfo()) {
  221.                 $ex->addHint($hint);
  222.             }
  223.             $ex->setPath($this->getPath());
  224.             throw $ex;
  225.         }
  226.     }
  227.     /**
  228.      * {@inheritdoc}
  229.      *
  230.      * @throws InvalidConfigurationException
  231.      */
  232.     protected function normalizeValue($value)
  233.     {
  234.         if (false === $value) {
  235.             return $value;
  236.         }
  237.         $value $this->remapXml($value);
  238.         $normalized = [];
  239.         foreach ($value as $name => $val) {
  240.             if (isset($this->children[$name])) {
  241.                 try {
  242.                     $normalized[$name] = $this->children[$name]->normalize($val);
  243.                 } catch (UnsetKeyException $e) {
  244.                 }
  245.                 unset($value[$name]);
  246.             } elseif (!$this->removeExtraKeys) {
  247.                 $normalized[$name] = $val;
  248.             }
  249.         }
  250.         // if extra fields are present, throw exception
  251.         if (\count($value) && !$this->ignoreExtraKeys) {
  252.             $proposals array_keys($this->children);
  253.             sort($proposals);
  254.             $guesses = [];
  255.             foreach (array_keys($value) as $subject) {
  256.                 $minScore = \INF;
  257.                 foreach ($proposals as $proposal) {
  258.                     $distance levenshtein($subject$proposal);
  259.                     if ($distance <= $minScore && $distance 3) {
  260.                         $guesses[$proposal] = $distance;
  261.                         $minScore $distance;
  262.                     }
  263.                 }
  264.             }
  265.             $msg sprintf('Unrecognized option%s "%s" under "%s"'=== \count($value) ? '' 's'implode(', 'array_keys($value)), $this->getPath());
  266.             if (\count($guesses)) {
  267.                 asort($guesses);
  268.                 $msg .= sprintf('. Did you mean "%s"?'implode('", "'array_keys($guesses)));
  269.             } else {
  270.                 $msg .= sprintf('. Available option%s %s "%s".'=== \count($proposals) ? '' 's'=== \count($proposals) ? 'is' 'are'implode('", "'$proposals));
  271.             }
  272.             $ex = new InvalidConfigurationException($msg);
  273.             $ex->setPath($this->getPath());
  274.             throw $ex;
  275.         }
  276.         return $normalized;
  277.     }
  278.     /**
  279.      * Remaps multiple singular values to a single plural value.
  280.      *
  281.      * @return array The remapped values
  282.      */
  283.     protected function remapXml(array $value)
  284.     {
  285.         foreach ($this->xmlRemappings as [$singular$plural]) {
  286.             if (!isset($value[$singular])) {
  287.                 continue;
  288.             }
  289.             $value[$plural] = Processor::normalizeConfig($value$singular$plural);
  290.             unset($value[$singular]);
  291.         }
  292.         return $value;
  293.     }
  294.     /**
  295.      * {@inheritdoc}
  296.      *
  297.      * @throws InvalidConfigurationException
  298.      * @throws \RuntimeException
  299.      */
  300.     protected function mergeValues($leftSide$rightSide)
  301.     {
  302.         if (false === $rightSide) {
  303.             // if this is still false after the last config has been merged the
  304.             // finalization pass will take care of removing this key entirely
  305.             return false;
  306.         }
  307.         if (false === $leftSide || !$this->performDeepMerging) {
  308.             return $rightSide;
  309.         }
  310.         foreach ($rightSide as $k => $v) {
  311.             // no conflict
  312.             if (!\array_key_exists($k$leftSide)) {
  313.                 if (!$this->allowNewKeys) {
  314.                     $ex = new InvalidConfigurationException(sprintf('You are not allowed to define new elements for path "%s". Please define all elements for this path in one config file. If you are trying to overwrite an element, make sure you redefine it with the same name.'$this->getPath()));
  315.                     $ex->setPath($this->getPath());
  316.                     throw $ex;
  317.                 }
  318.                 $leftSide[$k] = $v;
  319.                 continue;
  320.             }
  321.             if (!isset($this->children[$k])) {
  322.                 if (!$this->ignoreExtraKeys || $this->removeExtraKeys) {
  323.                     throw new \RuntimeException('merge() expects a normalized config array.');
  324.                 }
  325.                 $leftSide[$k] = $v;
  326.                 continue;
  327.             }
  328.             $leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v);
  329.         }
  330.         return $leftSide;
  331.     }
  332.     /**
  333.      * {@inheritdoc}
  334.      */
  335.     protected function allowPlaceholders(): bool
  336.     {
  337.         return false;
  338.     }
  339. }