ModelManager.php 16 KB

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