ModelManager.php 15 KB

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