ArrayNodeDefinition.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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\Builder;
  11. use Symfony\Component\Config\Definition\ArrayNode;
  12. use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
  13. use Symfony\Component\Config\Definition\PrototypedArrayNode;
  14. /**
  15. * This class provides a fluent interface for defining an array node.
  16. *
  17. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  18. */
  19. class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinitionInterface
  20. {
  21. protected $performDeepMerging = true;
  22. protected $ignoreExtraKeys = false;
  23. protected $removeExtraKeys = true;
  24. protected $children = [];
  25. protected $prototype;
  26. protected $atLeastOne = false;
  27. protected $allowNewKeys = true;
  28. protected $key;
  29. protected $removeKeyItem;
  30. protected $addDefaults = false;
  31. protected $addDefaultChildren = false;
  32. protected $nodeBuilder;
  33. protected $normalizeKeys = true;
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function __construct(?string $name, NodeParentInterface $parent = null)
  38. {
  39. parent::__construct($name, $parent);
  40. $this->nullEquivalent = [];
  41. $this->trueEquivalent = [];
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function setBuilder(NodeBuilder $builder)
  47. {
  48. $this->nodeBuilder = $builder;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function children()
  54. {
  55. return $this->getNodeBuilder();
  56. }
  57. /**
  58. * Sets a prototype for child nodes.
  59. *
  60. * @param string $type The type of node
  61. *
  62. * @return NodeDefinition
  63. */
  64. public function prototype($type)
  65. {
  66. return $this->prototype = $this->getNodeBuilder()->node(null, $type)->setParent($this);
  67. }
  68. /**
  69. * @return VariableNodeDefinition
  70. */
  71. public function variablePrototype()
  72. {
  73. return $this->prototype('variable');
  74. }
  75. /**
  76. * @return ScalarNodeDefinition
  77. */
  78. public function scalarPrototype()
  79. {
  80. return $this->prototype('scalar');
  81. }
  82. /**
  83. * @return BooleanNodeDefinition
  84. */
  85. public function booleanPrototype()
  86. {
  87. return $this->prototype('boolean');
  88. }
  89. /**
  90. * @return IntegerNodeDefinition
  91. */
  92. public function integerPrototype()
  93. {
  94. return $this->prototype('integer');
  95. }
  96. /**
  97. * @return FloatNodeDefinition
  98. */
  99. public function floatPrototype()
  100. {
  101. return $this->prototype('float');
  102. }
  103. /**
  104. * @return ArrayNodeDefinition
  105. */
  106. public function arrayPrototype()
  107. {
  108. return $this->prototype('array');
  109. }
  110. /**
  111. * @return EnumNodeDefinition
  112. */
  113. public function enumPrototype()
  114. {
  115. return $this->prototype('enum');
  116. }
  117. /**
  118. * Adds the default value if the node is not set in the configuration.
  119. *
  120. * This method is applicable to concrete nodes only (not to prototype nodes).
  121. * If this function has been called and the node is not set during the finalization
  122. * phase, it's default value will be derived from its children default values.
  123. *
  124. * @return $this
  125. */
  126. public function addDefaultsIfNotSet()
  127. {
  128. $this->addDefaults = true;
  129. return $this;
  130. }
  131. /**
  132. * Adds children with a default value when none are defined.
  133. *
  134. * This method is applicable to prototype nodes only.
  135. *
  136. * @param int|string|array|null $children The number of children|The child name|The children names to be added
  137. *
  138. * @return $this
  139. */
  140. public function addDefaultChildrenIfNoneSet($children = null)
  141. {
  142. $this->addDefaultChildren = $children;
  143. return $this;
  144. }
  145. /**
  146. * Requires the node to have at least one element.
  147. *
  148. * This method is applicable to prototype nodes only.
  149. *
  150. * @return $this
  151. */
  152. public function requiresAtLeastOneElement()
  153. {
  154. $this->atLeastOne = true;
  155. return $this;
  156. }
  157. /**
  158. * Disallows adding news keys in a subsequent configuration.
  159. *
  160. * If used all keys have to be defined in the same configuration file.
  161. *
  162. * @return $this
  163. */
  164. public function disallowNewKeysInSubsequentConfigs()
  165. {
  166. $this->allowNewKeys = false;
  167. return $this;
  168. }
  169. /**
  170. * Sets a normalization rule for XML configurations.
  171. *
  172. * @param string $singular The key to remap
  173. * @param string $plural The plural of the key for irregular plurals
  174. *
  175. * @return $this
  176. */
  177. public function fixXmlConfig($singular, $plural = null)
  178. {
  179. $this->normalization()->remap($singular, $plural);
  180. return $this;
  181. }
  182. /**
  183. * Sets the attribute which value is to be used as key.
  184. *
  185. * This is useful when you have an indexed array that should be an
  186. * associative array. You can select an item from within the array
  187. * to be the key of the particular item. For example, if "id" is the
  188. * "key", then:
  189. *
  190. * [
  191. * ['id' => 'my_name', 'foo' => 'bar'],
  192. * ];
  193. *
  194. * becomes
  195. *
  196. * [
  197. * 'my_name' => ['foo' => 'bar'],
  198. * ];
  199. *
  200. * If you'd like "'id' => 'my_name'" to still be present in the resulting
  201. * array, then you can set the second argument of this method to false.
  202. *
  203. * This method is applicable to prototype nodes only.
  204. *
  205. * @param string $name The name of the key
  206. * @param bool $removeKeyItem Whether or not the key item should be removed
  207. *
  208. * @return $this
  209. */
  210. public function useAttributeAsKey($name, $removeKeyItem = true)
  211. {
  212. $this->key = $name;
  213. $this->removeKeyItem = $removeKeyItem;
  214. return $this;
  215. }
  216. /**
  217. * Sets whether the node can be unset.
  218. *
  219. * @param bool $allow
  220. *
  221. * @return $this
  222. */
  223. public function canBeUnset($allow = true)
  224. {
  225. $this->merge()->allowUnset($allow);
  226. return $this;
  227. }
  228. /**
  229. * Adds an "enabled" boolean to enable the current section.
  230. *
  231. * By default, the section is disabled. If any configuration is specified then
  232. * the node will be automatically enabled:
  233. *
  234. * enableableArrayNode: {enabled: true, ...} # The config is enabled & default values get overridden
  235. * enableableArrayNode: ~ # The config is enabled & use the default values
  236. * enableableArrayNode: true # The config is enabled & use the default values
  237. * enableableArrayNode: {other: value, ...} # The config is enabled & default values get overridden
  238. * enableableArrayNode: {enabled: false, ...} # The config is disabled
  239. * enableableArrayNode: false # The config is disabled
  240. *
  241. * @return $this
  242. */
  243. public function canBeEnabled()
  244. {
  245. $this
  246. ->addDefaultsIfNotSet()
  247. ->treatFalseLike(['enabled' => false])
  248. ->treatTrueLike(['enabled' => true])
  249. ->treatNullLike(['enabled' => true])
  250. ->beforeNormalization()
  251. ->ifArray()
  252. ->then(function ($v) {
  253. $v['enabled'] = $v['enabled'] ?? true;
  254. return $v;
  255. })
  256. ->end()
  257. ->children()
  258. ->booleanNode('enabled')
  259. ->defaultFalse()
  260. ;
  261. return $this;
  262. }
  263. /**
  264. * Adds an "enabled" boolean to enable the current section.
  265. *
  266. * By default, the section is enabled.
  267. *
  268. * @return $this
  269. */
  270. public function canBeDisabled()
  271. {
  272. $this
  273. ->addDefaultsIfNotSet()
  274. ->treatFalseLike(['enabled' => false])
  275. ->treatTrueLike(['enabled' => true])
  276. ->treatNullLike(['enabled' => true])
  277. ->children()
  278. ->booleanNode('enabled')
  279. ->defaultTrue()
  280. ;
  281. return $this;
  282. }
  283. /**
  284. * Disables the deep merging of the node.
  285. *
  286. * @return $this
  287. */
  288. public function performNoDeepMerging()
  289. {
  290. $this->performDeepMerging = false;
  291. return $this;
  292. }
  293. /**
  294. * Allows extra config keys to be specified under an array without
  295. * throwing an exception.
  296. *
  297. * Those config values are ignored and removed from the resulting
  298. * array. This should be used only in special cases where you want
  299. * to send an entire configuration array through a special tree that
  300. * processes only part of the array.
  301. *
  302. * @param bool $remove Whether to remove the extra keys
  303. *
  304. * @return $this
  305. */
  306. public function ignoreExtraKeys($remove = true)
  307. {
  308. $this->ignoreExtraKeys = true;
  309. $this->removeExtraKeys = $remove;
  310. return $this;
  311. }
  312. /**
  313. * Sets key normalization.
  314. *
  315. * @param bool $bool Whether to enable key normalization
  316. *
  317. * @return $this
  318. */
  319. public function normalizeKeys($bool)
  320. {
  321. $this->normalizeKeys = (bool) $bool;
  322. return $this;
  323. }
  324. /**
  325. * {@inheritdoc}
  326. */
  327. public function append(NodeDefinition $node)
  328. {
  329. $this->children[$node->name] = $node->setParent($this);
  330. return $this;
  331. }
  332. /**
  333. * Returns a node builder to be used to add children and prototype.
  334. *
  335. * @return NodeBuilder The node builder
  336. */
  337. protected function getNodeBuilder()
  338. {
  339. if (null === $this->nodeBuilder) {
  340. $this->nodeBuilder = new NodeBuilder();
  341. }
  342. return $this->nodeBuilder->setParent($this);
  343. }
  344. /**
  345. * {@inheritdoc}
  346. */
  347. protected function createNode()
  348. {
  349. if (null === $this->prototype) {
  350. $node = new ArrayNode($this->name, $this->parent, $this->pathSeparator);
  351. $this->validateConcreteNode($node);
  352. $node->setAddIfNotSet($this->addDefaults);
  353. foreach ($this->children as $child) {
  354. $child->parent = $node;
  355. $node->addChild($child->getNode());
  356. }
  357. } else {
  358. $node = new PrototypedArrayNode($this->name, $this->parent, $this->pathSeparator);
  359. $this->validatePrototypeNode($node);
  360. if (null !== $this->key) {
  361. $node->setKeyAttribute($this->key, $this->removeKeyItem);
  362. }
  363. if (true === $this->atLeastOne || false === $this->allowEmptyValue) {
  364. $node->setMinNumberOfElements(1);
  365. }
  366. if ($this->default) {
  367. $node->setDefaultValue($this->defaultValue);
  368. }
  369. if (false !== $this->addDefaultChildren) {
  370. $node->setAddChildrenIfNoneSet($this->addDefaultChildren);
  371. if ($this->prototype instanceof static && null === $this->prototype->prototype) {
  372. $this->prototype->addDefaultsIfNotSet();
  373. }
  374. }
  375. $this->prototype->parent = $node;
  376. $node->setPrototype($this->prototype->getNode());
  377. }
  378. $node->setAllowNewKeys($this->allowNewKeys);
  379. $node->addEquivalentValue(null, $this->nullEquivalent);
  380. $node->addEquivalentValue(true, $this->trueEquivalent);
  381. $node->addEquivalentValue(false, $this->falseEquivalent);
  382. $node->setPerformDeepMerging($this->performDeepMerging);
  383. $node->setRequired($this->required);
  384. $node->setDeprecated($this->deprecationMessage);
  385. $node->setIgnoreExtraKeys($this->ignoreExtraKeys, $this->removeExtraKeys);
  386. $node->setNormalizeKeys($this->normalizeKeys);
  387. if (null !== $this->normalization) {
  388. $node->setNormalizationClosures($this->normalization->before);
  389. $node->setXmlRemappings($this->normalization->remappings);
  390. }
  391. if (null !== $this->merge) {
  392. $node->setAllowOverwrite($this->merge->allowOverwrite);
  393. $node->setAllowFalse($this->merge->allowFalse);
  394. }
  395. if (null !== $this->validation) {
  396. $node->setFinalValidationClosures($this->validation->rules);
  397. }
  398. return $node;
  399. }
  400. /**
  401. * Validate the configuration of a concrete node.
  402. *
  403. * @throws InvalidDefinitionException
  404. */
  405. protected function validateConcreteNode(ArrayNode $node)
  406. {
  407. $path = $node->getPath();
  408. if (null !== $this->key) {
  409. throw new InvalidDefinitionException(sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s".', $path));
  410. }
  411. if (false === $this->allowEmptyValue) {
  412. throw new InvalidDefinitionException(sprintf('->cannotBeEmpty() is not applicable to concrete nodes at path "%s".', $path));
  413. }
  414. if (true === $this->atLeastOne) {
  415. throw new InvalidDefinitionException(sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s".', $path));
  416. }
  417. if ($this->default) {
  418. throw new InvalidDefinitionException(sprintf('->defaultValue() is not applicable to concrete nodes at path "%s".', $path));
  419. }
  420. if (false !== $this->addDefaultChildren) {
  421. throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s".', $path));
  422. }
  423. }
  424. /**
  425. * Validate the configuration of a prototype node.
  426. *
  427. * @throws InvalidDefinitionException
  428. */
  429. protected function validatePrototypeNode(PrototypedArrayNode $node)
  430. {
  431. $path = $node->getPath();
  432. if ($this->addDefaults) {
  433. throw new InvalidDefinitionException(sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s".', $path));
  434. }
  435. if (false !== $this->addDefaultChildren) {
  436. if ($this->default) {
  437. throw new InvalidDefinitionException(sprintf('A default value and default children might not be used together at path "%s".', $path));
  438. }
  439. if (null !== $this->key && (null === $this->addDefaultChildren || \is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
  440. throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s".', $path));
  441. }
  442. if (null === $this->key && (\is_string($this->addDefaultChildren) || \is_array($this->addDefaultChildren))) {
  443. throw new InvalidDefinitionException(sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s".', $path));
  444. }
  445. }
  446. }
  447. /**
  448. * @return NodeDefinition[]
  449. */
  450. public function getChildNodeDefinitions()
  451. {
  452. return $this->children;
  453. }
  454. /**
  455. * Finds a node defined by the given $nodePath.
  456. *
  457. * @param string $nodePath The path of the node to find. e.g "doctrine.orm.mappings"
  458. */
  459. public function find(string $nodePath): NodeDefinition
  460. {
  461. $firstPathSegment = (false === $pathSeparatorPos = strpos($nodePath, $this->pathSeparator))
  462. ? $nodePath
  463. : substr($nodePath, 0, $pathSeparatorPos);
  464. if (null === $node = ($this->children[$firstPathSegment] ?? null)) {
  465. throw new \RuntimeException(sprintf('Node with name "%s" does not exist in the current node "%s".', $firstPathSegment, $this->name));
  466. }
  467. if (false === $pathSeparatorPos) {
  468. return $node;
  469. }
  470. return $node->find(substr($nodePath, $pathSeparatorPos + \strlen($this->pathSeparator)));
  471. }
  472. }