ModelManager.php 12 KB

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