ModelManager.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. public function getNormalizedIdentifier($entity)
  150. {
  151. // the entities is not managed
  152. if (!$this->getEntityManager()->getUnitOfWork()->isInIdentityMap($entity)) {
  153. return null;
  154. }
  155. $values = $this->getIdentifierValues($entity);
  156. return implode('-', $values);
  157. }
  158. /**
  159. * Deletes a set of $class identified by the provided $idx array
  160. *
  161. * @param string $class
  162. * @param array $idx
  163. * @return void
  164. */
  165. public function batchDelete($class, $idx)
  166. {
  167. $queryBuilder = $this->createQuery($class, 'o');
  168. $objects = $queryBuilder
  169. ->select('o')
  170. ->add('where', $queryBuilder->expr()->in('o.id', $idx))
  171. ->getQuery()
  172. ->execute();
  173. foreach ($objects as $object) {
  174. $this->entityManager->remove($object);
  175. }
  176. $this->entityManager->flush();
  177. }
  178. /**
  179. * Returns a new model instance
  180. * @param string $class
  181. * @return
  182. */
  183. public function getModelInstance($class)
  184. {
  185. return new $class;
  186. }
  187. /**
  188. * Returns the parameters used in the columns header
  189. *
  190. * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
  191. * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
  192. * @return string
  193. */
  194. public function getSortParameters(FieldDescriptionInterface $fieldDescription, DatagridInterface $datagrid)
  195. {
  196. $values = $datagrid->getValues();
  197. if ($fieldDescription->getOption('sortable') == $values['_sort_by']) {
  198. if ($values['_sort_order'] == 'ASC') {
  199. $values['_sort_order'] = 'DESC';
  200. } else {
  201. $values['_sort_order'] = 'ASC';
  202. }
  203. } else {
  204. $values['_sort_order'] = 'ASC';
  205. $values['_sort_by'] = $fieldDescription->getOption('sortable');
  206. }
  207. return $values;
  208. }
  209. /**
  210. * @param sring $class
  211. * @return array
  212. */
  213. public function getDefaultSortValues($class)
  214. {
  215. return array(
  216. '_sort_order' => 'ASC',
  217. '_sort_by' => implode(',', $this->getModelIdentifier($class))
  218. );
  219. }
  220. /**
  221. * @param string $class
  222. * @param object $instance
  223. * @return void
  224. */
  225. function modelTransform($class, $instance)
  226. {
  227. return $instance;
  228. }
  229. /**
  230. * @param string $class
  231. * @param array $array
  232. * @return object
  233. */
  234. function modelReverseTransform($class, array $array = array())
  235. {
  236. $instance = $this->getModelInstance($class);
  237. $metadata = $this->getMetadata($class);
  238. $reflClass = $metadata->reflClass;
  239. foreach ($array as $name => $value) {
  240. $reflection_property = false;
  241. // property or association ?
  242. if (array_key_exists($name, $metadata->fieldMappings)) {
  243. $property = $metadata->fieldMappings[$name]['fieldName'];
  244. $reflection_property = $metadata->reflFields[$name];
  245. } else if (array_key_exists($name, $metadata->associationMappings)) {
  246. $property = $metadata->associationMappings[$name]['fieldName'];
  247. } else {
  248. $property = $name;
  249. }
  250. $setter = 'set'.$this->camelize($name);
  251. if ($reflClass->hasMethod($setter)) {
  252. if (!$reflClass->getMethod($setter)->isPublic()) {
  253. throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
  254. }
  255. $instance->$setter($value);
  256. } else if ($reflClass->hasMethod('__set')) {
  257. // needed to support magic method __set
  258. $instance->$property = $value;
  259. } else if ($reflClass->hasProperty($property)) {
  260. if (!$reflClass->getProperty($property)->isPublic()) {
  261. 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)));
  262. }
  263. $instance->$property = $value;
  264. } else if ($reflection_property) {
  265. $reflection_property->setValue($instance, $value);
  266. }
  267. }
  268. return $instance;
  269. }
  270. /**
  271. * method taken from PropertyPath
  272. *
  273. * @param $property
  274. * @return mixed
  275. */
  276. protected function camelize($property)
  277. {
  278. return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $property);
  279. }
  280. /**
  281. * @param string $class
  282. * @return \Doctrine\Common\Collections\ArrayCollection
  283. */
  284. public function getModelCollectionInstance($class)
  285. {
  286. return new \Doctrine\Common\Collections\ArrayCollection();
  287. }
  288. function collectionClear(&$collection)
  289. {
  290. return $collection->clear();
  291. }
  292. function collectionHasElement(&$collection, &$element)
  293. {
  294. return $collection->contains($element);
  295. }
  296. function collectionAddElement(&$collection, &$element)
  297. {
  298. return $collection->add($element);
  299. }
  300. function collectionRemoveElement(&$collection, &$element)
  301. {
  302. return $collection->removeElement($element);
  303. }
  304. }