ModelManager.php 15 KB

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