Options.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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\OptionDefinitionException;
  12. /**
  13. * Container for resolving inter-dependent options.
  14. *
  15. * @author Bernhard Schussek <bschussek@gmail.com>
  16. */
  17. class Options implements \ArrayAccess, \Iterator, \Countable
  18. {
  19. /**
  20. * A list of option values.
  21. * @var array
  22. */
  23. private $options = array();
  24. /**
  25. * A list of normalizer closures.
  26. * @var array
  27. */
  28. private $normalizers = array();
  29. /**
  30. * A list of closures for evaluating lazy options.
  31. * @var array
  32. */
  33. private $lazy = array();
  34. /**
  35. * A list containing the currently locked options.
  36. * @var array
  37. */
  38. private $lock = array();
  39. /**
  40. * Whether at least one option has already been read.
  41. *
  42. * Once read, the options cannot be changed anymore. This is
  43. * necessary in order to avoid inconsistencies during the resolving
  44. * process. If any option is changed after being read, all evaluated
  45. * lazy options that depend on this option would become invalid.
  46. *
  47. * @var Boolean
  48. */
  49. private $reading = false;
  50. /**
  51. * Sets the value of a given option.
  52. *
  53. * You can set lazy options by passing a closure with the following
  54. * signature:
  55. *
  56. * <code>
  57. * function (Options $options)
  58. * </code>
  59. *
  60. * This closure will be evaluated once the option is read using
  61. * {@link get()}. The closure has access to the resolved values of
  62. * other options through the passed {@link Options} instance.
  63. *
  64. * @param string $option The name of the option.
  65. * @param mixed $value The value of the option.
  66. *
  67. * @throws OptionDefinitionException If options have already been read.
  68. * Once options are read, the container
  69. * becomes immutable.
  70. */
  71. public function set($option, $value)
  72. {
  73. // Setting is not possible once an option is read, because then lazy
  74. // options could manipulate the state of the object, leading to
  75. // inconsistent results.
  76. if ($this->reading) {
  77. throw new OptionDefinitionException('Options cannot be set anymore once options have been read.');
  78. }
  79. // Setting is equivalent to overloading while discarding the previous
  80. // option value
  81. unset($this->options[$option]);
  82. unset($this->lazy[$option]);
  83. $this->overload($option, $value);
  84. }
  85. /**
  86. * Sets the normalizer for a given option.
  87. *
  88. * Normalizers should be closures with the following signature:
  89. *
  90. * <code>
  91. * function (Options $options, $value)
  92. * </code>
  93. *
  94. * This closure will be evaluated once the option is read using
  95. * {@link get()}. The closure has access to the resolved values of
  96. * other options through the passed {@link Options} instance.
  97. *
  98. * @param string $option The name of the option.
  99. * @param \Closure $normalizer The normalizer.
  100. *
  101. * @throws OptionDefinitionException If options have already been read.
  102. * Once options are read, the container
  103. * becomes immutable.
  104. */
  105. public function setNormalizer($option, \Closure $normalizer)
  106. {
  107. if ($this->reading) {
  108. throw new OptionDefinitionException('Normalizers cannot be added anymore once options have been read.');
  109. }
  110. $this->normalizers[$option] = $normalizer;
  111. }
  112. /**
  113. * Replaces the contents of the container with the given options.
  114. *
  115. * This method is a shortcut for {@link clear()} with subsequent
  116. * calls to {@link set()}.
  117. *
  118. * @param array $options The options to set.
  119. *
  120. * @throws OptionDefinitionException If options have already been read.
  121. * Once options are read, the container
  122. * becomes immutable.
  123. */
  124. public function replace(array $options)
  125. {
  126. if ($this->reading) {
  127. throw new OptionDefinitionException('Options cannot be replaced anymore once options have been read.');
  128. }
  129. $this->options = array();
  130. $this->lazy = array();
  131. $this->normalizers = array();
  132. foreach ($options as $option => $value) {
  133. $this->overload($option, $value);
  134. }
  135. }
  136. /**
  137. * Overloads the value of a given option.
  138. *
  139. * Contrary to {@link set()}, this method keeps the previous default
  140. * value of the option so that you can access it if you pass a closure.
  141. * Passed closures should have the following signature:
  142. *
  143. * <code>
  144. * function (Options $options, $value)
  145. * </code>
  146. *
  147. * The second parameter passed to the closure is the current default
  148. * value of the option.
  149. *
  150. * @param string $option The option name.
  151. * @param mixed $value The option value.
  152. *
  153. * @throws OptionDefinitionException If options have already been read.
  154. * Once options are read, the container
  155. * becomes immutable.
  156. */
  157. public function overload($option, $value)
  158. {
  159. if ($this->reading) {
  160. throw new OptionDefinitionException('Options cannot be overloaded anymore once options have been read.');
  161. }
  162. // If an option is a closure that should be evaluated lazily, store it
  163. // in the "lazy" property.
  164. if ($value instanceof \Closure) {
  165. $reflClosure = new \ReflectionFunction($value);
  166. $params = $reflClosure->getParameters();
  167. if (isset($params[0]) && null !== ($class = $params[0]->getClass()) && __CLASS__ === $class->name) {
  168. // Initialize the option if no previous value exists
  169. if (!isset($this->options[$option])) {
  170. $this->options[$option] = null;
  171. }
  172. // Ignore previous lazy options if the closure has no second parameter
  173. if (!isset($this->lazy[$option]) || !isset($params[1])) {
  174. $this->lazy[$option] = array();
  175. }
  176. // Store closure for later evaluation
  177. $this->lazy[$option][] = $value;
  178. return;
  179. }
  180. }
  181. // Remove lazy options by default
  182. unset($this->lazy[$option]);
  183. $this->options[$option] = $value;
  184. }
  185. /**
  186. * Returns the value of the given option.
  187. *
  188. * If the option was a lazy option, it is evaluated now.
  189. *
  190. * @param string $option The option name.
  191. *
  192. * @return mixed The option value.
  193. *
  194. * @throws \OutOfBoundsException If the option does not exist.
  195. * @throws OptionDefinitionException If a cyclic dependency is detected
  196. * between two lazy options.
  197. */
  198. public function get($option)
  199. {
  200. $this->reading = true;
  201. if (!array_key_exists($option, $this->options)) {
  202. throw new \OutOfBoundsException(sprintf('The option "%s" does not exist.', $option));
  203. }
  204. if (isset($this->lazy[$option])) {
  205. $this->resolve($option);
  206. }
  207. if (isset($this->normalizers[$option])) {
  208. $this->normalize($option);
  209. }
  210. return $this->options[$option];
  211. }
  212. /**
  213. * Returns whether the given option exists.
  214. *
  215. * @param string $option The option name.
  216. *
  217. * @return Boolean Whether the option exists.
  218. */
  219. public function has($option)
  220. {
  221. return array_key_exists($option, $this->options);
  222. }
  223. /**
  224. * Removes the option with the given name.
  225. *
  226. * @param string $option The option name.
  227. *
  228. * @throws OptionDefinitionException If options have already been read.
  229. * Once options are read, the container
  230. * becomes immutable.
  231. */
  232. public function remove($option)
  233. {
  234. if ($this->reading) {
  235. throw new OptionDefinitionException('Options cannot be removed anymore once options have been read.');
  236. }
  237. unset($this->options[$option]);
  238. unset($this->lazy[$option]);
  239. unset($this->normalizers[$option]);
  240. }
  241. /**
  242. * Removes all options.
  243. *
  244. * @throws OptionDefinitionException If options have already been read.
  245. * Once options are read, the container
  246. * becomes immutable.
  247. */
  248. public function clear()
  249. {
  250. if ($this->reading) {
  251. throw new OptionDefinitionException('Options cannot be cleared anymore once options have been read.');
  252. }
  253. $this->options = array();
  254. $this->lazy = array();
  255. $this->normalizers = array();
  256. }
  257. /**
  258. * Returns the values of all options.
  259. *
  260. * Lazy options are evaluated at this point.
  261. *
  262. * @return array The option values.
  263. */
  264. public function all()
  265. {
  266. $this->reading = true;
  267. // Performance-wise this is slightly better than
  268. // while (null !== $option = key($this->lazy))
  269. foreach ($this->lazy as $option => $closures) {
  270. // Double check, in case the option has already been resolved
  271. // by cascade in the previous cycles
  272. if (isset($this->lazy[$option])) {
  273. $this->resolve($option);
  274. }
  275. }
  276. foreach ($this->normalizers as $option => $normalizer) {
  277. if (isset($this->normalizers[$option])) {
  278. $this->normalize($option);
  279. }
  280. }
  281. return $this->options;
  282. }
  283. /**
  284. * Equivalent to {@link has()}.
  285. *
  286. * @param string $option The option name.
  287. *
  288. * @return Boolean Whether the option exists.
  289. *
  290. * @see \ArrayAccess::offsetExists()
  291. */
  292. public function offsetExists($option)
  293. {
  294. return $this->has($option);
  295. }
  296. /**
  297. * Equivalent to {@link get()}.
  298. *
  299. * @param string $option The option name.
  300. *
  301. * @return mixed The option value.
  302. *
  303. * @throws \OutOfBoundsException If the option does not exist.
  304. * @throws OptionDefinitionException If a cyclic dependency is detected
  305. * between two lazy options.
  306. *
  307. * @see \ArrayAccess::offsetGet()
  308. */
  309. public function offsetGet($option)
  310. {
  311. return $this->get($option);
  312. }
  313. /**
  314. * Equivalent to {@link set()}.
  315. *
  316. * @param string $option The name of the option.
  317. * @param mixed $value The value of the option. May be a closure with a
  318. * signature as defined in DefaultOptions::add().
  319. *
  320. * @throws OptionDefinitionException If options have already been read.
  321. * Once options are read, the container
  322. * becomes immutable.
  323. *
  324. * @see \ArrayAccess::offsetSet()
  325. */
  326. public function offsetSet($option, $value)
  327. {
  328. $this->set($option, $value);
  329. }
  330. /**
  331. * Equivalent to {@link remove()}.
  332. *
  333. * @param string $option The option name.
  334. *
  335. * @throws OptionDefinitionException If options have already been read.
  336. * Once options are read, the container
  337. * becomes immutable.
  338. *
  339. * @see \ArrayAccess::offsetUnset()
  340. */
  341. public function offsetUnset($option)
  342. {
  343. $this->remove($option);
  344. }
  345. /**
  346. * {@inheritdoc}
  347. */
  348. public function current()
  349. {
  350. return $this->get($this->key());
  351. }
  352. /**
  353. * {@inheritdoc}
  354. */
  355. public function next()
  356. {
  357. next($this->options);
  358. }
  359. /**
  360. * {@inheritdoc}
  361. */
  362. public function key()
  363. {
  364. return key($this->options);
  365. }
  366. /**
  367. * {@inheritdoc}
  368. */
  369. public function valid()
  370. {
  371. return null !== $this->key();
  372. }
  373. /**
  374. * {@inheritdoc}
  375. */
  376. public function rewind()
  377. {
  378. reset($this->options);
  379. }
  380. /**
  381. * {@inheritdoc}
  382. */
  383. public function count()
  384. {
  385. return count($this->options);
  386. }
  387. /**
  388. * Evaluates the given lazy option.
  389. *
  390. * The evaluated value is written into the options array. The closure for
  391. * evaluating the option is discarded afterwards.
  392. *
  393. * @param string $option The option to evaluate.
  394. *
  395. * @throws OptionDefinitionException If the option has a cyclic dependency
  396. * on another option.
  397. */
  398. private function resolve($option)
  399. {
  400. // The code duplication with normalize() exists for performance
  401. // reasons, in order to save a method call.
  402. // Remember that this method is potentially called a couple of thousand
  403. // times and needs to be as efficient as possible.
  404. if (isset($this->lock[$option])) {
  405. $conflicts = array();
  406. foreach ($this->lock as $option => $locked) {
  407. if ($locked) {
  408. $conflicts[] = $option;
  409. }
  410. }
  411. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', $conflicts)));
  412. }
  413. $this->lock[$option] = true;
  414. foreach ($this->lazy[$option] as $closure) {
  415. $this->options[$option] = $closure($this, $this->options[$option]);
  416. }
  417. unset($this->lock[$option]);
  418. // The option now isn't lazy anymore
  419. unset($this->lazy[$option]);
  420. }
  421. /**
  422. * Normalizes the given option.
  423. *
  424. * The evaluated value is written into the options array.
  425. *
  426. * @param string $option The option to normalizer.
  427. *
  428. * @throws OptionDefinitionException If the option has a cyclic dependency
  429. * on another option.
  430. */
  431. private function normalize($option)
  432. {
  433. // The code duplication with resolve() exists for performance
  434. // reasons, in order to save a method call.
  435. // Remember that this method is potentially called a couple of thousand
  436. // times and needs to be as efficient as possible.
  437. if (isset($this->lock[$option])) {
  438. $conflicts = array();
  439. foreach ($this->lock as $option => $locked) {
  440. if ($locked) {
  441. $conflicts[] = $option;
  442. }
  443. }
  444. throw new OptionDefinitionException(sprintf('The options "%s" have a cyclic dependency.', implode('", "', $conflicts)));
  445. }
  446. /** @var \Closure $normalizer */
  447. $normalizer = $this->normalizers[$option];
  448. $this->lock[$option] = true;
  449. $this->options[$option] = $normalizer($this, array_key_exists($option, $this->options) ? $this->options[$option] : null);
  450. unset($this->lock[$option]);
  451. // The option is now normalized
  452. unset($this->normalizers[$option]);
  453. }
  454. }