ModelManager.php 16 KB

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