ModelManager.php 11 KB

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