ModelChoiceList.php 8.2 KB

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