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

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;
  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. 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 $boolean, bool $remove = true)
  121. {
  122. $this->ignoreExtraKeys = $boolean;
  123. $this->removeExtraKeys = $this->ignoreExtraKeys && $remove;
  124. }
  125. /**
  126. * Returns true when extra keys should be ignored without an exception.
  127. */
  128. public function shouldIgnoreExtraKeys(): bool
  129. {
  130. return $this->ignoreExtraKeys;
  131. }
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function setName(string $name)
  136. {
  137. $this->name = $name;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function hasDefaultValue()
  143. {
  144. return $this->addIfNotSet;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function getDefaultValue()
  150. {
  151. if (!$this->hasDefaultValue()) {
  152. throw new \RuntimeException(sprintf('The node at path "%s" has no default value.', $this->getPath()));
  153. }
  154. $defaults = [];
  155. foreach ($this->children as $name => $child) {
  156. if ($child->hasDefaultValue()) {
  157. $defaults[$name] = $child->getDefaultValue();
  158. }
  159. }
  160. return $defaults;
  161. }
  162. /**
  163. * Adds a child node.
  164. *
  165. * @throws \InvalidArgumentException when the child node has no name
  166. * @throws \InvalidArgumentException when the child node's name is not unique
  167. */
  168. public function addChild(NodeInterface $node)
  169. {
  170. $name = $node->getName();
  171. if ('' === $name) {
  172. throw new \InvalidArgumentException('Child nodes must be named.');
  173. }
  174. if (isset($this->children[$name])) {
  175. throw new \InvalidArgumentException(sprintf('A child node named "%s" already exists.', $name));
  176. }
  177. $this->children[$name] = $node;
  178. }
  179. /**
  180. * {@inheritdoc}
  181. *
  182. * @throws UnsetKeyException
  183. * @throws InvalidConfigurationException if the node doesn't have enough children
  184. */
  185. protected function finalizeValue($value)
  186. {
  187. if (false === $value) {
  188. throw new UnsetKeyException(sprintf('Unsetting key for path "%s", value: %s.', $this->getPath(), json_encode($value)));
  189. }
  190. foreach ($this->children as $name => $child) {
  191. if (!\array_key_exists($name, $value)) {
  192. if ($child->isRequired()) {
  193. $message = sprintf('The child config "%s" under "%s" must be configured', $name, $this->getPath());
  194. if ($child->getInfo()) {
  195. $message .= sprintf(': %s', $child->getInfo());
  196. } else {
  197. $message .= '.';
  198. }
  199. $ex = new InvalidConfigurationException($message);
  200. $ex->setPath($this->getPath());
  201. throw $ex;
  202. }
  203. if ($child->hasDefaultValue()) {
  204. $value[$name] = $child->getDefaultValue();
  205. }
  206. continue;
  207. }
  208. if ($child->isDeprecated()) {
  209. $deprecation = $child->getDeprecation($name, $this->getPath());
  210. trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
  211. }
  212. try {
  213. $value[$name] = $child->finalize($value[$name]);
  214. } catch (UnsetKeyException $e) {
  215. unset($value[$name]);
  216. }
  217. }
  218. return $value;
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. protected function validateType($value)
  224. {
  225. if (!\is_array($value) && (!$this->allowFalse || false !== $value)) {
  226. $ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected "array", but got "%s"', $this->getPath(), get_debug_type($value)));
  227. if ($hint = $this->getInfo()) {
  228. $ex->addHint($hint);
  229. }
  230. $ex->setPath($this->getPath());
  231. throw $ex;
  232. }
  233. }
  234. /**
  235. * {@inheritdoc}
  236. *
  237. * @throws InvalidConfigurationException
  238. */
  239. protected function normalizeValue($value)
  240. {
  241. if (false === $value) {
  242. return $value;
  243. }
  244. $value = $this->remapXml($value);
  245. $normalized = [];
  246. foreach ($value as $name => $val) {
  247. if (isset($this->children[$name])) {
  248. try {
  249. $normalized[$name] = $this->children[$name]->normalize($val);
  250. } catch (UnsetKeyException $e) {
  251. }
  252. unset($value[$name]);
  253. } elseif (!$this->removeExtraKeys) {
  254. $normalized[$name] = $val;
  255. }
  256. }
  257. // if extra fields are present, throw exception
  258. if (\count($value) && !$this->ignoreExtraKeys) {
  259. $proposals = array_keys($this->children);
  260. sort($proposals);
  261. $guesses = [];
  262. foreach (array_keys($value) as $subject) {
  263. $minScore = \INF;
  264. foreach ($proposals as $proposal) {
  265. $distance = levenshtein($subject, $proposal);
  266. if ($distance <= $minScore && $distance < 3) {
  267. $guesses[$proposal] = $distance;
  268. $minScore = $distance;
  269. }
  270. }
  271. }
  272. $msg = sprintf('Unrecognized option%s "%s" under "%s"', 1 === \count($value) ? '' : 's', implode(', ', array_keys($value)), $this->getPath());
  273. if (\count($guesses)) {
  274. asort($guesses);
  275. $msg .= sprintf('. Did you mean "%s"?', implode('", "', array_keys($guesses)));
  276. } else {
  277. $msg .= sprintf('. Available option%s %s "%s".', 1 === \count($proposals) ? '' : 's', 1 === \count($proposals) ? 'is' : 'are', implode('", "', $proposals));
  278. }
  279. $ex = new InvalidConfigurationException($msg);
  280. $ex->setPath($this->getPath());
  281. throw $ex;
  282. }
  283. return $normalized;
  284. }
  285. /**
  286. * Remaps multiple singular values to a single plural value.
  287. *
  288. * @return array
  289. */
  290. protected function remapXml(array $value)
  291. {
  292. foreach ($this->xmlRemappings as [$singular, $plural]) {
  293. if (!isset($value[$singular])) {
  294. continue;
  295. }
  296. $value[$plural] = Processor::normalizeConfig($value, $singular, $plural);
  297. unset($value[$singular]);
  298. }
  299. return $value;
  300. }
  301. /**
  302. * {@inheritdoc}
  303. *
  304. * @throws InvalidConfigurationException
  305. * @throws \RuntimeException
  306. */
  307. protected function mergeValues($leftSide, $rightSide)
  308. {
  309. if (false === $rightSide) {
  310. // if this is still false after the last config has been merged the
  311. // finalization pass will take care of removing this key entirely
  312. return false;
  313. }
  314. if (false === $leftSide || !$this->performDeepMerging) {
  315. return $rightSide;
  316. }
  317. foreach ($rightSide as $k => $v) {
  318. // no conflict
  319. if (!\array_key_exists($k, $leftSide)) {
  320. if (!$this->allowNewKeys) {
  321. $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()));
  322. $ex->setPath($this->getPath());
  323. throw $ex;
  324. }
  325. $leftSide[$k] = $v;
  326. continue;
  327. }
  328. if (!isset($this->children[$k])) {
  329. if (!$this->ignoreExtraKeys || $this->removeExtraKeys) {
  330. throw new \RuntimeException('merge() expects a normalized config array.');
  331. }
  332. $leftSide[$k] = $v;
  333. continue;
  334. }
  335. $leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v);
  336. }
  337. return $leftSide;
  338. }
  339. /**
  340. * {@inheritdoc}
  341. */
  342. protected function allowPlaceholders(): bool
  343. {
  344. return false;
  345. }
  346. }