ModelManager.php 13 KB

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