ModelChoiceList.php 8.9 KB

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