ModelChoiceList.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 Sonata\AdminBundle\Form\ChoiceList;
  11. use Doctrine\Common\Util\ClassUtils;
  12. use Symfony\Component\PropertyAccess\PropertyAccess;
  13. use Symfony\Component\PropertyAccess\PropertyPath;
  14. use Symfony\Component\Form\Exception\InvalidArgumentException;
  15. use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
  16. use Sonata\AdminBundle\Model\ModelManagerInterface;
  17. class ModelChoiceList extends SimpleChoiceList
  18. {
  19. /**
  20. * @var \Sonata\AdminBundle\Model\ModelManagerInterface
  21. */
  22. private $modelManager;
  23. /**
  24. * @var string
  25. */
  26. private $class;
  27. /**
  28. * The entities from which the user can choose
  29. *
  30. * This array is either indexed by ID (if the ID is a single field)
  31. * or by key in the choices array (if the ID consists of multiple fields)
  32. *
  33. * This property is initialized by initializeChoices(). It should only
  34. * be accessed through getEntity() and getEntities().
  35. *
  36. * @var mixed
  37. */
  38. private $entities = array();
  39. /**
  40. * Contains the query builder that builds the query for fetching the
  41. * entities
  42. *
  43. * This property should only be accessed through queryBuilder.
  44. *
  45. * @var \Doctrine\ORM\QueryBuilder
  46. */
  47. private $query;
  48. /**
  49. * The fields of which the identifier of the underlying class consists
  50. *
  51. * This property should only be accessed through identifier.
  52. *
  53. * @var array
  54. */
  55. private $identifier = array();
  56. /**
  57. * A cache for \ReflectionProperty instances for the underlying class
  58. *
  59. * This property should only be accessed through getReflProperty().
  60. *
  61. * @var array
  62. */
  63. private $reflProperties = array();
  64. private $propertyPath;
  65. /**
  66. * @param ModelManagerInterface $modelManager
  67. * @param string $class
  68. * @param null $property
  69. * @param null $query
  70. * @param array $choices
  71. */
  72. public function __construct(ModelManagerInterface $modelManager, $class, $property = null, $query = null, $choices = array())
  73. {
  74. $this->modelManager = $modelManager;
  75. $this->class = $class;
  76. $this->query = $query;
  77. $this->identifier = $this->modelManager->getIdentifierFieldNames($this->class);
  78. // The property option defines, which property (path) is used for
  79. // displaying entities as strings
  80. if ($property) {
  81. $this->propertyPath = new PropertyPath($property);
  82. }
  83. parent::__construct($this->load($choices));
  84. }
  85. /**
  86. * Initializes the choices and returns them
  87. *
  88. * The choices are generated from the entities. If the entities have a
  89. * composite identifier, the choices are indexed using ascending integers.
  90. * Otherwise the identifiers are used as indices.
  91. *
  92. * If the entities were passed in the "choices" option, this method
  93. * does not have any significant overhead. Otherwise, if a query builder
  94. * was passed in the "query" option, this builder is now used to construct
  95. * a query which is executed. In the last case, all entities for the
  96. * underlying class are fetched from the repository.
  97. *
  98. * If the option "property" was passed, the property path in that option
  99. * is used as option values. Otherwise this method tries to convert
  100. * objects to strings using __toString().
  101. *
  102. * @param $choices
  103. *
  104. * @return array An array of choices
  105. */
  106. protected function load($choices)
  107. {
  108. if (is_array($choices)) {
  109. $entities = $choices;
  110. } elseif ($this->query) {
  111. $entities = $this->modelManager->executeQuery($this->query);
  112. } else {
  113. $entities = $this->modelManager->findBy($this->class);
  114. }
  115. $choices = array();
  116. $this->entities = array();
  117. foreach ($entities as $key => $entity) {
  118. if ($this->propertyPath) {
  119. // If the property option was given, use it
  120. $propertyAccessor = PropertyAccess::getPropertyAccessor();
  121. $value = $propertyAccessor->getValue($entity, $this->propertyPath);
  122. } else {
  123. // Otherwise expect a __toString() method in the entity
  124. $value = (string) $entity;
  125. }
  126. if (count($this->identifier) > 1) {
  127. // When the identifier consists of multiple field, use
  128. // naturally ordered keys to refer to the choices
  129. $choices[$key] = $value;
  130. $this->entities[$key] = $entity;
  131. } else {
  132. // When the identifier is a single field, index choices by
  133. // entity ID for performance reasons
  134. $id = current($this->getIdentifierValues($entity));
  135. $choices[$id] = $value;
  136. $this->entities[$id] = $entity;
  137. }
  138. }
  139. return $choices;
  140. }
  141. /**
  142. * @return array
  143. */
  144. public function getIdentifier()
  145. {
  146. return $this->identifier;
  147. }
  148. /**
  149. * Returns the according entities for the choices
  150. *
  151. * If the choices were not initialized, they are initialized now. This
  152. * is an expensive operation, except if the entities were passed in the
  153. * "choices" option.
  154. *
  155. * @return array An array of entities
  156. */
  157. public function getEntities()
  158. {
  159. return $this->entities;
  160. }
  161. /**
  162. * Returns the entity for the given key
  163. *
  164. * If the underlying entities have composite identifiers, the choices
  165. * are initialized. The key is expected to be the index in the choices
  166. * array in this case.
  167. *
  168. * If they have single identifiers, they are either fetched from the
  169. * internal entity cache (if filled) or loaded from the database.
  170. *
  171. * @param string $key The choice key (for entities with composite
  172. * identifiers) or entity ID (for entities with single
  173. * identifiers)
  174. * @return object The matching entity
  175. */
  176. public function getEntity($key)
  177. {
  178. if (count($this->identifier) > 1) {
  179. // $key is a collection index
  180. $entities = $this->getEntities();
  181. return isset($entities[$key]) ? $entities[$key] : null;
  182. } elseif ($this->entities) {
  183. return isset($this->entities[$key]) ? $this->entities[$key] : null;
  184. }
  185. return $this->modelManager->find($this->class, $key);
  186. }
  187. /**
  188. * Returns the \ReflectionProperty instance for a property of the
  189. * underlying class
  190. *
  191. * @param string $property The name of the property
  192. *
  193. * @return \ReflectionProperty The reflection instance
  194. */
  195. private function getReflProperty($property)
  196. {
  197. if (!isset($this->reflProperties[$property])) {
  198. $this->reflProperties[$property] = new \ReflectionProperty($this->class, $property);
  199. $this->reflProperties[$property]->setAccessible(true);
  200. }
  201. return $this->reflProperties[$property];
  202. }
  203. /**
  204. * Returns the values of the identifier fields of an entity
  205. *
  206. * Doctrine must know about this entity, that is, the entity must already
  207. * be persisted or added to the identity map before. Otherwise an
  208. * exception is thrown.
  209. *
  210. * @param object $entity The entity for which to get the identifier
  211. * @throws InvalidArgumentException If the entity does not exist in Doctrine's
  212. * identity map
  213. * @return array
  214. */
  215. public function getIdentifierValues($entity)
  216. {
  217. try {
  218. return $this->modelManager->getIdentifierValues($entity);
  219. } catch (\Exception $e) {
  220. throw new InvalidArgumentException(sprintf("Unable to retrieve the identifier values for entity %s", ClassUtils::getClass($entity)), 0, $e);
  221. }
  222. }
  223. /**
  224. * @return \Sonata\AdminBundle\Model\ModelManagerInterface
  225. */
  226. public function getModelManager()
  227. {
  228. return $this->modelManager;
  229. }
  230. /**
  231. * @return string
  232. */
  233. public function getClass()
  234. {
  235. return $this->class;
  236. }
  237. }