ModelManager.php 14 KB

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