ModelManager.php 14 KB

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