ModelChoiceList.php 9.1 KB

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