OptionsResolver.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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 = array();
  29. /**
  30. * The default option values.
  31. */
  32. private $defaults = array();
  33. /**
  34. * The names of required options.
  35. */
  36. private $required = array();
  37. /**
  38. * The resolved option values.
  39. */
  40. private $resolved = array();
  41. /**
  42. * A list of normalizer closures.
  43. *
  44. * @var \Closure[]
  45. */
  46. private $normalizers = array();
  47. /**
  48. * A list of accepted values for each option.
  49. */
  50. private $allowedValues = array();
  51. /**
  52. * A list of accepted types for each option.
  53. */
  54. private $allowedTypes = array();
  55. /**
  56. * A list of closures for evaluating lazy options.
  57. */
  58. private $lazy = array();
  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 = array();
  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 = array(
  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] = array();
  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 : array($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 = array($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 = array();
  523. $this->defaults = array();
  524. $this->required = array();
  525. $this->resolved = array();
  526. $this->lazy = array();
  527. $this->normalizers = array();
  528. $this->allowedTypes = array();
  529. $this->allowedValues = array();
  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 = array())
  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 = array();
  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 = array();
  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. private function verifyTypes(string $type, $value, array &$invalidTypes): bool
  720. {
  721. if (\is_array($value) && '[]' === substr($type, -2)) {
  722. return $this->verifyArrayType($type, $value, $invalidTypes);
  723. }
  724. if (self::isValueValidType($type, $value)) {
  725. return true;
  726. }
  727. if (!$invalidTypes) {
  728. $invalidTypes[$this->formatTypeOf($value, null)] = true;
  729. }
  730. return false;
  731. }
  732. private function verifyArrayType(string $type, array $value, array &$invalidTypes, int $level = 0): bool
  733. {
  734. $type = substr($type, 0, -2);
  735. $suffix = '[]';
  736. while (\strlen($suffix) <= $level * 2) {
  737. $suffix .= '[]';
  738. }
  739. if ('[]' === substr($type, -2)) {
  740. $success = true;
  741. foreach ($value as $item) {
  742. if (!\is_array($item)) {
  743. $invalidTypes[$this->formatTypeOf($item, null).$suffix] = true;
  744. return false;
  745. }
  746. if (!$this->verifyArrayType($type, $item, $invalidTypes, $level + 1)) {
  747. $success = false;
  748. }
  749. }
  750. return $success;
  751. }
  752. foreach ($value as $item) {
  753. if (!self::isValueValidType($type, $item)) {
  754. $invalidTypes[$this->formatTypeOf($item, $type).$suffix] = $value;
  755. return false;
  756. }
  757. }
  758. return true;
  759. }
  760. /**
  761. * Returns whether a resolved option with the given name exists.
  762. *
  763. * @param string $option The option name
  764. *
  765. * @return bool Whether the option is set
  766. *
  767. * @throws AccessException If accessing this method outside of {@link resolve()}
  768. *
  769. * @see \ArrayAccess::offsetExists()
  770. */
  771. public function offsetExists($option)
  772. {
  773. if (!$this->locked) {
  774. throw new AccessException('Array access is only supported within closures of lazy options and normalizers.');
  775. }
  776. return array_key_exists($option, $this->defaults);
  777. }
  778. /**
  779. * Not supported.
  780. *
  781. * @throws AccessException
  782. */
  783. public function offsetSet($option, $value)
  784. {
  785. throw new AccessException('Setting options via array access is not supported. Use setDefault() instead.');
  786. }
  787. /**
  788. * Not supported.
  789. *
  790. * @throws AccessException
  791. */
  792. public function offsetUnset($option)
  793. {
  794. throw new AccessException('Removing options via array access is not supported. Use remove() instead.');
  795. }
  796. /**
  797. * Returns the number of set options.
  798. *
  799. * This may be only a subset of the defined options.
  800. *
  801. * @return int Number of options
  802. *
  803. * @throws AccessException If accessing this method outside of {@link resolve()}
  804. *
  805. * @see \Countable::count()
  806. */
  807. public function count()
  808. {
  809. if (!$this->locked) {
  810. throw new AccessException('Counting is only supported within closures of lazy options and normalizers.');
  811. }
  812. return \count($this->defaults);
  813. }
  814. /**
  815. * Returns a string representation of the type of the value.
  816. *
  817. * This method should be used if you pass the type of a value as
  818. * message parameter to a constraint violation. Note that such
  819. * parameters should usually not be included in messages aimed at
  820. * non-technical people.
  821. *
  822. * @param mixed $value The value to return the type of
  823. */
  824. private function formatTypeOf($value, ?string $type): string
  825. {
  826. $suffix = '';
  827. if (null !== $type && '[]' === substr($type, -2)) {
  828. $suffix = '[]';
  829. $type = substr($type, 0, -2);
  830. while ('[]' === substr($type, -2)) {
  831. $type = substr($type, 0, -2);
  832. $value = array_shift($value);
  833. if (!\is_array($value)) {
  834. break;
  835. }
  836. $suffix .= '[]';
  837. }
  838. if (\is_array($value)) {
  839. $subTypes = array();
  840. foreach ($value as $val) {
  841. $subTypes[$this->formatTypeOf($val, null)] = true;
  842. }
  843. return implode('|', array_keys($subTypes)).$suffix;
  844. }
  845. }
  846. return (\is_object($value) ? \get_class($value) : \gettype($value)).$suffix;
  847. }
  848. /**
  849. * Returns a string representation of the value.
  850. *
  851. * This method returns the equivalent PHP tokens for most scalar types
  852. * (i.e. "false" for false, "1" for 1 etc.). Strings are always wrapped
  853. * in double quotes (").
  854. *
  855. * @param mixed $value The value to format as string
  856. */
  857. private function formatValue($value): string
  858. {
  859. if (\is_object($value)) {
  860. return \get_class($value);
  861. }
  862. if (\is_array($value)) {
  863. return 'array';
  864. }
  865. if (\is_string($value)) {
  866. return '"'.$value.'"';
  867. }
  868. if (\is_resource($value)) {
  869. return 'resource';
  870. }
  871. if (null === $value) {
  872. return 'null';
  873. }
  874. if (false === $value) {
  875. return 'false';
  876. }
  877. if (true === $value) {
  878. return 'true';
  879. }
  880. return (string) $value;
  881. }
  882. /**
  883. * Returns a string representation of a list of values.
  884. *
  885. * Each of the values is converted to a string using
  886. * {@link formatValue()}. The values are then concatenated with commas.
  887. *
  888. * @see formatValue()
  889. */
  890. private function formatValues(array $values): string
  891. {
  892. foreach ($values as $key => $value) {
  893. $values[$key] = $this->formatValue($value);
  894. }
  895. return implode(', ', $values);
  896. }
  897. private static function isValueValidType(string $type, $value): bool
  898. {
  899. return (\function_exists($isFunction = 'is_'.$type) && $isFunction($value)) || $value instanceof $type;
  900. }
  901. }