ArrayNode.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 The children
  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. * {@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 (!\strlen($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. * Finalizes the value of this node.
  174. *
  175. * @param mixed $value
  176. *
  177. * @return mixed The finalised value
  178. *
  179. * @throws UnsetKeyException
  180. * @throws InvalidConfigurationException if the node doesn't have enough children
  181. */
  182. protected function finalizeValue($value)
  183. {
  184. if (false === $value) {
  185. throw new UnsetKeyException(sprintf('Unsetting key for path "%s", value: %s.', $this->getPath(), json_encode($value)));
  186. }
  187. foreach ($this->children as $name => $child) {
  188. if (!\array_key_exists($name, $value)) {
  189. if ($child->isRequired()) {
  190. $message = sprintf('The child config "%s" under "%s" must be configured', $name, $this->getPath());
  191. if ($child->getInfo()) {
  192. $message .= sprintf(': %s', $child->getInfo());
  193. } else {
  194. $message .= '.';
  195. }
  196. $ex = new InvalidConfigurationException($message);
  197. $ex->setPath($this->getPath());
  198. throw $ex;
  199. }
  200. if ($child->hasDefaultValue()) {
  201. $value[$name] = $child->getDefaultValue();
  202. }
  203. continue;
  204. }
  205. if ($child->isDeprecated()) {
  206. $deprecation = $child->getDeprecation($name, $this->getPath());
  207. trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
  208. }
  209. try {
  210. $value[$name] = $child->finalize($value[$name]);
  211. } catch (UnsetKeyException $e) {
  212. unset($value[$name]);
  213. }
  214. }
  215. return $value;
  216. }
  217. /**
  218. * Validates the type of the value.
  219. *
  220. * @param mixed $value
  221. *
  222. * @throws InvalidTypeException
  223. */
  224. protected function validateType($value)
  225. {
  226. if (!\is_array($value) && (!$this->allowFalse || false !== $value)) {
  227. $ex = new InvalidTypeException(sprintf('Invalid type for path "%s". Expected "array", but got "%s"', $this->getPath(), get_debug_type($value)));
  228. if ($hint = $this->getInfo()) {
  229. $ex->addHint($hint);
  230. }
  231. $ex->setPath($this->getPath());
  232. throw $ex;
  233. }
  234. }
  235. /**
  236. * Normalizes the value.
  237. *
  238. * @param mixed $value The value to normalize
  239. *
  240. * @return mixed The normalized value
  241. *
  242. * @throws InvalidConfigurationException
  243. */
  244. protected function normalizeValue($value)
  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 $e) {
  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"', 1 === \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".', 1 === \count($proposals) ? '' : 's', 1 === \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. * @return array The remapped values
  294. */
  295. protected function remapXml(array $value)
  296. {
  297. foreach ($this->xmlRemappings as [$singular, $plural]) {
  298. if (!isset($value[$singular])) {
  299. continue;
  300. }
  301. $value[$plural] = Processor::normalizeConfig($value, $singular, $plural);
  302. unset($value[$singular]);
  303. }
  304. return $value;
  305. }
  306. /**
  307. * Merges values together.
  308. *
  309. * @param mixed $leftSide The left side to merge
  310. * @param mixed $rightSide The right side to merge
  311. *
  312. * @return mixed The merged values
  313. *
  314. * @throws InvalidConfigurationException
  315. * @throws \RuntimeException
  316. */
  317. protected function mergeValues($leftSide, $rightSide)
  318. {
  319. if (false === $rightSide) {
  320. // if this is still false after the last config has been merged the
  321. // finalization pass will take care of removing this key entirely
  322. return false;
  323. }
  324. if (false === $leftSide || !$this->performDeepMerging) {
  325. return $rightSide;
  326. }
  327. foreach ($rightSide as $k => $v) {
  328. // no conflict
  329. if (!\array_key_exists($k, $leftSide)) {
  330. if (!$this->allowNewKeys) {
  331. $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()));
  332. $ex->setPath($this->getPath());
  333. throw $ex;
  334. }
  335. $leftSide[$k] = $v;
  336. continue;
  337. }
  338. if (!isset($this->children[$k])) {
  339. if (!$this->ignoreExtraKeys || $this->removeExtraKeys) {
  340. throw new \RuntimeException('merge() expects a normalized config array.');
  341. }
  342. $leftSide[$k] = $v;
  343. continue;
  344. }
  345. $leftSide[$k] = $this->children[$k]->merge($leftSide[$k], $v);
  346. }
  347. return $leftSide;
  348. }
  349. /**
  350. * {@inheritdoc}
  351. */
  352. protected function allowPlaceholders(): bool
  353. {
  354. return false;
  355. }
  356. }