You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1070 lines
34 KiB

  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 = true;
  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. $fmtActualValue = $this->formatValue($value);
  655. $fmtAllowedTypes = implode('" or "', $this->allowedTypes[$option]);
  656. $fmtProvidedTypes = implode('|', array_keys($invalidTypes));
  657. $allowedContainsArrayType = \count(array_filter(
  658. $this->allowedTypes[$option],
  659. function ($item) {
  660. return '[]' === substr(isset(self::$typeAliases[$item]) ? self::$typeAliases[$item] : $item, -2);
  661. }
  662. )) > 0;
  663. if (\is_array($value) && $allowedContainsArrayType) {
  664. 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, $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes));
  665. }
  666. throw new InvalidOptionsException(sprintf('The option "%s" with value %s is expected to be of type "%s", but is of type "%s".', $option, $fmtActualValue, $fmtAllowedTypes, $fmtProvidedTypes));
  667. }
  668. }
  669. // Validate the value of the resolved option
  670. if (isset($this->allowedValues[$option])) {
  671. $success = false;
  672. $printableAllowedValues = [];
  673. foreach ($this->allowedValues[$option] as $allowedValue) {
  674. if ($allowedValue instanceof \Closure) {
  675. if ($allowedValue($value)) {
  676. $success = true;
  677. break;
  678. }
  679. // Don't include closures in the exception message
  680. continue;
  681. }
  682. if ($value === $allowedValue) {
  683. $success = true;
  684. break;
  685. }
  686. $printableAllowedValues[] = $allowedValue;
  687. }
  688. if (!$success) {
  689. $message = sprintf(
  690. 'The option "%s" with value %s is invalid.',
  691. $option,
  692. $this->formatValue($value)
  693. );
  694. if (\count($printableAllowedValues) > 0) {
  695. $message .= sprintf(
  696. ' Accepted values are: %s.',
  697. $this->formatValues($printableAllowedValues)
  698. );
  699. }
  700. throw new InvalidOptionsException($message);
  701. }
  702. }
  703. // Normalize the validated option
  704. if (isset($this->normalizers[$option])) {
  705. // If the closure is already being called, we have a cyclic
  706. // dependency
  707. if (isset($this->calling[$option])) {
  708. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', array_keys($this->calling))));
  709. }
  710. $normalizer = $this->normalizers[$option];
  711. // The following section must be protected from cyclic
  712. // calls. Set $calling for the current $option to detect a cyclic
  713. // dependency
  714. // BEGIN
  715. $this->calling[$option] = true;
  716. try {
  717. $value = $normalizer($this, $value);
  718. } finally {
  719. unset($this->calling[$option]);
  720. }
  721. // END
  722. }
  723. // Mark as resolved
  724. $this->resolved[$option] = $value;
  725. return $value;
  726. }
  727. /**
  728. * @param string $type
  729. * @param mixed $value
  730. * @param array &$invalidTypes
  731. *
  732. * @return bool
  733. */
  734. private function verifyTypes($type, $value, array &$invalidTypes)
  735. {
  736. if (\is_array($value) && '[]' === substr($type, -2)) {
  737. return $this->verifyArrayType($type, $value, $invalidTypes);
  738. }
  739. if (self::isValueValidType($type, $value)) {
  740. return true;
  741. }
  742. if (!$invalidTypes) {
  743. $invalidTypes[$this->formatTypeOf($value, null)] = true;
  744. }
  745. return false;
  746. }
  747. /**
  748. * @return bool
  749. */
  750. private function verifyArrayType($type, array $value, array &$invalidTypes, $level = 0)
  751. {
  752. $type = substr($type, 0, -2);
  753. if ('[]' === substr($type, -2)) {
  754. $success = true;
  755. foreach ($value as $item) {
  756. if (!\is_array($item)) {
  757. $invalidTypes[$this->formatTypeOf($item, null)] = true;
  758. $success = false;
  759. } elseif (!$this->verifyArrayType($type, $item, $invalidTypes, $level + 1)) {
  760. $success = false;
  761. }
  762. }
  763. return $success;
  764. }
  765. $valid = true;
  766. foreach ($value as $item) {
  767. if (!self::isValueValidType($type, $item)) {
  768. $invalidTypes[$this->formatTypeOf($item, $type)] = $value;
  769. $valid = false;
  770. }
  771. }
  772. return $valid;
  773. }
  774. /**
  775. * Returns whether a resolved option with the given name exists.
  776. *
  777. * @param string $option The option name
  778. *
  779. * @return bool Whether the option is set
  780. *
  781. * @throws AccessException If accessing this method outside of {@link resolve()}
  782. *
  783. * @see \ArrayAccess::offsetExists()
  784. */
  785. public function offsetExists($option)
  786. {
  787. if (!$this->locked) {
  788. throw new AccessException('Array access is only supported within closures of lazy options and normalizers.');
  789. }
  790. return \array_key_exists($option, $this->defaults);
  791. }
  792. /**
  793. * Not supported.
  794. *
  795. * @throws AccessException
  796. */
  797. public function offsetSet($option, $value)
  798. {
  799. throw new AccessException('Setting options via array access is not supported. Use setDefault() instead.');
  800. }
  801. /**
  802. * Not supported.
  803. *
  804. * @throws AccessException
  805. */
  806. public function offsetUnset($option)
  807. {
  808. throw new AccessException('Removing options via array access is not supported. Use remove() instead.');
  809. }
  810. /**
  811. * Returns the number of set options.
  812. *
  813. * This may be only a subset of the defined options.
  814. *
  815. * @return int Number of options
  816. *
  817. * @throws AccessException If accessing this method outside of {@link resolve()}
  818. *
  819. * @see \Countable::count()
  820. */
  821. public function count()
  822. {
  823. if (!$this->locked) {
  824. throw new AccessException('Counting is only supported within closures of lazy options and normalizers.');
  825. }
  826. return \count($this->defaults);
  827. }
  828. /**
  829. * Returns a string representation of the type of the value.
  830. *
  831. * This method should be used if you pass the type of a value as
  832. * message parameter to a constraint violation. Note that such
  833. * parameters should usually not be included in messages aimed at
  834. * non-technical people.
  835. *
  836. * @param mixed $value The value to return the type of
  837. * @param string $type
  838. *
  839. * @return string The type of the value
  840. */
  841. private function formatTypeOf($value, $type)
  842. {
  843. $suffix = '';
  844. if ('[]' === substr($type, -2)) {
  845. $suffix = '[]';
  846. $type = substr($type, 0, -2);
  847. while ('[]' === substr($type, -2)) {
  848. $type = substr($type, 0, -2);
  849. $value = array_shift($value);
  850. if (!\is_array($value)) {
  851. break;
  852. }
  853. $suffix .= '[]';
  854. }
  855. if (\is_array($value)) {
  856. $subTypes = [];
  857. foreach ($value as $val) {
  858. $subTypes[$this->formatTypeOf($val, null)] = true;
  859. }
  860. return implode('|', array_keys($subTypes)).$suffix;
  861. }
  862. }
  863. return (\is_object($value) ? \get_class($value) : \gettype($value)).$suffix;
  864. }
  865. /**
  866. * Returns a string representation of the value.
  867. *
  868. * This method returns the equivalent PHP tokens for most scalar types
  869. * (i.e. "false" for false, "1" for 1 etc.). Strings are always wrapped
  870. * in double quotes (").
  871. *
  872. * @param mixed $value The value to format as string
  873. *
  874. * @return string The string representation of the passed value
  875. */
  876. private function formatValue($value)
  877. {
  878. if (\is_object($value)) {
  879. return \get_class($value);
  880. }
  881. if (\is_array($value)) {
  882. return 'array';
  883. }
  884. if (\is_string($value)) {
  885. return '"'.$value.'"';
  886. }
  887. if (\is_resource($value)) {
  888. return 'resource';
  889. }
  890. if (null === $value) {
  891. return 'null';
  892. }
  893. if (false === $value) {
  894. return 'false';
  895. }
  896. if (true === $value) {
  897. return 'true';
  898. }
  899. return (string) $value;
  900. }
  901. /**
  902. * Returns a string representation of a list of values.
  903. *
  904. * Each of the values is converted to a string using
  905. * {@link formatValue()}. The values are then concatenated with commas.
  906. *
  907. * @param array $values A list of values
  908. *
  909. * @return string The string representation of the value list
  910. *
  911. * @see formatValue()
  912. */
  913. private function formatValues(array $values)
  914. {
  915. foreach ($values as $key => $value) {
  916. $values[$key] = $this->formatValue($value);
  917. }
  918. return implode(', ', $values);
  919. }
  920. private static function isValueValidType($type, $value)
  921. {
  922. return (\function_exists($isFunction = 'is_'.$type) && $isFunction($value)) || $value instanceof $type;
  923. }
  924. }