OptionsResolver.php 33 KB

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