OptionsResolver.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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\OptionsResolver;
  11. use Symfony\Component\OptionsResolver\Exception\AccessException;
  12. use Symfony\Component\OptionsResolver\Exception\InvalidArgumentException;
  13. use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
  14. use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
  15. use Symfony\Component\OptionsResolver\Exception\NoSuchOptionException;
  16. use Symfony\Component\OptionsResolver\Exception\OptionDefinitionException;
  17. use Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException;
  18. /**
  19. * Validates options and merges them with default values.
  20. *
  21. * @author Bernhard Schussek <bschussek@gmail.com>
  22. * @author Tobias Schultze <http://tobion.de>
  23. */
  24. class OptionsResolver implements Options
  25. {
  26. /**
  27. * The names of all defined options.
  28. */
  29. private $defined = [];
  30. /**
  31. * The default option values.
  32. */
  33. private $defaults = [];
  34. /**
  35. * A list of closure for nested options.
  36. *
  37. * @var \Closure[][]
  38. */
  39. private $nested = [];
  40. /**
  41. * The names of required options.
  42. */
  43. private $required = [];
  44. /**
  45. * The resolved option values.
  46. */
  47. private $resolved = [];
  48. /**
  49. * A list of normalizer closures.
  50. *
  51. * @var \Closure[][]
  52. */
  53. private $normalizers = [];
  54. /**
  55. * A list of accepted values for each option.
  56. */
  57. private $allowedValues = [];
  58. /**
  59. * A list of accepted types for each option.
  60. */
  61. private $allowedTypes = [];
  62. /**
  63. * A list of closures for evaluating lazy options.
  64. */
  65. private $lazy = [];
  66. /**
  67. * A list of lazy options whose closure is currently being called.
  68. *
  69. * This list helps detecting circular dependencies between lazy options.
  70. */
  71. private $calling = [];
  72. /**
  73. * A list of deprecated options.
  74. */
  75. private $deprecated = [];
  76. /**
  77. * The list of options provided by the user.
  78. */
  79. private $given = [];
  80. /**
  81. * Whether the instance is locked for reading.
  82. *
  83. * Once locked, the options cannot be changed anymore. This is
  84. * necessary in order to avoid inconsistencies during the resolving
  85. * process. If any option is changed after being read, all evaluated
  86. * lazy options that depend on this option would become invalid.
  87. */
  88. private $locked = false;
  89. private $parentsOptions = [];
  90. private static $typeAliases = [
  91. 'boolean' => 'bool',
  92. 'integer' => 'int',
  93. 'double' => 'float',
  94. ];
  95. /**
  96. * Sets the default value of a given option.
  97. *
  98. * If the default value should be set based on other options, you can pass
  99. * a closure with the following signature:
  100. *
  101. * function (Options $options) {
  102. * // ...
  103. * }
  104. *
  105. * The closure will be evaluated when {@link resolve()} is called. The
  106. * closure has access to the resolved values of other options through the
  107. * passed {@link Options} instance:
  108. *
  109. * function (Options $options) {
  110. * if (isset($options['port'])) {
  111. * // ...
  112. * }
  113. * }
  114. *
  115. * If you want to access the previously set default value, add a second
  116. * argument to the closure's signature:
  117. *
  118. * $options->setDefault('name', 'Default Name');
  119. *
  120. * $options->setDefault('name', function (Options $options, $previousValue) {
  121. * // 'Default Name' === $previousValue
  122. * });
  123. *
  124. * This is mostly useful if the configuration of the {@link Options} object
  125. * is spread across different locations of your code, such as base and
  126. * sub-classes.
  127. *
  128. * If you want to define nested options, you can pass a closure with the
  129. * following signature:
  130. *
  131. * $options->setDefault('database', function (OptionsResolver $resolver) {
  132. * $resolver->setDefined(['dbname', 'host', 'port', 'user', 'pass']);
  133. * }
  134. *
  135. * To get access to the parent options, add a second argument to the closure's
  136. * signature:
  137. *
  138. * function (OptionsResolver $resolver, Options $parent) {
  139. * // 'default' === $parent['connection']
  140. * }
  141. *
  142. * @param string $option The name of the option
  143. * @param mixed $value The default value of the option
  144. *
  145. * @return $this
  146. *
  147. * @throws AccessException If called from a lazy option or normalizer
  148. */
  149. public function setDefault($option, $value)
  150. {
  151. // Setting is not possible once resolving starts, because then lazy
  152. // options could manipulate the state of the object, leading to
  153. // inconsistent results.
  154. if ($this->locked) {
  155. throw new AccessException('Default values cannot be set from a lazy option or normalizer.');
  156. }
  157. // If an option is a closure that should be evaluated lazily, store it
  158. // in the "lazy" property.
  159. if ($value instanceof \Closure) {
  160. $reflClosure = new \ReflectionFunction($value);
  161. $params = $reflClosure->getParameters();
  162. if (isset($params[0]) && Options::class === $this->getParameterClassName($params[0])) {
  163. // Initialize the option if no previous value exists
  164. if (!isset($this->defaults[$option])) {
  165. $this->defaults[$option] = null;
  166. }
  167. // Ignore previous lazy options if the closure has no second parameter
  168. if (!isset($this->lazy[$option]) || !isset($params[1])) {
  169. $this->lazy[$option] = [];
  170. }
  171. // Store closure for later evaluation
  172. $this->lazy[$option][] = $value;
  173. $this->defined[$option] = true;
  174. // Make sure the option is processed and is not nested anymore
  175. unset($this->resolved[$option], $this->nested[$option]);
  176. return $this;
  177. }
  178. if (isset($params[0]) && null !== ($type = $params[0]->getType()) && self::class === $type->getName() && (!isset($params[1]) || (null !== ($type = $params[1]->getType()) && Options::class === $type->getName()))) {
  179. // Store closure for later evaluation
  180. $this->nested[$option][] = $value;
  181. $this->defaults[$option] = [];
  182. $this->defined[$option] = true;
  183. // Make sure the option is processed and is not lazy anymore
  184. unset($this->resolved[$option], $this->lazy[$option]);
  185. return $this;
  186. }
  187. }
  188. // This option is not lazy nor nested anymore
  189. unset($this->lazy[$option], $this->nested[$option]);
  190. // Yet undefined options can be marked as resolved, because we only need
  191. // to resolve options with lazy closures, normalizers or validation
  192. // rules, none of which can exist for undefined options
  193. // If the option was resolved before, update the resolved value
  194. if (!isset($this->defined[$option]) || \array_key_exists($option, $this->resolved)) {
  195. $this->resolved[$option] = $value;
  196. }
  197. $this->defaults[$option] = $value;
  198. $this->defined[$option] = true;
  199. return $this;
  200. }
  201. /**
  202. * Sets a list of default values.
  203. *
  204. * @param array $defaults The default values to set
  205. *
  206. * @return $this
  207. *
  208. * @throws AccessException If called from a lazy option or normalizer
  209. */
  210. public function setDefaults(array $defaults)
  211. {
  212. foreach ($defaults as $option => $value) {
  213. $this->setDefault($option, $value);
  214. }
  215. return $this;
  216. }
  217. /**
  218. * Returns whether a default value is set for an option.
  219. *
  220. * Returns true if {@link setDefault()} was called for this option.
  221. * An option is also considered set if it was set to null.
  222. *
  223. * @param string $option The option name
  224. *
  225. * @return bool Whether a default value is set
  226. */
  227. public function hasDefault($option)
  228. {
  229. return \array_key_exists($option, $this->defaults);
  230. }
  231. /**
  232. * Marks one or more options as required.
  233. *
  234. * @param string|string[] $optionNames One or more option names
  235. *
  236. * @return $this
  237. *
  238. * @throws AccessException If called from a lazy option or normalizer
  239. */
  240. public function setRequired($optionNames)
  241. {
  242. if ($this->locked) {
  243. throw new AccessException('Options cannot be made required from a lazy option or normalizer.');
  244. }
  245. foreach ((array) $optionNames as $option) {
  246. $this->defined[$option] = true;
  247. $this->required[$option] = true;
  248. }
  249. return $this;
  250. }
  251. /**
  252. * Returns whether an option is required.
  253. *
  254. * An option is required if it was passed to {@link setRequired()}.
  255. *
  256. * @param string $option The name of the option
  257. *
  258. * @return bool Whether the option is required
  259. */
  260. public function isRequired($option)
  261. {
  262. return isset($this->required[$option]);
  263. }
  264. /**
  265. * Returns the names of all required options.
  266. *
  267. * @return string[] The names of the required options
  268. *
  269. * @see isRequired()
  270. */
  271. public function getRequiredOptions()
  272. {
  273. return array_keys($this->required);
  274. }
  275. /**
  276. * Returns whether an option is missing a default value.
  277. *
  278. * An option is missing if it was passed to {@link setRequired()}, but not
  279. * to {@link setDefault()}. This option must be passed explicitly to
  280. * {@link resolve()}, otherwise an exception will be thrown.
  281. *
  282. * @param string $option The name of the option
  283. *
  284. * @return bool Whether the option is missing
  285. */
  286. public function isMissing($option)
  287. {
  288. return isset($this->required[$option]) && !\array_key_exists($option, $this->defaults);
  289. }
  290. /**
  291. * Returns the names of all options missing a default value.
  292. *
  293. * @return string[] The names of the missing options
  294. *
  295. * @see isMissing()
  296. */
  297. public function getMissingOptions()
  298. {
  299. return array_keys(array_diff_key($this->required, $this->defaults));
  300. }
  301. /**
  302. * Defines a valid option name.
  303. *
  304. * Defines an option name without setting a default value. The option will
  305. * be accepted when passed to {@link resolve()}. When not passed, the
  306. * option will not be included in the resolved options.
  307. *
  308. * @param string|string[] $optionNames One or more option names
  309. *
  310. * @return $this
  311. *
  312. * @throws AccessException If called from a lazy option or normalizer
  313. */
  314. public function setDefined($optionNames)
  315. {
  316. if ($this->locked) {
  317. throw new AccessException('Options cannot be defined from a lazy option or normalizer.');
  318. }
  319. foreach ((array) $optionNames as $option) {
  320. $this->defined[$option] = true;
  321. }
  322. return $this;
  323. }
  324. /**
  325. * Returns whether an option is defined.
  326. *
  327. * Returns true for any option passed to {@link setDefault()},
  328. * {@link setRequired()} or {@link setDefined()}.
  329. *
  330. * @param string $option The option name
  331. *
  332. * @return bool Whether the option is defined
  333. */
  334. public function isDefined($option)
  335. {
  336. return isset($this->defined[$option]);
  337. }
  338. /**
  339. * Returns the names of all defined options.
  340. *
  341. * @return string[] The names of the defined options
  342. *
  343. * @see isDefined()
  344. */
  345. public function getDefinedOptions()
  346. {
  347. return array_keys($this->defined);
  348. }
  349. public function isNested(string $option): bool
  350. {
  351. return isset($this->nested[$option]);
  352. }
  353. /**
  354. * Deprecates an option, allowed types or values.
  355. *
  356. * Instead of passing the message, you may also pass a closure with the
  357. * following signature:
  358. *
  359. * function (Options $options, $value): string {
  360. * // ...
  361. * }
  362. *
  363. * The closure receives the value as argument and should return a string.
  364. * Return an empty string to ignore the option deprecation.
  365. *
  366. * The closure is invoked when {@link resolve()} is called. The parameter
  367. * passed to the closure is the value of the option after validating it
  368. * and before normalizing it.
  369. *
  370. * @param string|\Closure $deprecationMessage
  371. */
  372. public function setDeprecated(string $option, $deprecationMessage = 'The option "%name%" is deprecated.'): self
  373. {
  374. if ($this->locked) {
  375. throw new AccessException('Options cannot be deprecated from a lazy option or normalizer.');
  376. }
  377. if (!isset($this->defined[$option])) {
  378. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist, defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  379. }
  380. if (!\is_string($deprecationMessage) && !$deprecationMessage instanceof \Closure) {
  381. throw new InvalidArgumentException(sprintf('Invalid type for deprecation message argument, expected string or \Closure, but got "%s".', \gettype($deprecationMessage)));
  382. }
  383. // ignore if empty string
  384. if ('' === $deprecationMessage) {
  385. return $this;
  386. }
  387. $this->deprecated[$option] = $deprecationMessage;
  388. // Make sure the option is processed
  389. unset($this->resolved[$option]);
  390. return $this;
  391. }
  392. public function isDeprecated(string $option): bool
  393. {
  394. return isset($this->deprecated[$option]);
  395. }
  396. /**
  397. * Sets the normalizer for an option.
  398. *
  399. * The normalizer should be a closure with the following signature:
  400. *
  401. * function (Options $options, $value) {
  402. * // ...
  403. * }
  404. *
  405. * The closure is invoked when {@link resolve()} is called. The closure
  406. * has access to the resolved values of other options through the passed
  407. * {@link Options} instance.
  408. *
  409. * The second parameter passed to the closure is the value of
  410. * the option.
  411. *
  412. * The resolved option value is set to the return value of the closure.
  413. *
  414. * @param string $option The option name
  415. * @param \Closure $normalizer The normalizer
  416. *
  417. * @return $this
  418. *
  419. * @throws UndefinedOptionsException If the option is undefined
  420. * @throws AccessException If called from a lazy option or normalizer
  421. */
  422. public function setNormalizer($option, \Closure $normalizer)
  423. {
  424. if ($this->locked) {
  425. throw new AccessException('Normalizers cannot be set from a lazy option or normalizer.');
  426. }
  427. if (!isset($this->defined[$option])) {
  428. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  429. }
  430. $this->normalizers[$option] = [$normalizer];
  431. // Make sure the option is processed
  432. unset($this->resolved[$option]);
  433. return $this;
  434. }
  435. /**
  436. * Adds a normalizer for an option.
  437. *
  438. * The normalizer should be a closure with the following signature:
  439. *
  440. * function (Options $options, $value): mixed {
  441. * // ...
  442. * }
  443. *
  444. * The closure is invoked when {@link resolve()} is called. The closure
  445. * has access to the resolved values of other options through the passed
  446. * {@link Options} instance.
  447. *
  448. * The second parameter passed to the closure is the value of
  449. * the option.
  450. *
  451. * The resolved option value is set to the return value of the closure.
  452. *
  453. * @param string $option The option name
  454. * @param \Closure $normalizer The normalizer
  455. * @param bool $forcePrepend If set to true, prepend instead of appending
  456. *
  457. * @return $this
  458. *
  459. * @throws UndefinedOptionsException If the option is undefined
  460. * @throws AccessException If called from a lazy option or normalizer
  461. */
  462. public function addNormalizer(string $option, \Closure $normalizer, bool $forcePrepend = false): self
  463. {
  464. if ($this->locked) {
  465. throw new AccessException('Normalizers cannot be set from a lazy option or normalizer.');
  466. }
  467. if (!isset($this->defined[$option])) {
  468. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  469. }
  470. if ($forcePrepend) {
  471. array_unshift($this->normalizers[$option], $normalizer);
  472. } else {
  473. $this->normalizers[$option][] = $normalizer;
  474. }
  475. // Make sure the option is processed
  476. unset($this->resolved[$option]);
  477. return $this;
  478. }
  479. /**
  480. * Sets allowed values for an option.
  481. *
  482. * Instead of passing values, you may also pass a closures with the
  483. * following signature:
  484. *
  485. * function ($value) {
  486. * // return true or false
  487. * }
  488. *
  489. * The closure receives the value as argument and should return true to
  490. * accept the value and false to reject the value.
  491. *
  492. * @param string $option The option name
  493. * @param mixed $allowedValues One or more acceptable values/closures
  494. *
  495. * @return $this
  496. *
  497. * @throws UndefinedOptionsException If the option is undefined
  498. * @throws AccessException If called from a lazy option or normalizer
  499. */
  500. public function setAllowedValues($option, $allowedValues)
  501. {
  502. if ($this->locked) {
  503. throw new AccessException('Allowed values cannot be set from a lazy option or normalizer.');
  504. }
  505. if (!isset($this->defined[$option])) {
  506. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  507. }
  508. $this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : [$allowedValues];
  509. // Make sure the option is processed
  510. unset($this->resolved[$option]);
  511. return $this;
  512. }
  513. /**
  514. * Adds allowed values for an option.
  515. *
  516. * The values are merged with the allowed values defined previously.
  517. *
  518. * Instead of passing values, you may also pass a closures with the
  519. * following signature:
  520. *
  521. * function ($value) {
  522. * // return true or false
  523. * }
  524. *
  525. * The closure receives the value as argument and should return true to
  526. * accept the value and false to reject the value.
  527. *
  528. * @param string $option The option name
  529. * @param mixed $allowedValues One or more acceptable values/closures
  530. *
  531. * @return $this
  532. *
  533. * @throws UndefinedOptionsException If the option is undefined
  534. * @throws AccessException If called from a lazy option or normalizer
  535. */
  536. public function addAllowedValues($option, $allowedValues)
  537. {
  538. if ($this->locked) {
  539. throw new AccessException('Allowed values cannot be added from a lazy option or normalizer.');
  540. }
  541. if (!isset($this->defined[$option])) {
  542. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  543. }
  544. if (!\is_array($allowedValues)) {
  545. $allowedValues = [$allowedValues];
  546. }
  547. if (!isset($this->allowedValues[$option])) {
  548. $this->allowedValues[$option] = $allowedValues;
  549. } else {
  550. $this->allowedValues[$option] = array_merge($this->allowedValues[$option], $allowedValues);
  551. }
  552. // Make sure the option is processed
  553. unset($this->resolved[$option]);
  554. return $this;
  555. }
  556. /**
  557. * Sets allowed types for an option.
  558. *
  559. * Any type for which a corresponding is_<type>() function exists is
  560. * acceptable. Additionally, fully-qualified class or interface names may
  561. * be passed.
  562. *
  563. * @param string $option The option name
  564. * @param string|string[] $allowedTypes One or more accepted types
  565. *
  566. * @return $this
  567. *
  568. * @throws UndefinedOptionsException If the option is undefined
  569. * @throws AccessException If called from a lazy option or normalizer
  570. */
  571. public function setAllowedTypes($option, $allowedTypes)
  572. {
  573. if ($this->locked) {
  574. throw new AccessException('Allowed types cannot be set from a lazy option or normalizer.');
  575. }
  576. if (!isset($this->defined[$option])) {
  577. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  578. }
  579. $this->allowedTypes[$option] = (array) $allowedTypes;
  580. // Make sure the option is processed
  581. unset($this->resolved[$option]);
  582. return $this;
  583. }
  584. /**
  585. * Adds allowed types for an option.
  586. *
  587. * The types are merged with the allowed types defined previously.
  588. *
  589. * Any type for which a corresponding is_<type>() function exists is
  590. * acceptable. Additionally, fully-qualified class or interface names may
  591. * be passed.
  592. *
  593. * @param string $option The option name
  594. * @param string|string[] $allowedTypes One or more accepted types
  595. *
  596. * @return $this
  597. *
  598. * @throws UndefinedOptionsException If the option is undefined
  599. * @throws AccessException If called from a lazy option or normalizer
  600. */
  601. public function addAllowedTypes($option, $allowedTypes)
  602. {
  603. if ($this->locked) {
  604. throw new AccessException('Allowed types cannot be added from a lazy option or normalizer.');
  605. }
  606. if (!isset($this->defined[$option])) {
  607. throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  608. }
  609. if (!isset($this->allowedTypes[$option])) {
  610. $this->allowedTypes[$option] = (array) $allowedTypes;
  611. } else {
  612. $this->allowedTypes[$option] = array_merge($this->allowedTypes[$option], (array) $allowedTypes);
  613. }
  614. // Make sure the option is processed
  615. unset($this->resolved[$option]);
  616. return $this;
  617. }
  618. /**
  619. * Removes the option with the given name.
  620. *
  621. * Undefined options are ignored.
  622. *
  623. * @param string|string[] $optionNames One or more option names
  624. *
  625. * @return $this
  626. *
  627. * @throws AccessException If called from a lazy option or normalizer
  628. */
  629. public function remove($optionNames)
  630. {
  631. if ($this->locked) {
  632. throw new AccessException('Options cannot be removed from a lazy option or normalizer.');
  633. }
  634. foreach ((array) $optionNames as $option) {
  635. unset($this->defined[$option], $this->defaults[$option], $this->required[$option], $this->resolved[$option]);
  636. unset($this->lazy[$option], $this->normalizers[$option], $this->allowedTypes[$option], $this->allowedValues[$option]);
  637. }
  638. return $this;
  639. }
  640. /**
  641. * Removes all options.
  642. *
  643. * @return $this
  644. *
  645. * @throws AccessException If called from a lazy option or normalizer
  646. */
  647. public function clear()
  648. {
  649. if ($this->locked) {
  650. throw new AccessException('Options cannot be cleared from a lazy option or normalizer.');
  651. }
  652. $this->defined = [];
  653. $this->defaults = [];
  654. $this->nested = [];
  655. $this->required = [];
  656. $this->resolved = [];
  657. $this->lazy = [];
  658. $this->normalizers = [];
  659. $this->allowedTypes = [];
  660. $this->allowedValues = [];
  661. $this->deprecated = [];
  662. return $this;
  663. }
  664. /**
  665. * Merges options with the default values stored in the container and
  666. * validates them.
  667. *
  668. * Exceptions are thrown if:
  669. *
  670. * - Undefined options are passed;
  671. * - Required options are missing;
  672. * - Options have invalid types;
  673. * - Options have invalid values.
  674. *
  675. * @param array $options A map of option names to values
  676. *
  677. * @return array The merged and validated options
  678. *
  679. * @throws UndefinedOptionsException If an option name is undefined
  680. * @throws InvalidOptionsException If an option doesn't fulfill the
  681. * specified validation rules
  682. * @throws MissingOptionsException If a required option is missing
  683. * @throws OptionDefinitionException If there is a cyclic dependency between
  684. * lazy options and/or normalizers
  685. * @throws NoSuchOptionException If a lazy option reads an unavailable option
  686. * @throws AccessException If called from a lazy option or normalizer
  687. */
  688. public function resolve(array $options = [])
  689. {
  690. if ($this->locked) {
  691. throw new AccessException('Options cannot be resolved from a lazy option or normalizer.');
  692. }
  693. // Allow this method to be called multiple times
  694. $clone = clone $this;
  695. // Make sure that no unknown options are passed
  696. $diff = array_diff_key($options, $clone->defined);
  697. if (\count($diff) > 0) {
  698. ksort($clone->defined);
  699. ksort($diff);
  700. throw new UndefinedOptionsException(sprintf((\count($diff) > 1 ? 'The options "%s" do not exist.' : 'The option "%s" does not exist.').' Defined options are: "%s".', $this->formatOptions(array_keys($diff)), implode('", "', array_keys($clone->defined))));
  701. }
  702. // Override options set by the user
  703. foreach ($options as $option => $value) {
  704. $clone->given[$option] = true;
  705. $clone->defaults[$option] = $value;
  706. unset($clone->resolved[$option], $clone->lazy[$option]);
  707. }
  708. // Check whether any required option is missing
  709. $diff = array_diff_key($clone->required, $clone->defaults);
  710. if (\count($diff) > 0) {
  711. ksort($diff);
  712. throw new MissingOptionsException(sprintf(\count($diff) > 1 ? 'The required options "%s" are missing.' : 'The required option "%s" is missing.', $this->formatOptions(array_keys($diff))));
  713. }
  714. // Lock the container
  715. $clone->locked = true;
  716. // Now process the individual options. Use offsetGet(), which resolves
  717. // the option itself and any options that the option depends on
  718. foreach ($clone->defaults as $option => $_) {
  719. $clone->offsetGet($option);
  720. }
  721. return $clone->resolved;
  722. }
  723. /**
  724. * Returns the resolved value of an option.
  725. *
  726. * @param string $option The option name
  727. * @param bool $triggerDeprecation Whether to trigger the deprecation or not (true by default)
  728. *
  729. * @return mixed The option value
  730. *
  731. * @throws AccessException If accessing this method outside of
  732. * {@link resolve()}
  733. * @throws NoSuchOptionException If the option is not set
  734. * @throws InvalidOptionsException If the option doesn't fulfill the
  735. * specified validation rules
  736. * @throws OptionDefinitionException If there is a cyclic dependency between
  737. * lazy options and/or normalizers
  738. */
  739. public function offsetGet($option/*, bool $triggerDeprecation = true*/)
  740. {
  741. if (!$this->locked) {
  742. throw new AccessException('Array access is only supported within closures of lazy options and normalizers.');
  743. }
  744. $triggerDeprecation = 1 === \func_num_args() || func_get_arg(1);
  745. // Shortcut for resolved options
  746. if (isset($this->resolved[$option]) || \array_key_exists($option, $this->resolved)) {
  747. if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || $this->calling) && \is_string($this->deprecated[$option])) {
  748. @trigger_error(strtr($this->deprecated[$option], ['%name%' => $option]), E_USER_DEPRECATED);
  749. }
  750. return $this->resolved[$option];
  751. }
  752. // Check whether the option is set at all
  753. if (!isset($this->defaults[$option]) && !\array_key_exists($option, $this->defaults)) {
  754. if (!isset($this->defined[$option])) {
  755. throw new NoSuchOptionException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $this->formatOptions([$option]), implode('", "', array_keys($this->defined))));
  756. }
  757. throw new NoSuchOptionException(sprintf('The optional option "%s" has no value set. You should make sure it is set with "isset" before reading it.', $this->formatOptions([$option])));
  758. }
  759. $value = $this->defaults[$option];
  760. // Resolve the option if it is a nested definition
  761. if (isset($this->nested[$option])) {
  762. // If the closure is already being called, we have a cyclic dependency
  763. if (isset($this->calling[$option])) {
  764. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling))));
  765. }
  766. if (!\is_array($value)) {
  767. throw new InvalidOptionsException(sprintf('The nested option "%s" with value %s is expected to be of type array, but is of type "%s".', $this->formatOptions([$option]), $this->formatValue($value), $this->formatTypeOf($value)));
  768. }
  769. // The following section must be protected from cyclic calls.
  770. $this->calling[$option] = true;
  771. try {
  772. $resolver = new self();
  773. $resolver->parentsOptions = $this->parentsOptions;
  774. $resolver->parentsOptions[] = $option;
  775. foreach ($this->nested[$option] as $closure) {
  776. $closure($resolver, $this);
  777. }
  778. $value = $resolver->resolve($value);
  779. } finally {
  780. unset($this->calling[$option]);
  781. }
  782. }
  783. // Resolve the option if the default value is lazily evaluated
  784. if (isset($this->lazy[$option])) {
  785. // If the closure is already being called, we have a cyclic
  786. // dependency
  787. if (isset($this->calling[$option])) {
  788. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling))));
  789. }
  790. // The following section must be protected from cyclic
  791. // calls. Set $calling for the current $option to detect a cyclic
  792. // dependency
  793. // BEGIN
  794. $this->calling[$option] = true;
  795. try {
  796. foreach ($this->lazy[$option] as $closure) {
  797. $value = $closure($this, $value);
  798. }
  799. } finally {
  800. unset($this->calling[$option]);
  801. }
  802. // END
  803. }
  804. // Validate the type of the resolved option
  805. if (isset($this->allowedTypes[$option])) {
  806. $valid = true;
  807. $invalidTypes = [];
  808. foreach ($this->allowedTypes[$option] as $type) {
  809. $type = self::$typeAliases[$type] ?? $type;
  810. if ($valid = $this->verifyTypes($type, $value, $invalidTypes)) {
  811. break;
  812. }
  813. }
  814. if (!$valid) {
  815. $fmtActualValue = $this->formatValue($value);
  816. $fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]);
  817. $fmtProvidedTypes = implode('|', array_keys($invalidTypes));
  818. $allowedContainsArrayType = \count(array_filter($this->allowedTypes[$option], static function ($item) {
  819. return '[]' === substr(self::$typeAliases[$item] ?? $item, -2);
  820. })) > 0;
  821. if (\is_array($value) && $allowedContainsArrayType) {
  822. throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but one of the elements is of type "%s".', $this->formatOptions([$option]), $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes));
  823. }
  824. throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but is of type "%s".', $this->formatOptions([$option]), $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes));
  825. }
  826. }
  827. // Validate the value of the resolved option
  828. if (isset($this->allowedValues[$option])) {
  829. $success = false;
  830. $printableAllowedValues = [];
  831. foreach ($this->allowedValues[$option] as $allowedValue) {
  832. if ($allowedValue instanceof \Closure) {
  833. if ($allowedValue($value)) {
  834. $success = true;
  835. break;
  836. }
  837. // Don't include closures in the exception message
  838. continue;
  839. }
  840. if ($value === $allowedValue) {
  841. $success = true;
  842. break;
  843. }
  844. $printableAllowedValues[] = $allowedValue;
  845. }
  846. if (!$success) {
  847. $message = sprintf(
  848. 'The option "%s" with value %s is invalid.',
  849. $option,
  850. $this->formatValue($value)
  851. );
  852. if (\count($printableAllowedValues) > 0) {
  853. $message .= sprintf(
  854. ' Accepted values are: %s.',
  855. $this->formatValues($printableAllowedValues)
  856. );
  857. }
  858. throw new InvalidOptionsException($message);
  859. }
  860. }
  861. // Check whether the option is deprecated
  862. // and it is provided by the user or is being called from a lazy evaluation
  863. if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || ($this->calling && \is_string($this->deprecated[$option])))) {
  864. $deprecationMessage = $this->deprecated[$option];
  865. if ($deprecationMessage instanceof \Closure) {
  866. // If the closure is already being called, we have a cyclic dependency
  867. if (isset($this->calling[$option])) {
  868. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling))));
  869. }
  870. $this->calling[$option] = true;
  871. try {
  872. if (!\is_string($deprecationMessage = $deprecationMessage($this, $value))) {
  873. throw new InvalidOptionsException(sprintf('Invalid type for deprecation message, expected string but got "%s", return an empty string to ignore.', \gettype($deprecationMessage)));
  874. }
  875. } finally {
  876. unset($this->calling[$option]);
  877. }
  878. }
  879. if ('' !== $deprecationMessage) {
  880. @trigger_error(strtr($deprecationMessage, ['%name%' => $option]), E_USER_DEPRECATED);
  881. }
  882. }
  883. // Normalize the validated option
  884. if (isset($this->normalizers[$option])) {
  885. // If the closure is already being called, we have a cyclic
  886. // dependency
  887. if (isset($this->calling[$option])) {
  888. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', $this->formatOptions(array_keys($this->calling))));
  889. }
  890. // The following section must be protected from cyclic
  891. // calls. Set $calling for the current $option to detect a cyclic
  892. // dependency
  893. // BEGIN
  894. $this->calling[$option] = true;
  895. try {
  896. foreach ($this->normalizers[$option] as $normalizer) {
  897. $value = $normalizer($this, $value);
  898. }
  899. } finally {
  900. unset($this->calling[$option]);
  901. }
  902. // END
  903. }
  904. // Mark as resolved
  905. $this->resolved[$option] = $value;
  906. return $value;
  907. }
  908. private function verifyTypes(string $type, $value, array &$invalidTypes, int $level = 0): bool
  909. {
  910. if (\is_array($value) && '[]' === substr($type, -2)) {
  911. $type = substr($type, 0, -2);
  912. $valid = true;
  913. foreach ($value as $val) {
  914. if (!$this->verifyTypes($type, $val, $invalidTypes, $level + 1)) {
  915. $valid = false;
  916. }
  917. }
  918. return $valid;
  919. }
  920. if (('null' === $type && null === $value) || (\function_exists($func = 'is_'.$type) && $func($value)) || $value instanceof $type) {
  921. return true;
  922. }
  923. if (!$invalidTypes || $level > 0) {
  924. $invalidTypes[$this->formatTypeOf($value)] = true;
  925. }
  926. return false;
  927. }
  928. /**
  929. * Returns whether a resolved option with the given name exists.
  930. *
  931. * @param string $option The option name
  932. *
  933. * @return bool Whether the option is set
  934. *
  935. * @throws AccessException If accessing this method outside of {@link resolve()}
  936. *
  937. * @see \ArrayAccess::offsetExists()
  938. */
  939. public function offsetExists($option)
  940. {
  941. if (!$this->locked) {
  942. throw new AccessException('Array access is only supported within closures of lazy options and normalizers.');
  943. }
  944. return \array_key_exists($option, $this->defaults);
  945. }
  946. /**
  947. * Not supported.
  948. *
  949. * @throws AccessException
  950. */
  951. public function offsetSet($option, $value)
  952. {
  953. throw new AccessException('Setting options via array access is not supported. Use setDefault() instead.');
  954. }
  955. /**
  956. * Not supported.
  957. *
  958. * @throws AccessException
  959. */
  960. public function offsetUnset($option)
  961. {
  962. throw new AccessException('Removing options via array access is not supported. Use remove() instead.');
  963. }
  964. /**
  965. * Returns the number of set options.
  966. *
  967. * This may be only a subset of the defined options.
  968. *
  969. * @return int Number of options
  970. *
  971. * @throws AccessException If accessing this method outside of {@link resolve()}
  972. *
  973. * @see \Countable::count()
  974. */
  975. public function count()
  976. {
  977. if (!$this->locked) {
  978. throw new AccessException('Counting is only supported within closures of lazy options and normalizers.');
  979. }
  980. return \count($this->defaults);
  981. }
  982. /**
  983. * Returns a string representation of the type of the value.
  984. *
  985. * @param mixed $value The value to return the type of
  986. *
  987. * @return string The type of the value
  988. */
  989. private function formatTypeOf($value): string
  990. {
  991. return \is_object($value) ? \get_class($value) : \gettype($value);
  992. }
  993. /**
  994. * Returns a string representation of the value.
  995. *
  996. * This method returns the equivalent PHP tokens for most scalar types
  997. * (i.e. "false" for false, "1" for 1 etc.). Strings are always wrapped
  998. * in double quotes (").
  999. *
  1000. * @param mixed $value The value to format as string
  1001. */
  1002. private function formatValue($value): string
  1003. {
  1004. if (\is_object($value)) {
  1005. return \get_class($value);
  1006. }
  1007. if (\is_array($value)) {
  1008. return 'array';
  1009. }
  1010. if (\is_string($value)) {
  1011. return '"'.$value.'"';
  1012. }
  1013. if (\is_resource($value)) {
  1014. return 'resource';
  1015. }
  1016. if (null === $value) {
  1017. return 'null';
  1018. }
  1019. if (false === $value) {
  1020. return 'false';
  1021. }
  1022. if (true === $value) {
  1023. return 'true';
  1024. }
  1025. return (string) $value;
  1026. }
  1027. /**
  1028. * Returns a string representation of a list of values.
  1029. *
  1030. * Each of the values is converted to a string using
  1031. * {@link formatValue()}. The values are then concatenated with commas.
  1032. *
  1033. * @see formatValue()
  1034. */
  1035. private function formatValues(array $values): string
  1036. {
  1037. foreach ($values as $key => $value) {
  1038. $values[$key] = $this->formatValue($value);
  1039. }
  1040. return implode(', ', $values);
  1041. }
  1042. private function formatOptions(array $options): string
  1043. {
  1044. if ($this->parentsOptions) {
  1045. $prefix = array_shift($this->parentsOptions);
  1046. if ($this->parentsOptions) {
  1047. $prefix .= sprintf('[%s]', implode('][', $this->parentsOptions));
  1048. }
  1049. $options = array_map(static function (string $option) use ($prefix): string {
  1050. return sprintf('%s[%s]', $prefix, $option);
  1051. }, $options);
  1052. }
  1053. return implode('", "', $options);
  1054. }
  1055. private function getParameterClassName(\ReflectionParameter $parameter): ?string
  1056. {
  1057. if (!($type = $parameter->getType()) || $type->isBuiltin()) {
  1058. return null;
  1059. }
  1060. return $type->getName();
  1061. }
  1062. }