ModelManager.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 Doctrine\ORM\EntityManager;
  16. use Doctrine\ORM\QueryBuilder;
  17. use Symfony\Component\Form\Exception\PropertyAccessDeniedException;
  18. class ModelManager implements ModelManagerInterface
  19. {
  20. protected $entityManager;
  21. /**
  22. *
  23. * @param \Doctrine\ORM\EntityManager $entityManager
  24. */
  25. public function __construct(EntityManager $entityManager)
  26. {
  27. $this->entityManager = $entityManager;
  28. }
  29. /**
  30. * Returns the related model's metadata
  31. *
  32. * @abstract
  33. * @param string $name
  34. * @return \Doctrine\ORM\Mapping\ClassMetadataInfo
  35. */
  36. public function getMetadata($class)
  37. {
  38. return $this->entityManager->getMetadataFactory()->getMetadataFor($class);
  39. }
  40. /**
  41. * Returns true is the model has some metadata
  42. *
  43. * @return boolean
  44. */
  45. public function hasMetadata($class)
  46. {
  47. return $this->entityManager->getMetadataFactory()->hasMetadataFor($class);
  48. }
  49. /**
  50. * Returns a new FieldDescription
  51. *
  52. * @abstract
  53. * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
  54. */
  55. public function getNewFieldDescriptionInstance($class, $name, array $options = array())
  56. {
  57. $metadata = $this->getMetadata($class);
  58. $fieldDescription = new FieldDescription;
  59. $fieldDescription->setName($name);
  60. $fieldDescription->setOptions($options);
  61. if (isset($metadata->associationMappings[$name])) {
  62. $fieldDescription->setAssociationMapping($metadata->associationMappings[$name]);
  63. }
  64. if (isset($metadata->fieldMappings[$name])) {
  65. $fieldDescription->setFieldMapping($metadata->fieldMappings[$name]);
  66. }
  67. return $fieldDescription;
  68. }
  69. public function create($object)
  70. {
  71. $this->entityManager->persist($object);
  72. $this->entityManager->flush();
  73. }
  74. public function update($object)
  75. {
  76. $this->entityManager->persist($object);
  77. $this->entityManager->flush();
  78. }
  79. public function delete($object)
  80. {
  81. $this->entityManager->remove($object);
  82. $this->entityManager->flush();
  83. }
  84. public function findOne($class, $id)
  85. {
  86. return $this->entityManager->getRepository($class)->find($id);
  87. }
  88. public function find($class, array $criteria = array())
  89. {
  90. return $this->entityManager->getRepository($class)->findBy($criteria);
  91. }
  92. /**
  93. * @return \Doctrine\ORM\EntityManager
  94. */
  95. public function getEntityManager()
  96. {
  97. return $this->entityManager;
  98. }
  99. /**
  100. * @param string $parentAssociationMapping
  101. * @param string $class
  102. * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
  103. */
  104. public function getParentFieldDescription($parentAssociationMapping, $class)
  105. {
  106. $fieldName = $parentAssociationMapping['fieldName'];
  107. $metadata = $this->getMetadata($class);
  108. $associatingMapping = $metadata->associationMappings[$parentAssociationMapping];
  109. $fieldDescription = $this->getNewFieldDescriptionInstance($class, $fieldName);
  110. $fieldDescription->setName($parentAssociationMapping);
  111. $fieldDescription->setAssociationMapping($associatingMapping);
  112. return $fieldDescription;
  113. }
  114. /**
  115. * @param string $alias
  116. * @return \Doctrine\ORM\QueryBuilder a query instance
  117. */
  118. public function createQuery($class, $alias = 'o')
  119. {
  120. $repository = $this->getEntityManager()->getRepository($class);
  121. return $repository->createQueryBuilder($alias);
  122. }
  123. public function executeQuery($query)
  124. {
  125. if ($query instanceof QueryBuilder) {
  126. return $query->getQuery()->execute();
  127. }
  128. return $query->execute();
  129. }
  130. /**
  131. * @param string $class
  132. * @return string
  133. */
  134. public function getModelIdentifier($class)
  135. {
  136. return $this->getMetadata($class)->identifier;
  137. }
  138. public function getIdentifierValues($entity)
  139. {
  140. if (!$this->getEntityManager()->getUnitOfWork()->isInIdentityMap($entity)) {
  141. throw new \RuntimeException('Entities passed to the choice field must be managed');
  142. }
  143. return $this->getEntityManager()->getUnitOfWork()->getEntityIdentifier($entity);
  144. }
  145. public function getIdentifierFieldNames($class)
  146. {
  147. return $this->getMetadata($class)->getIdentifierFieldNames();
  148. }
  149. /**
  150. * Deletes a set of $class identified by the provided $idx array
  151. *
  152. * @param string $class
  153. * @param array $idx
  154. * @return void
  155. */
  156. public function batchDelete($class, $idx)
  157. {
  158. $queryBuilder = $this->createQuery($class, 'o');
  159. $objects = $queryBuilder
  160. ->select('o')
  161. ->add('where', $queryBuilder->expr()->in('o.id', $idx))
  162. ->getQuery()
  163. ->execute();
  164. foreach ($objects as $object) {
  165. $this->entityManager->remove($object);
  166. }
  167. $this->entityManager->flush();
  168. }
  169. /**
  170. * Returns a new model instance
  171. * @param string $class
  172. * @return
  173. */
  174. public function getModelInstance($class)
  175. {
  176. return new $class;
  177. }
  178. /**
  179. * Returns the parameters used in the columns header
  180. *
  181. * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  182. * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
  183. * @return string
  184. */
  185. public function getSortParameters(FieldDescriptionInterface $fieldDescription, DatagridInterface $datagrid)
  186. {
  187. $values = $datagrid->getValues();
  188. if ($fieldDescription->getOption('sortable') == $values['_sort_by']) {
  189. if ($values['_sort_order'] == 'ASC') {
  190. $values['_sort_order'] = 'DESC';
  191. } else {
  192. $values['_sort_order'] = 'ASC';
  193. }
  194. } else {
  195. $values['_sort_order'] = 'ASC';
  196. $values['_sort_by'] = $fieldDescription->getOption('sortable');
  197. }
  198. return $values;
  199. }
  200. /**
  201. * @param sring $class
  202. * @return array
  203. */
  204. public function getDefaultSortValues($class)
  205. {
  206. return array(
  207. '_sort_order' => 'ASC',
  208. '_sort_by' => implode(',', $this->getModelIdentifier($class))
  209. );
  210. }
  211. /**
  212. * @param string $class
  213. * @param object $instance
  214. * @return void
  215. */
  216. function modelTransform($class, $instance)
  217. {
  218. return $instance;
  219. }
  220. /**
  221. * @param string $class
  222. * @param array $array
  223. * @return object
  224. */
  225. function modelReverseTransform($class, array $array = array())
  226. {
  227. $instance = $this->getModelInstance($class);
  228. $metadata = $this->getMetadata($class);
  229. $reflClass = $metadata->reflClass;
  230. foreach ($array as $name => $value) {
  231. $reflection_property = false;
  232. // property or association ?
  233. if (array_key_exists($name, $metadata->fieldMappings)) {
  234. $property = $metadata->fieldMappings[$name]['fieldName'];
  235. $reflection_property = $metadata->reflFields[$name];
  236. } else if (array_key_exists($name, $metadata->associationMappings)) {
  237. $property = $metadata->associationMappings[$name]['fieldName'];
  238. } else {
  239. $property = $name;
  240. }
  241. $setter = 'set'.$this->camelize($name);
  242. if ($reflClass->hasMethod($setter)) {
  243. if (!$reflClass->getMethod($setter)->isPublic()) {
  244. throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
  245. }
  246. $instance->$setter($value);
  247. } else if ($reflClass->hasMethod('__set')) {
  248. // needed to support magic method __set
  249. $instance->$property = $value;
  250. } else if ($reflClass->hasProperty($property)) {
  251. if (!$reflClass->getProperty($property)->isPublic()) {
  252. 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)));
  253. }
  254. $instance->$property = $value;
  255. } else if ($reflection_property) {
  256. $reflection_property->setValue($instance, $value);
  257. }
  258. }
  259. return $instance;
  260. }
  261. /**
  262. * method taken from PropertyPath
  263. *
  264. * @param $property
  265. * @return mixed
  266. */
  267. protected function camelize($property)
  268. {
  269. return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $property);
  270. }
  271. /**
  272. * @param string $class
  273. * @return \Doctrine\Common\Collections\ArrayCollection
  274. */
  275. public function getModelCollectionInstance($class)
  276. {
  277. return new \Doctrine\Common\Collections\ArrayCollection();
  278. }
  279. function collectionClear(&$collection)
  280. {
  281. return $collection->clear();
  282. }
  283. function collectionHasElement(&$collection, &$element)
  284. {
  285. return $collection->contains($element);
  286. }
  287. function collectionAddElement(&$collection, &$element)
  288. {
  289. return $collection->add($element);
  290. }
  291. function collectionRemoveElement(&$collection, &$element)
  292. {
  293. return $collection->removeElement($element);
  294. }
  295. }