ModelChoiceList.php 9.4 KB

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