ModelManager.php 15 KB

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