ModelManager.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. $values['_sort_by'] = $fieldDescription->getName();
  325. } else {
  326. $values['_sort_order'] = 'ASC';
  327. $values['_sort_by'] = $fieldDescription->getName();
  328. }
  329. return array('filter' => $values);
  330. }
  331. /**
  332. * {@inheritdoc}
  333. */
  334. public function getPaginationParameters(DatagridInterface $datagrid, $page)
  335. {
  336. $values = $datagrid->getValues();
  337. $values['_page'] = $page;
  338. return array('filter' => $values);
  339. }
  340. /**
  341. * {@inheritdoc}
  342. */
  343. public function getDefaultSortValues($class)
  344. {
  345. return array(
  346. '_sort_order' => 'ASC',
  347. '_sort_by' => implode(',', $this->getModelIdentifier($class)),
  348. '_page' => 1
  349. );
  350. }
  351. /**
  352. * {@inheritdoc}
  353. */
  354. public function modelTransform($class, $instance)
  355. {
  356. return $instance;
  357. }
  358. /**
  359. * {@inheritdoc}
  360. */
  361. public function modelReverseTransform($class, array $array = array())
  362. {
  363. $instance = $this->getModelInstance($class);
  364. $metadata = $this->getMetadata($class);
  365. $reflClass = $metadata->reflClass;
  366. foreach ($array as $name => $value) {
  367. $reflection_property = false;
  368. // property or association ?
  369. if (array_key_exists($name, $metadata->fieldMappings)) {
  370. $property = $metadata->fieldMappings[$name]['fieldName'];
  371. $reflection_property = $metadata->reflFields[$name];
  372. } else if (array_key_exists($name, $metadata->associationMappings)) {
  373. $property = $metadata->associationMappings[$name]['fieldName'];
  374. } else {
  375. $property = $name;
  376. }
  377. $setter = 'set'.$this->camelize($name);
  378. if ($reflClass->hasMethod($setter)) {
  379. if (!$reflClass->getMethod($setter)->isPublic()) {
  380. throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
  381. }
  382. $instance->$setter($value);
  383. } else if ($reflClass->hasMethod('__set')) {
  384. // needed to support magic method __set
  385. $instance->$property = $value;
  386. } else if ($reflClass->hasProperty($property)) {
  387. if (!$reflClass->getProperty($property)->isPublic()) {
  388. 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)));
  389. }
  390. $instance->$property = $value;
  391. } else if ($reflection_property) {
  392. $reflection_property->setValue($instance, $value);
  393. }
  394. }
  395. return $instance;
  396. }
  397. /**
  398. * method taken from PropertyPath
  399. *
  400. * @param string $property
  401. *
  402. * @return mixed
  403. */
  404. protected function camelize($property)
  405. {
  406. return preg_replace_callback('/(^|[_. ])+(.)/', function ($match) {
  407. return ('.' === $match[1] ? '_' : '') . strtoupper($match[2]);
  408. }, $property);
  409. }
  410. /**
  411. * {@inheritdoc}
  412. */
  413. public function getModelCollectionInstance($class)
  414. {
  415. return new \Doctrine\Common\Collections\ArrayCollection();
  416. }
  417. /**
  418. * {@inheritdoc}
  419. */
  420. public function collectionClear(&$collection)
  421. {
  422. return $collection->clear();
  423. }
  424. /**
  425. * {@inheritdoc}
  426. */
  427. public function collectionHasElement(&$collection, &$element)
  428. {
  429. return $collection->contains($element);
  430. }
  431. /**
  432. * {@inheritdoc}
  433. */
  434. public function collectionAddElement(&$collection, &$element)
  435. {
  436. return $collection->add($element);
  437. }
  438. /**
  439. * {@inheritdoc}
  440. */
  441. public function collectionRemoveElement(&$collection, &$element)
  442. {
  443. return $collection->removeElement($element);
  444. }
  445. }