ModelManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. <?php
  2. /*
  3. * This file is part of the Sonata 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\Model\ORM;
  11. use Sonata\AdminBundle\Model\ModelManagerInterface;
  12. use Sonata\AdminBundle\Admin\ORM\FieldDescription;
  13. use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
  14. use Sonata\AdminBundle\Datagrid\DatagridInterface;
  15. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  16. use Doctrine\ORM\EntityManager;
  17. use Doctrine\ORM\QueryBuilder;
  18. use Symfony\Component\Form\Exception\PropertyAccessDeniedException;
  19. class ModelManager implements ModelManagerInterface
  20. {
  21. protected $entityManager;
  22. /**
  23. *
  24. * @param \Doctrine\ORM\EntityManager $entityManager
  25. */
  26. public function __construct(EntityManager $entityManager)
  27. {
  28. $this->entityManager = $entityManager;
  29. }
  30. /**
  31. * Returns the related model's metadata
  32. *
  33. * @abstract
  34. * @param string $name
  35. * @return \Doctrine\ORM\Mapping\ClassMetadataInfo
  36. */
  37. public function getMetadata($class)
  38. {
  39. return $this->entityManager->getMetadataFactory()->getMetadataFor($class);
  40. }
  41. /**
  42. * Returns true is the model has some metadata
  43. *
  44. * @return boolean
  45. */
  46. public function hasMetadata($class)
  47. {
  48. return $this->entityManager->getMetadataFactory()->hasMetadataFor($class);
  49. }
  50. /**
  51. * Returns a new FieldDescription
  52. *
  53. * @abstract
  54. * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
  55. */
  56. public function getNewFieldDescriptionInstance($class, $name, array $options = array())
  57. {
  58. $metadata = $this->getMetadata($class);
  59. $fieldDescription = new FieldDescription;
  60. $fieldDescription->setName($name);
  61. $fieldDescription->setOptions($options);
  62. if (isset($metadata->associationMappings[$name])) {
  63. $fieldDescription->setAssociationMapping($metadata->associationMappings[$name]);
  64. }
  65. if (isset($metadata->fieldMappings[$name])) {
  66. $fieldDescription->setFieldMapping($metadata->fieldMappings[$name]);
  67. }
  68. return $fieldDescription;
  69. }
  70. public function create($object)
  71. {
  72. $this->entityManager->persist($object);
  73. $this->entityManager->flush();
  74. }
  75. public function update($object)
  76. {
  77. $this->entityManager->persist($object);
  78. $this->entityManager->flush();
  79. }
  80. public function delete($object)
  81. {
  82. $this->entityManager->remove($object);
  83. $this->entityManager->flush();
  84. }
  85. /**
  86. * Find one object from the given class repository.
  87. *
  88. * @param string $class Class name
  89. * @param string|int $id Identifier. Can be a string with several IDs concatenated, separated by '-'.
  90. * @return Object
  91. */
  92. public function findOne($class, $id)
  93. {
  94. $values = array_combine($this->getIdentifierFieldNames($class), explode('-', $id));
  95. return $this->entityManager->getRepository($class)->find($values);
  96. }
  97. public function find($class, array $criteria = array())
  98. {
  99. return $this->entityManager->getRepository($class)->findBy($criteria);
  100. }
  101. /**
  102. * @return \Doctrine\ORM\EntityManager
  103. */
  104. public function getEntityManager()
  105. {
  106. return $this->entityManager;
  107. }
  108. /**
  109. * @param string $parentAssociationMapping
  110. * @param string $class
  111. * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
  112. */
  113. public function getParentFieldDescription($parentAssociationMapping, $class)
  114. {
  115. $fieldName = $parentAssociationMapping['fieldName'];
  116. $metadata = $this->getMetadata($class);
  117. $associatingMapping = $metadata->associationMappings[$parentAssociationMapping];
  118. $fieldDescription = $this->getNewFieldDescriptionInstance($class, $fieldName);
  119. $fieldDescription->setName($parentAssociationMapping);
  120. $fieldDescription->setAssociationMapping($associatingMapping);
  121. return $fieldDescription;
  122. }
  123. /**
  124. * @param string $alias
  125. * @return \Doctrine\ORM\QueryBuilder a query instance
  126. */
  127. public function createQuery($class, $alias = 'o')
  128. {
  129. $repository = $this->getEntityManager()->getRepository($class);
  130. return $repository->createQueryBuilder($alias);
  131. }
  132. public function executeQuery($query)
  133. {
  134. if ($query instanceof QueryBuilder) {
  135. return $query->getQuery()->execute();
  136. }
  137. return $query->execute();
  138. }
  139. /**
  140. * @param string $class
  141. * @return string
  142. */
  143. public function getModelIdentifier($class)
  144. {
  145. return $this->getMetadata($class)->identifier;
  146. }
  147. public function getIdentifierValues($entity)
  148. {
  149. if (!$this->getEntityManager()->getUnitOfWork()->isInIdentityMap($entity)) {
  150. throw new \RuntimeException('Entities passed to the choice field must be managed');
  151. }
  152. return $this->getEntityManager()->getUnitOfWork()->getEntityIdentifier($entity);
  153. }
  154. public function getIdentifierFieldNames($class)
  155. {
  156. return $this->getMetadata($class)->getIdentifierFieldNames();
  157. }
  158. public function getNormalizedIdentifier($entity)
  159. {
  160. // the entities is not managed
  161. if (!$entity || !$this->getEntityManager()->getUnitOfWork()->isInIdentityMap($entity)) {
  162. return null;
  163. }
  164. $values = $this->getIdentifierValues($entity);
  165. return implode('-', $values);
  166. }
  167. public function addIdentifiersToQuery($class, ProxyQueryInterface $queryProxy, array $idx)
  168. {
  169. $fieldNames = $this->getIdentifierFieldNames($class);
  170. $qb = $queryProxy->getQueryBuilder();
  171. $prefix = uniqid();
  172. foreach ($idx as $pos => $id) {
  173. $ids = explode('-', $id);
  174. $ands = array();
  175. foreach ($fieldNames as $posName => $name) {
  176. $parameterName = sprintf('field_%s_%s_%d', $prefix, $name, $pos);
  177. $ands[] = sprintf('%s.%s = :%s', $qb->getRootAlias(), $name, $parameterName);
  178. $qb->setParameter($parameterName, $ids[$posName]);
  179. }
  180. $qb->orWhere(implode(' AND ', $ands));
  181. }
  182. }
  183. /**
  184. * Deletes a set of $class identified by the provided $idx array
  185. *
  186. * @param string $class
  187. * @param array $idx
  188. * @return void
  189. */
  190. public function batchDelete($class, ProxyQueryInterface $queryProxy)
  191. {
  192. $i = 0;
  193. foreach ($queryProxy->getQuery()->iterate() as $pos => $object) {
  194. $this->entityManager->remove($object[0]);
  195. if ((++$i % 20) == 0) {
  196. $this->entityManager->flush();
  197. $this->entityManager->clear();
  198. }
  199. }
  200. $this->entityManager->flush();
  201. $this->entityManager->clear();
  202. }
  203. /**
  204. * Returns a new model instance
  205. * @param string $class
  206. * @return
  207. */
  208. public function getModelInstance($class)
  209. {
  210. return new $class;
  211. }
  212. /**
  213. * Returns the parameters used in the columns header
  214. *
  215. * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  216. * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
  217. * @return string
  218. */
  219. public function getSortParameters(FieldDescriptionInterface $fieldDescription, DatagridInterface $datagrid)
  220. {
  221. $values = $datagrid->getValues();
  222. if ($fieldDescription->getOption('sortable') == $values['_sort_by']) {
  223. if ($values['_sort_order'] == 'ASC') {
  224. $values['_sort_order'] = 'DESC';
  225. } else {
  226. $values['_sort_order'] = 'ASC';
  227. }
  228. } else {
  229. $values['_sort_order'] = 'ASC';
  230. $values['_sort_by'] = $fieldDescription->getOption('sortable');
  231. }
  232. return $values;
  233. }
  234. /**
  235. * @param sring $class
  236. * @return array
  237. */
  238. public function getDefaultSortValues($class)
  239. {
  240. return array(
  241. '_sort_order' => 'ASC',
  242. '_sort_by' => implode(',', $this->getModelIdentifier($class))
  243. );
  244. }
  245. /**
  246. * @param string $class
  247. * @param object $instance
  248. * @return void
  249. */
  250. function modelTransform($class, $instance)
  251. {
  252. return $instance;
  253. }
  254. /**
  255. * @param string $class
  256. * @param array $array
  257. * @return object
  258. */
  259. function modelReverseTransform($class, array $array = array())
  260. {
  261. $instance = $this->getModelInstance($class);
  262. $metadata = $this->getMetadata($class);
  263. $reflClass = $metadata->reflClass;
  264. foreach ($array as $name => $value) {
  265. $reflection_property = false;
  266. // property or association ?
  267. if (array_key_exists($name, $metadata->fieldMappings)) {
  268. $property = $metadata->fieldMappings[$name]['fieldName'];
  269. $reflection_property = $metadata->reflFields[$name];
  270. } else if (array_key_exists($name, $metadata->associationMappings)) {
  271. $property = $metadata->associationMappings[$name]['fieldName'];
  272. } else {
  273. $property = $name;
  274. }
  275. $setter = 'set'.$this->camelize($name);
  276. if ($reflClass->hasMethod($setter)) {
  277. if (!$reflClass->getMethod($setter)->isPublic()) {
  278. throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
  279. }
  280. $instance->$setter($value);
  281. } else if ($reflClass->hasMethod('__set')) {
  282. // needed to support magic method __set
  283. $instance->$property = $value;
  284. } else if ($reflClass->hasProperty($property)) {
  285. if (!$reflClass->getProperty($property)->isPublic()) {
  286. throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "set%s()"?', $property, $reflClass->getName(), ucfirst($property)));
  287. }
  288. $instance->$property = $value;
  289. } else if ($reflection_property) {
  290. $reflection_property->setValue($instance, $value);
  291. }
  292. }
  293. return $instance;
  294. }
  295. /**
  296. * method taken from PropertyPath
  297. *
  298. * @param $property
  299. * @return mixed
  300. */
  301. protected function camelize($property)
  302. {
  303. return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $property);
  304. }
  305. /**
  306. * @param string $class
  307. * @return \Doctrine\Common\Collections\ArrayCollection
  308. */
  309. public function getModelCollectionInstance($class)
  310. {
  311. return new \Doctrine\Common\Collections\ArrayCollection();
  312. }
  313. function collectionClear(&$collection)
  314. {
  315. return $collection->clear();
  316. }
  317. function collectionHasElement(&$collection, &$element)
  318. {
  319. return $collection->contains($element);
  320. }
  321. function collectionAddElement(&$collection, &$element)
  322. {
  323. return $collection->add($element);
  324. }
  325. function collectionRemoveElement(&$collection, &$element)
  326. {
  327. return $collection->removeElement($element);
  328. }
  329. }