You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

301 satır
14KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller\Admin;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\ORM\EntityRepository;
  5. use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  7. use FOS\UserBundle\Model\UserManagerInterface;
  8. use Lc\ShopBundle\Context\FilterMultipleMerchantsInterface;
  9. use Lc\ShopBundle\Context\MerchantInterface;
  10. use Lc\ShopBundle\Context\SortableInterface;
  11. use Lc\ShopBundle\Context\StatusInterface;
  12. use Lc\ShopBundle\Context\TreeInterface;
  13. use Lc\ShopBundle\Form\AbstractEditPositionType;
  14. use Lc\ShopBundle\Services\Utils;
  15. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  16. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  17. use Symfony\Component\Form\FormEvent;
  18. use Symfony\Component\Form\FormEvents;
  19. use Symfony\Component\Security\Core\Security;
  20. class AdminController extends EasyAdminController
  21. {
  22. protected $security;
  23. protected $userManager;
  24. protected $em;
  25. protected $utils;
  26. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em, Utils $utils)
  27. {
  28. $this->security = $security;
  29. $this->userManager = $userManager;
  30. $this->em = $em;
  31. $this->utils = $utils;
  32. }
  33. /**
  34. * Réécriture de show action pr rediriger vers l'édition
  35. */
  36. public function showAction()
  37. {
  38. $id = $this->request->query->get('id');
  39. $entity = $this->request->query->get('entity');
  40. return $this->redirectToRoute('easyadmin', [
  41. 'action' => 'edit',
  42. 'entity' => $entity,
  43. 'id' => $id
  44. ]);
  45. }
  46. /**
  47. * Réécriture de removeEntity pour passer les status à -1
  48. */
  49. protected function removeEntity($entity)
  50. {
  51. if ($entity instanceof StatusInterface) {
  52. $entity->setStatus(-1);
  53. $this->em->persist($entity);
  54. $this->em->flush();
  55. } else {
  56. parent::removeEntity($entity);
  57. }
  58. }
  59. protected function commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
  60. {
  61. if ($pos = strpos($dqlFilter, 'currentMerchant')) {
  62. $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
  63. }
  64. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  65. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  66. else $dqlFilter .= sprintf(' entity.status > = 0');
  67. }
  68. return $dqlFilter;
  69. }
  70. protected function commonQueryFilter($entityClass, $queryBuilder)
  71. {
  72. if (new $entityClass instanceof FilterMultipleMerchantsInterface) {
  73. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchants')
  74. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  75. }
  76. }
  77. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  78. {
  79. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  80. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
  81. $this->commonQueryFilter($entityClass, $queryBuilder);
  82. return $queryBuilder;
  83. }
  84. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  85. {
  86. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  87. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  88. $this->commonQueryFilter($entityClass, $queryBuilder);
  89. return $queryBuilder;
  90. }
  91. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  92. {
  93. $parameters = array_merge(
  94. $parameters,
  95. $this->getTwigExtraParameters()
  96. );
  97. return parent::renderTemplate($actionName, $templatePath, $parameters);
  98. }
  99. public function getTwigExtraParameters()
  100. {
  101. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  102. $merchants = $repositoryMerchant->findAll();
  103. $user = $this->security->getUser();
  104. return [
  105. 'merchants' => $merchants,
  106. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  107. ];
  108. }
  109. public function listChildrenAction()
  110. {
  111. $this->dispatch(EasyAdminEvents::PRE_LIST);
  112. $id = $this->request->query->get('id');
  113. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  114. $easyadmin = $this->request->attributes->get('easyadmin');
  115. $entity = $easyadmin['item'];
  116. $fields = $this->entity['list']['fields'];
  117. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->entity['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
  118. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  119. $parameters = [
  120. 'paginator' => $paginator,
  121. 'fields' => $fields,
  122. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  123. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  124. 'entity' => $entity,
  125. ];
  126. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  127. }
  128. public function sortAction()
  129. {
  130. $this->dispatch(EasyAdminEvents::PRE_LIST);
  131. $entity = null;
  132. //Replace this with query builder function, do not use finAll of easyAdmin
  133. if ($this->request->query->get('id')) {
  134. $id = $this->request->query->get('id');
  135. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  136. $easyadmin = $this->request->attributes->get('easyadmin');
  137. $entity = $easyadmin['item'];
  138. }
  139. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  140. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  141. $fields = $this->entity['list']['fields'];
  142. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
  143. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  144. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  145. ->add('entities', CollectionType::class, array(
  146. 'required' => true,
  147. 'allow_add' => true,
  148. 'entry_type' => AbstractEditPositionType::class,
  149. ))
  150. ->getForm();
  151. $positionForm->handleRequest($this->request);
  152. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  153. $class = $this->entity['class'];
  154. $repo = $this->em->getRepository($class);
  155. $latsPos = 0;
  156. foreach ($positionForm->get('entities')->getData() as $elm) {
  157. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  158. $entity = $repo->find($elm['id']);
  159. $entity->setPosition($elm['position']);
  160. $this->em->persist($entity);
  161. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  162. $latsPos = $elm['position'];
  163. }
  164. //to do récupérer les élements hors ligne et incrémenter position
  165. foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  166. $latsPos++;
  167. $offlineEntity->setPosition($latsPos);
  168. $this->em->persist($offlineEntity);
  169. }
  170. $this->em->flush();
  171. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  172. return $this->redirectToReferrer();
  173. }
  174. $parameters = [
  175. 'paginator' => $paginator,
  176. 'fields' => $fields,
  177. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  178. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  179. 'postion_form' => $positionForm->createView(),
  180. 'entity' => $entity,
  181. 'sortable' => true
  182. ];
  183. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  184. }
  185. public function createEntityFormBuilder($entity, $view)
  186. {
  187. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  188. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  189. if ($entity instanceof TreeInterface) {
  190. $formBuilder->add('parent', EntityType::class, array(
  191. 'class' => $this->entity['class'],
  192. 'query_builder' => function (EntityRepository $repo) use ($id) {
  193. return $repo->createQueryBuilder('e')
  194. ->where('e.parent is NULL')
  195. ->andWhere('e.status >= 0')
  196. ->orderBy('e.status', "DESC");
  197. },
  198. 'required' => false,
  199. )
  200. );
  201. }
  202. // @TODO : À passer dans le controller de App
  203. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  204. $form = $event->getForm();
  205. $allChilds = $form->all();
  206. foreach ($allChilds as $child) {
  207. $type = $child->getConfig()->getType()->getInnerType();
  208. if ($type instanceof EntityType) {
  209. $passedOptions = $child->getConfig()->getOptions();
  210. $classImplements = class_implements($passedOptions['class']);
  211. if (in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements)) {
  212. $propertyMerchant = 'merchant';
  213. $form->add($child->getName(), EntityType::class, array(
  214. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  215. 'label' => $passedOptions['label'],
  216. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  217. 'placeholder' => '--',
  218. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant) {
  219. $queryBuilder = $repo->createQueryBuilder('e');
  220. $propertyMerchant = 'e.' . $propertyMerchant;
  221. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  222. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  223. } else {
  224. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  225. }
  226. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  227. return $queryBuilder;
  228. },
  229. 'required' => $passedOptions['required'],
  230. )
  231. );
  232. }
  233. }
  234. }
  235. });
  236. return $formBuilder;
  237. }
  238. }