OptionsResolver.php 44 KB

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