ModelChoiceList.php 8.7 KB

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