ArrayChoiceList.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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\Form\ChoiceList;
  11. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  12. /**
  13. * A list of choices with arbitrary data types.
  14. *
  15. * The user of this class is responsible for assigning string values to the
  16. * choices. Both the choices and their values are passed to the constructor.
  17. * Each choice must have a corresponding value (with the same array key) in
  18. * the value array.
  19. *
  20. * @author Bernhard Schussek <bschussek@gmail.com>
  21. */
  22. class ArrayChoiceList implements ChoiceListInterface
  23. {
  24. /**
  25. * The choices in the list.
  26. *
  27. * @var array
  28. */
  29. protected $choices;
  30. /**
  31. * The values indexed by the original keys.
  32. *
  33. * @var array
  34. */
  35. protected $structuredValues;
  36. /**
  37. * The original keys of the choices array.
  38. *
  39. * @var int[]|string[]
  40. */
  41. protected $originalKeys;
  42. /**
  43. * The callback for creating the value for a choice.
  44. *
  45. * @var callable
  46. */
  47. protected $valueCallback;
  48. /**
  49. * Creates a list with the given choices and values.
  50. *
  51. * The given choice array must have the same array keys as the value array.
  52. *
  53. * @param iterable $choices The selectable choices
  54. * @param callable|null $value The callable for creating the value
  55. * for a choice. If `null` is passed,
  56. * incrementing integers are used as
  57. * values
  58. */
  59. public function __construct($choices, $value = null)
  60. {
  61. if (null !== $value && !\is_callable($value)) {
  62. throw new UnexpectedTypeException($value, 'null or callable');
  63. }
  64. if ($choices instanceof \Traversable) {
  65. $choices = iterator_to_array($choices);
  66. }
  67. if (null === $value && $this->castableToString($choices)) {
  68. $value = function ($choice) {
  69. return false === $choice ? '0' : (string) $choice;
  70. };
  71. }
  72. if (null !== $value) {
  73. // If a deterministic value generator was passed, use it later
  74. $this->valueCallback = $value;
  75. } else {
  76. // Otherwise simply generate incrementing integers as values
  77. $i = 0;
  78. $value = function () use (&$i) {
  79. return $i++;
  80. };
  81. }
  82. // If the choices are given as recursive array (i.e. with explicit
  83. // choice groups), flatten the array. The grouping information is needed
  84. // in the view only.
  85. $this->flatten($choices, $value, $choicesByValues, $keysByValues, $structuredValues);
  86. $this->choices = $choicesByValues;
  87. $this->originalKeys = $keysByValues;
  88. $this->structuredValues = $structuredValues;
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function getChoices()
  94. {
  95. return $this->choices;
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. public function getValues()
  101. {
  102. return array_map('strval', array_keys($this->choices));
  103. }
  104. /**
  105. * {@inheritdoc}
  106. */
  107. public function getStructuredValues()
  108. {
  109. return $this->structuredValues;
  110. }
  111. /**
  112. * {@inheritdoc}
  113. */
  114. public function getOriginalKeys()
  115. {
  116. return $this->originalKeys;
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function getChoicesForValues(array $values)
  122. {
  123. $choices = array();
  124. foreach ($values as $i => $givenValue) {
  125. if (array_key_exists($givenValue, $this->choices)) {
  126. $choices[$i] = $this->choices[$givenValue];
  127. }
  128. }
  129. return $choices;
  130. }
  131. /**
  132. * {@inheritdoc}
  133. */
  134. public function getValuesForChoices(array $choices)
  135. {
  136. $values = array();
  137. // Use the value callback to compare choices by their values, if present
  138. if ($this->valueCallback) {
  139. $givenValues = array();
  140. foreach ($choices as $i => $givenChoice) {
  141. $givenValues[$i] = (string) \call_user_func($this->valueCallback, $givenChoice);
  142. }
  143. return array_intersect($givenValues, array_keys($this->choices));
  144. }
  145. // Otherwise compare choices by identity
  146. foreach ($choices as $i => $givenChoice) {
  147. foreach ($this->choices as $value => $choice) {
  148. if ($choice === $givenChoice) {
  149. $values[$i] = (string) $value;
  150. break;
  151. }
  152. }
  153. }
  154. return $values;
  155. }
  156. /**
  157. * Flattens an array into the given output variables.
  158. *
  159. * @param array $choices The array to flatten
  160. * @param callable $value The callable for generating choice values
  161. * @param array $choicesByValues The flattened choices indexed by the
  162. * corresponding values
  163. * @param array $keysByValues The original keys indexed by the
  164. * corresponding values
  165. * @param array $structuredValues The values indexed by the original keys
  166. *
  167. * @internal Must not be used by user-land code
  168. */
  169. protected function flatten(array $choices, $value, &$choicesByValues, &$keysByValues, &$structuredValues)
  170. {
  171. if (null === $choicesByValues) {
  172. $choicesByValues = array();
  173. $keysByValues = array();
  174. $structuredValues = array();
  175. }
  176. foreach ($choices as $key => $choice) {
  177. if (\is_array($choice)) {
  178. $this->flatten($choice, $value, $choicesByValues, $keysByValues, $structuredValues[$key]);
  179. continue;
  180. }
  181. $choiceValue = (string) \call_user_func($value, $choice);
  182. $choicesByValues[$choiceValue] = $choice;
  183. $keysByValues[$choiceValue] = $key;
  184. $structuredValues[$key] = $choiceValue;
  185. }
  186. }
  187. /**
  188. * Checks whether the given choices can be cast to strings without
  189. * generating duplicates.
  190. *
  191. * @param array $choices The choices
  192. * @param array|null $cache The cache for previously checked entries. Internal
  193. *
  194. * @return bool returns true if the choices can be cast to strings and
  195. * false otherwise
  196. */
  197. private function castableToString(array $choices, array &$cache = array())
  198. {
  199. foreach ($choices as $choice) {
  200. if (\is_array($choice)) {
  201. if (!$this->castableToString($choice, $cache)) {
  202. return false;
  203. }
  204. continue;
  205. } elseif (!is_scalar($choice)) {
  206. return false;
  207. }
  208. $choice = false === $choice ? '0' : (string) $choice;
  209. if (isset($cache[$choice])) {
  210. return false;
  211. }
  212. $cache[$choice] = true;
  213. }
  214. return true;
  215. }
  216. }