PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/protected/extensions/doctrine/vendors/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php

https://bitbucket.org/NordLabs/yiidoctrine
PHP | 326 lines | 134 code | 41 blank | 151 comment | 24 complexity | 1c232966cba42f33bb98167396b0165f MD5 | raw file
Possible License(s): BSD-2-Clause, LGPL-2.1, BSD-3-Clause
  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 Symfony\Bridge\Doctrine\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\ArrayChoiceList;
  15. use Doctrine\ORM\EntityManager;
  16. use Doctrine\ORM\QueryBuilder;
  17. use Doctrine\ORM\NoResultException;
  18. class EntityChoiceList extends ArrayChoiceList
  19. {
  20. /**
  21. * @var Doctrine\ORM\EntityManager
  22. */
  23. private $em;
  24. /**
  25. * @var Doctrine\ORM\Mapping\ClassMetadata
  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 Collection
  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 $queryBuilder;
  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. /**
  66. * A cache for the UnitOfWork instance of Doctrine
  67. *
  68. * @var Doctrine\ORM\UnitOfWork
  69. */
  70. private $unitOfWork;
  71. private $propertyPath;
  72. /**
  73. * Constructor.
  74. *
  75. * @param EntityManager $em An EntityManager instance
  76. * @param string $class The class name
  77. * @param string $property The property name
  78. * @param QueryBuilder|\Closure $queryBuilder An optional query builder
  79. * @param array|\Closure $choices An array of choices or a function returning an array
  80. */
  81. public function __construct(EntityManager $em, $class, $property = null, $queryBuilder = null, $choices = null)
  82. {
  83. // If a query builder was passed, it must be a closure or QueryBuilder
  84. // instance
  85. if (!(null === $queryBuilder || $queryBuilder instanceof QueryBuilder || $queryBuilder instanceof \Closure)) {
  86. throw new UnexpectedTypeException($queryBuilder, 'Doctrine\ORM\QueryBuilder or \Closure');
  87. }
  88. if ($queryBuilder instanceof \Closure) {
  89. $queryBuilder = $queryBuilder($em->getRepository($class));
  90. if (!$queryBuilder instanceof QueryBuilder) {
  91. throw new UnexpectedTypeException($queryBuilder, 'Doctrine\ORM\QueryBuilder');
  92. }
  93. }
  94. $this->em = $em;
  95. $this->class = $class;
  96. $this->queryBuilder = $queryBuilder;
  97. $this->unitOfWork = $em->getUnitOfWork();
  98. $this->identifier = $em->getClassMetadata($class)->getIdentifierFieldNames();
  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. }
  104. if (!is_array($choices) && !$choices instanceof \Closure && !is_null($choices)) {
  105. throw new UnexpectedTypeException($choices, 'array or \Closure or null');
  106. }
  107. $this->choices = $choices;
  108. }
  109. /**
  110. * Initializes the choices and returns them.
  111. *
  112. * If the entities were passed in the "choices" option, this method
  113. * does not have any significant overhead. Otherwise, if a query builder
  114. * was passed in the "query_builder" option, this builder is now used
  115. * to construct a query which is executed. In the last case, all entities
  116. * for the underlying class are fetched from the repository.
  117. *
  118. * @return array An array of choices
  119. */
  120. protected function load()
  121. {
  122. parent::load();
  123. if (is_array($this->choices)) {
  124. $entities = $this->choices;
  125. } elseif ($qb = $this->queryBuilder) {
  126. $entities = $qb->getQuery()->execute();
  127. } else {
  128. $entities = $this->em->getRepository($this->class)->findAll();
  129. }
  130. $this->choices = array();
  131. $this->entities = array();
  132. $this->loadEntities($entities);
  133. return $this->choices;
  134. }
  135. /**
  136. * Converts entities into choices with support for groups.
  137. *
  138. * The choices are generated from the entities. If the entities have a
  139. * composite identifier, the choices are indexed using ascending integers.
  140. * Otherwise the identifiers are used as indices.
  141. *
  142. * If the option "property" was passed, the property path in that option
  143. * is used as option values. Otherwise this method tries to convert
  144. * objects to strings using __toString().
  145. *
  146. * @param array $entities An array of entities
  147. * @param string $group A group name
  148. */
  149. private function loadEntities($entities, $group = null)
  150. {
  151. foreach ($entities as $key => $entity) {
  152. if (is_array($entity)) {
  153. // Entities are in named groups
  154. $this->loadEntities($entity, $key);
  155. continue;
  156. }
  157. if ($this->propertyPath) {
  158. // If the property option was given, use it
  159. $value = $this->propertyPath->getValue($entity);
  160. } else {
  161. // Otherwise expect a __toString() method in the entity
  162. if (!method_exists($entity, '__toString')) {
  163. throw new FormException(sprintf('Entity "%s" passed to the choice field must have a "__toString()" method defined (or you can also override the "property" option).', $this->class));
  164. }
  165. $value = (string) $entity;
  166. }
  167. if (count($this->identifier) > 1) {
  168. // When the identifier consists of multiple field, use
  169. // naturally ordered keys to refer to the choices
  170. $id = $key;
  171. } else {
  172. // When the identifier is a single field, index choices by
  173. // entity ID for performance reasons
  174. $id = current($this->getIdentifierValues($entity));
  175. }
  176. if (null === $group) {
  177. // Flat list of choices
  178. $this->choices[$id] = $value;
  179. } else {
  180. // Nested choices
  181. $this->choices[$group][$id] = $value;
  182. }
  183. $this->entities[$id] = $entity;
  184. }
  185. }
  186. /**
  187. * Returns the fields of which the identifier of the underlying class consists.
  188. *
  189. * @return array
  190. */
  191. public function getIdentifier()
  192. {
  193. return $this->identifier;
  194. }
  195. /**
  196. * Returns the according entities for the choices.
  197. *
  198. * If the choices were not initialized, they are initialized now. This
  199. * is an expensive operation, except if the entities were passed in the
  200. * "choices" option.
  201. *
  202. * @return array An array of entities
  203. */
  204. public function getEntities()
  205. {
  206. if (!$this->loaded) {
  207. $this->load();
  208. }
  209. return $this->entities;
  210. }
  211. /**
  212. * Returns the entity for the given key.
  213. *
  214. * If the underlying entities have composite identifiers, the choices
  215. * are initialized. The key is expected to be the index in the choices
  216. * array in this case.
  217. *
  218. * If they have single identifiers, they are either fetched from the
  219. * internal entity cache (if filled) or loaded from the database.
  220. *
  221. * @param string $key The choice key (for entities with composite
  222. * identifiers) or entity ID (for entities with single
  223. * identifiers)
  224. *
  225. * @return object The matching entity
  226. */
  227. public function getEntity($key)
  228. {
  229. if (!$this->loaded) {
  230. $this->load();
  231. }
  232. try {
  233. if (count($this->identifier) > 1) {
  234. // $key is a collection index
  235. $entities = $this->getEntities();
  236. return isset($entities[$key]) ? $entities[$key] : null;
  237. } elseif ($this->entities) {
  238. return isset($this->entities[$key]) ? $this->entities[$key] : null;
  239. } elseif ($qb = $this->queryBuilder) {
  240. // should we clone the builder?
  241. $alias = $qb->getRootAlias();
  242. $where = $qb->expr()->eq($alias.'.'.current($this->identifier), $key);
  243. return $qb->andWhere($where)->getQuery()->getSingleResult();
  244. }
  245. return $this->em->find($this->class, $key);
  246. } catch (NoResultException $e) {
  247. return null;
  248. }
  249. }
  250. /**
  251. * Returns the \ReflectionProperty instance for a property of the underlying class.
  252. *
  253. * @param string $property The name of the property
  254. *
  255. * @return \ReflectionProperty The reflection instance
  256. */
  257. private function getReflProperty($property)
  258. {
  259. if (!isset($this->reflProperties[$property])) {
  260. $this->reflProperties[$property] = new \ReflectionProperty($this->class, $property);
  261. $this->reflProperties[$property]->setAccessible(true);
  262. }
  263. return $this->reflProperties[$property];
  264. }
  265. /**
  266. * Returns the values of the identifier fields of an entity.
  267. *
  268. * Doctrine must know about this entity, that is, the entity must already
  269. * be persisted or added to the identity map before. Otherwise an
  270. * exception is thrown.
  271. *
  272. * @param object $entity The entity for which to get the identifier
  273. *
  274. * @return array The identifier values
  275. *
  276. * @throws FormException If the entity does not exist in Doctrine's identity map
  277. */
  278. public function getIdentifierValues($entity)
  279. {
  280. if (!$this->unitOfWork->isInIdentityMap($entity)) {
  281. throw new FormException('Entities passed to the choice field must be managed');
  282. }
  283. return $this->unitOfWork->getEntityIdentifier($entity);
  284. }
  285. }