ModelManager.php 13 KB

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