ModelManager.php 13 KB

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