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