/src/Symfony/Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.php

https://github.com/aderuwe/symfony · PHP · 184 lines · 73 code · 21 blank · 90 comment · 8 complexity · b3c420587ca03303c558f9f021a5c6a0 MD5 · raw file

  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\Extension\Core\ChoiceList;
  11. use Symfony\Component\Form\Exception\StringCastException;
  12. use Symfony\Component\Form\Exception\InvalidArgumentException;
  13. use Symfony\Component\PropertyAccess\PropertyPath;
  14. use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
  15. use Symfony\Component\PropertyAccess\PropertyAccess;
  16. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  17. /**
  18. * A choice list for object choices.
  19. *
  20. * Supports generation of choice labels, choice groups and choice values
  21. * by calling getters of the object (or associated objects).
  22. *
  23. * <code>
  24. * $choices = array($user1, $user2);
  25. *
  26. * // call getName() to determine the choice labels
  27. * $choiceList = new ObjectChoiceList($choices, 'name');
  28. * </code>
  29. *
  30. * @author Bernhard Schussek <bschussek@gmail.com>
  31. */
  32. class ObjectChoiceList extends ChoiceList
  33. {
  34. /**
  35. * @var PropertyAccessorInterface
  36. */
  37. private $propertyAccessor;
  38. /**
  39. * The property path used to obtain the choice label.
  40. *
  41. * @var PropertyPath
  42. */
  43. private $labelPath;
  44. /**
  45. * The property path used for object grouping.
  46. *
  47. * @var PropertyPath
  48. */
  49. private $groupPath;
  50. /**
  51. * The property path used to obtain the choice value.
  52. *
  53. * @var PropertyPath
  54. */
  55. private $valuePath;
  56. /**
  57. * Creates a new object choice list.
  58. *
  59. * @param array|\Traversable $choices The array of choices. Choices may also be given
  60. * as hierarchy of unlimited depth by creating nested
  61. * arrays. The title of the sub-hierarchy can be
  62. * stored in the array key pointing to the nested
  63. * array. The topmost level of the hierarchy may also
  64. * be a \Traversable.
  65. * @param string $labelPath A property path pointing to the property used
  66. * for the choice labels. The value is obtained
  67. * by calling the getter on the object. If the
  68. * path is NULL, the object's __toString() method
  69. * is used instead.
  70. * @param array $preferredChoices A flat array of choices that should be
  71. * presented to the user with priority.
  72. * @param string $groupPath A property path pointing to the property used
  73. * to group the choices. Only allowed if
  74. * the choices are given as flat array.
  75. * @param string $valuePath A property path pointing to the property used
  76. * for the choice values. If not given, integers
  77. * are generated instead.
  78. * @param PropertyAccessorInterface $propertyAccessor The reflection graph for reading property paths.
  79. */
  80. public function __construct($choices, $labelPath = null, array $preferredChoices = array(), $groupPath = null, $valuePath = null, PropertyAccessorInterface $propertyAccessor = null)
  81. {
  82. $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  83. $this->labelPath = null !== $labelPath ? new PropertyPath($labelPath) : null;
  84. $this->groupPath = null !== $groupPath ? new PropertyPath($groupPath) : null;
  85. $this->valuePath = null !== $valuePath ? new PropertyPath($valuePath) : null;
  86. parent::__construct($choices, array(), $preferredChoices);
  87. }
  88. /**
  89. * Initializes the list with choices.
  90. *
  91. * Safe to be called multiple times. The list is cleared on every call.
  92. *
  93. * @param array|\Traversable $choices The choices to write into the list.
  94. * @param array $labels Ignored.
  95. * @param array $preferredChoices The choices to display with priority.
  96. *
  97. * @throws InvalidArgumentException When passing a hierarchy of choices and using
  98. * the "groupPath" option at the same time.
  99. */
  100. protected function initialize($choices, array $labels, array $preferredChoices)
  101. {
  102. if (null !== $this->groupPath) {
  103. $groupedChoices = array();
  104. foreach ($choices as $i => $choice) {
  105. if (is_array($choice)) {
  106. throw new InvalidArgumentException('You should pass a plain object array (without groups) when using the "groupPath" option.');
  107. }
  108. try {
  109. $group = $this->propertyAccessor->getValue($choice, $this->groupPath);
  110. } catch (NoSuchPropertyException $e) {
  111. // Don't group items whose group property does not exist
  112. // see https://github.com/symfony/symfony/commit/d9b7abb7c7a0f28e0ce970afc5e305dce5dccddf
  113. $group = null;
  114. }
  115. if (null === $group) {
  116. $groupedChoices[$i] = $choice;
  117. } else {
  118. if (!isset($groupedChoices[$group])) {
  119. $groupedChoices[$group] = array();
  120. }
  121. $groupedChoices[$group][$i] = $choice;
  122. }
  123. }
  124. $choices = $groupedChoices;
  125. }
  126. $labels = array();
  127. $this->extractLabels($choices, $labels);
  128. parent::initialize($choices, $labels, $preferredChoices);
  129. }
  130. /**
  131. * Creates a new unique value for this choice.
  132. *
  133. * If a property path for the value was given at object creation,
  134. * the getter behind that path is now called to obtain a new value.
  135. * Otherwise a new integer is generated.
  136. *
  137. * @param mixed $choice The choice to create a value for
  138. *
  139. * @return integer|string A unique value without character limitations.
  140. */
  141. protected function createValue($choice)
  142. {
  143. if ($this->valuePath) {
  144. return (string) $this->propertyAccessor->getValue($choice, $this->valuePath);
  145. }
  146. return parent::createValue($choice);
  147. }
  148. private function extractLabels($choices, array &$labels)
  149. {
  150. foreach ($choices as $i => $choice) {
  151. if (is_array($choice)) {
  152. $labels[$i] = array();
  153. $this->extractLabels($choice, $labels[$i]);
  154. } elseif ($this->labelPath) {
  155. $labels[$i] = $this->propertyAccessor->getValue($choice, $this->labelPath);
  156. } elseif (method_exists($choice, '__toString')) {
  157. $labels[$i] = (string) $choice;
  158. } else {
  159. throw new StringCastException(sprintf('A "__toString()" method was not found on the objects of type "%s" passed to the choice field. To read a custom getter instead, set the argument $labelPath to the desired property path.', get_class($choice)));
  160. }
  161. }
  162. }
  163. }