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

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