ModelManager.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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\DoctrineORMAdminBundle\Model;
  11. use Sonata\DoctrineORMAdminBundle\Admin\FieldDescription;
  12. use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
  13. use Sonata\AdminBundle\Model\ModelManagerInterface;
  14. use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
  15. use Sonata\AdminBundle\Datagrid\DatagridInterface;
  16. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  17. use Sonata\AdminBundle\Exception\ModelManagerException;
  18. use Doctrine\ORM\QueryBuilder;
  19. use Symfony\Component\Form\Exception\PropertyAccessDeniedException;
  20. use Symfony\Bridge\Doctrine\RegistryInterface;
  21. use Exporter\Source\DoctrineORMQuerySourceIterator;
  22. class ModelManager implements ModelManagerInterface
  23. {
  24. protected $registry;
  25. /**
  26. * @param \Symfony\Bridge\Doctrine\RegistryInterface $registry
  27. */
  28. public function __construct(RegistryInterface $registry)
  29. {
  30. $this->registry = $registry;
  31. }
  32. /**
  33. * Returns the related model's metadata
  34. *
  35. * @param $class
  36. * @return \Doctrine\ORM\Mapping\ClassMetadata
  37. */
  38. public function getMetadata($class)
  39. {
  40. return $this->getEntityManager($class)->getMetadataFactory()->getMetadataFor($class);
  41. }
  42. /**
  43. * Returns true is the model has some metadata
  44. *
  45. * @param $class
  46. * @return boolean
  47. */
  48. public function hasMetadata($class)
  49. {
  50. return $this->getEntityManager($class)->getMetadataFactory()->hasMetadataFor($class);
  51. }
  52. /**
  53. * Returns a new FieldDescription
  54. *
  55. * @throws \RunTimeException
  56. * @param $class
  57. * @param $name
  58. * @param array $options
  59. * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
  60. */
  61. public function getNewFieldDescriptionInstance($class, $name, array $options = array())
  62. {
  63. if (!is_string($name)) {
  64. throw new \RunTimeException('The name argument must be a string');
  65. }
  66. $metadata = $this->getMetadata($class);
  67. $fieldDescription = new FieldDescription;
  68. $fieldDescription->setName($name);
  69. $fieldDescription->setOptions($options);
  70. if (isset($metadata->associationMappings[$name])) {
  71. $fieldDescription->setAssociationMapping($metadata->associationMappings[$name]);
  72. }
  73. if (isset($metadata->fieldMappings[$name])) {
  74. $fieldDescription->setFieldMapping($metadata->fieldMappings[$name]);
  75. }
  76. return $fieldDescription;
  77. }
  78. public function create($object)
  79. {
  80. try {
  81. $entityManager = $this->getEntityManager($object);
  82. $entityManager->persist($object);
  83. $entityManager->flush();
  84. } catch ( \PDOException $e ) {
  85. throw new ModelManagerException('', 0, $e);
  86. }
  87. }
  88. public function update($object)
  89. {
  90. try {
  91. $entityManager = $this->getEntityManager($object);
  92. $entityManager->persist($object);
  93. $entityManager->flush();
  94. } catch ( \PDOException $e ) {
  95. throw new ModelManagerException('', 0, $e);
  96. }
  97. }
  98. public function delete($object)
  99. {
  100. try {
  101. $entityManager = $this->getEntityManager($object);
  102. $entityManager->remove($object);
  103. $entityManager->flush();
  104. } catch ( \PDOException $e ) {
  105. throw new ModelManagerException('', 0, $e);
  106. }
  107. }
  108. /**
  109. * Find one object from the given class repository.
  110. *
  111. * @param string $class Class name
  112. * @param string|int $id Identifier. Can be a string with several IDs concatenated, separated by '-'.
  113. * @return Object
  114. */
  115. public function find($class, $id)
  116. {
  117. $values = array_combine($this->getIdentifierFieldNames($class), explode('-', $id));
  118. return $this->getEntityManager($class)->getRepository($class)->find($values);
  119. }
  120. /**
  121. * @param $class
  122. * @param array $criteria
  123. * @return array
  124. */
  125. public function findBy($class, array $criteria = array())
  126. {
  127. return $this->getEntityManager($class)->getRepository($class)->findBy($criteria);
  128. }
  129. /**
  130. * @param $class
  131. * @param array $criteria
  132. * @return array
  133. */
  134. public function findOneBy($class, array $criteria = array())
  135. {
  136. return $this->getEntityManager($class)->getRepository($class)->findOneBy($criteria);
  137. }
  138. /**
  139. * @return \Doctrine\ORM\EntityManager
  140. */
  141. public function getEntityManager($class)
  142. {
  143. if (is_object($class)) {
  144. $class = get_class($class);
  145. }
  146. return $this->registry->getEntityManagerForClass($class);
  147. }
  148. /**
  149. * @param string $parentAssociationMapping
  150. * @param string $class
  151. * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
  152. */
  153. public function getParentFieldDescription($parentAssociationMapping, $class)
  154. {
  155. $fieldName = $parentAssociationMapping['fieldName'];
  156. $metadata = $this->getMetadata($class);
  157. $associatingMapping = $metadata->associationMappings[$parentAssociationMapping];
  158. $fieldDescription = $this->getNewFieldDescriptionInstance($class, $fieldName);
  159. $fieldDescription->setName($parentAssociationMapping);
  160. $fieldDescription->setAssociationMapping($associatingMapping);
  161. return $fieldDescription;
  162. }
  163. /**
  164. * @param $class
  165. * @param string $alias
  166. * @return \Doctrine\ORM\QueryBuilder
  167. */
  168. public function createQuery($class, $alias = 'o')
  169. {
  170. $repository = $this->getEntityManager($class)->getRepository($class);
  171. return new ProxyQuery($repository->createQueryBuilder($alias));
  172. }
  173. /**
  174. * @param $query
  175. * @return mixed
  176. */
  177. public function executeQuery($query)
  178. {
  179. if ($query instanceof QueryBuilder) {
  180. return $query->getQuery()->execute();
  181. }
  182. return $query->execute();
  183. }
  184. /**
  185. * @param string $class
  186. * @return string
  187. */
  188. public function getModelIdentifier($class)
  189. {
  190. return $this->getMetadata($class)->identifier;
  191. }
  192. /**
  193. * @throws \RuntimeException
  194. * @param $entity
  195. * @return mixed
  196. */
  197. public function getIdentifierValues($entity)
  198. {
  199. $entityManager = $this->getEntityManager($entity);
  200. if (!$entityManager->getUnitOfWork()->isInIdentityMap($entity)) {
  201. throw new \RuntimeException('Entities passed to the choice field must be managed');
  202. }
  203. return $entityManager->getUnitOfWork()->getEntityIdentifier($entity);
  204. }
  205. /**
  206. * @param $class
  207. * @return mixed
  208. */
  209. public function getIdentifierFieldNames($class)
  210. {
  211. return $this->getMetadata($class)->getIdentifierFieldNames();
  212. }
  213. /**
  214. * @throws \RunTimeException
  215. * @param $entity
  216. * @return null|string
  217. */
  218. public function getNormalizedIdentifier($entity)
  219. {
  220. if (is_scalar($entity)) {
  221. throw new \RunTimeException('Invalid argument, object or null required');
  222. }
  223. // the entities is not managed
  224. if (!$entity || !$this->getEntityManager($entity)->getUnitOfWork()->isInIdentityMap($entity)) {
  225. return null;
  226. }
  227. $values = $this->getIdentifierValues($entity);
  228. return implode('-', $values);
  229. }
  230. /**
  231. * @param $class
  232. * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy
  233. * @param array $idx
  234. * @return void
  235. */
  236. public function addIdentifiersToQuery($class, ProxyQueryInterface $queryProxy, array $idx)
  237. {
  238. $fieldNames = $this->getIdentifierFieldNames($class);
  239. $qb = $queryProxy->getQueryBuilder();
  240. $prefix = uniqid();
  241. $sqls = array();
  242. foreach ($idx as $pos => $id) {
  243. $ids = explode('-', $id);
  244. $ands = array();
  245. foreach ($fieldNames as $posName => $name) {
  246. $parameterName = sprintf('field_%s_%s_%d', $prefix, $name, $pos);
  247. $ands[] = sprintf('%s.%s = :%s', $qb->getRootAlias(), $name, $parameterName);
  248. $qb->setParameter($parameterName, $ids[$posName]);
  249. }
  250. $sqls[] = implode(' AND ', $ands);
  251. }
  252. $qb->andWhere(sprintf('( %s )', implode(' OR ', $sqls)));
  253. }
  254. /**
  255. * Deletes a set of $class identified by the provided $idx array
  256. *
  257. * @param $class
  258. * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy
  259. * @return void
  260. */
  261. public function batchDelete($class, ProxyQueryInterface $queryProxy)
  262. {
  263. $queryProxy->select('DISTINCT '.$queryProxy->getRootAlias());
  264. try {
  265. $entityManager = $this->getEntityManager($class);
  266. $i = 0;
  267. foreach ($queryProxy->getQuery()->iterate() as $pos => $object) {
  268. $entityManager->remove($object[0]);
  269. if ((++$i % 20) == 0) {
  270. $entityManager->flush();
  271. $entityManager->clear();
  272. }
  273. }
  274. $entityManager->flush();
  275. $entityManager->clear();
  276. } catch ( \PDOException $e ) {
  277. throw new ModelManagerException('', 0, $e);
  278. }
  279. }
  280. /**
  281. * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
  282. * @param array $fields
  283. * @param null $firstResult
  284. * @param null $maxResult
  285. * @return \Exporter\Source\DoctrineORMQuerySourceIterator
  286. */
  287. public function getDataSourceIterator(DatagridInterface $datagrid, array $fields, $firstResult = null, $maxResult = null)
  288. {
  289. $datagrid->buildPager();
  290. $query = $datagrid->getQuery();
  291. $query->select('DISTINCT '.$query->getRootAlias());
  292. $query->setFirstResult($firstResult);
  293. $query->setMaxResults($maxResult);
  294. return new DoctrineORMQuerySourceIterator($query instanceof ProxyQuery ? $query->getQuery() : $query, $fields);
  295. }
  296. /**
  297. * @param $class
  298. * @return array
  299. */
  300. public function getExportFields($class)
  301. {
  302. $metadata = $this->registry->getEntityManager()->getClassMetadata($class);
  303. return $metadata->getFieldNames();
  304. }
  305. /**
  306. * Returns a new model instance
  307. * @param string $class
  308. * @return
  309. */
  310. public function getModelInstance($class)
  311. {
  312. return new $class;
  313. }
  314. /**
  315. * Returns the parameters used in the columns header
  316. *
  317. * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  318. * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
  319. * @return array
  320. */
  321. public function getSortParameters(FieldDescriptionInterface $fieldDescription, DatagridInterface $datagrid)
  322. {
  323. $values = $datagrid->getValues();
  324. if ($fieldDescription->getOption('sortable') == $values['_sort_by']) {
  325. if ($values['_sort_order'] == 'ASC') {
  326. $values['_sort_order'] = 'DESC';
  327. } else {
  328. $values['_sort_order'] = 'ASC';
  329. }
  330. } else {
  331. $values['_sort_order'] = 'ASC';
  332. $values['_sort_by'] = $fieldDescription->getOption('sortable');
  333. }
  334. return array('filter' => $values);
  335. }
  336. /**
  337. * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
  338. * @param $page
  339. * @return array
  340. */
  341. public function getPaginationParameters(DatagridInterface $datagrid, $page)
  342. {
  343. $values = $datagrid->getValues();
  344. $values['_page'] = $page;
  345. return array('filter' => $values);
  346. }
  347. /**
  348. * @param sring $class
  349. * @return array
  350. */
  351. public function getDefaultSortValues($class)
  352. {
  353. return array(
  354. '_sort_order' => 'ASC',
  355. '_sort_by' => implode(',', $this->getModelIdentifier($class)),
  356. '_page' => 1
  357. );
  358. }
  359. /**
  360. * @param string $class
  361. * @param object $instance
  362. * @return mixed
  363. */
  364. public function modelTransform($class, $instance)
  365. {
  366. return $instance;
  367. }
  368. /**
  369. * @param string $class
  370. * @param array $array
  371. * @return object
  372. */
  373. public function modelReverseTransform($class, array $array = array())
  374. {
  375. $instance = $this->getModelInstance($class);
  376. $metadata = $this->getMetadata($class);
  377. $reflClass = $metadata->reflClass;
  378. foreach ($array as $name => $value) {
  379. $reflection_property = false;
  380. // property or association ?
  381. if (array_key_exists($name, $metadata->fieldMappings)) {
  382. $property = $metadata->fieldMappings[$name]['fieldName'];
  383. $reflection_property = $metadata->reflFields[$name];
  384. } else if (array_key_exists($name, $metadata->associationMappings)) {
  385. $property = $metadata->associationMappings[$name]['fieldName'];
  386. } else {
  387. $property = $name;
  388. }
  389. $setter = 'set'.$this->camelize($name);
  390. if ($reflClass->hasMethod($setter)) {
  391. if (!$reflClass->getMethod($setter)->isPublic()) {
  392. throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
  393. }
  394. $instance->$setter($value);
  395. } else if ($reflClass->hasMethod('__set')) {
  396. // needed to support magic method __set
  397. $instance->$property = $value;
  398. } else if ($reflClass->hasProperty($property)) {
  399. if (!$reflClass->getProperty($property)->isPublic()) {
  400. 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)));
  401. }
  402. $instance->$property = $value;
  403. } else if ($reflection_property) {
  404. $reflection_property->setValue($instance, $value);
  405. }
  406. }
  407. return $instance;
  408. }
  409. /**
  410. * method taken from PropertyPath
  411. *
  412. * @param $property
  413. * @return mixed
  414. */
  415. protected function camelize($property)
  416. {
  417. return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $property);
  418. }
  419. /**
  420. * @param string $class
  421. * @return \Doctrine\Common\Collections\ArrayCollection
  422. */
  423. public function getModelCollectionInstance($class)
  424. {
  425. return new \Doctrine\Common\Collections\ArrayCollection();
  426. }
  427. public function collectionClear(&$collection)
  428. {
  429. return $collection->clear();
  430. }
  431. public function collectionHasElement(&$collection, &$element)
  432. {
  433. return $collection->contains($element);
  434. }
  435. public function collectionAddElement(&$collection, &$element)
  436. {
  437. return $collection->add($element);
  438. }
  439. public function collectionRemoveElement(&$collection, &$element)
  440. {
  441. return $collection->removeElement($element);
  442. }
  443. }