OptionsResolver.php 41 KB

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