ArrayNode.php 12 KB

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