lib/composer/LisaBundle/src/VisualMedia/LisaBundle/Controller/CrudController.php line 256

Open in your IDE?
  1. <?php
  2. /**
  3. * Crud Controller
  4. *
  5. * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
  6. */
  7. namespace VisualMedia\LisaBundle\Controller;
  8. use DateTime;
  9. use Exception;
  10. use ReflectionClass;
  11. use Symfony\Component\Form\FormInterface;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use VisualMedia\LisaBundle\Bulk\BulkFactory;
  16. use VisualMedia\LisaBundle\Form\Type\DuplicateType;
  17. use VisualMedia\LisaBundle\Helper\CloneHelper;
  18. use VisualMedia\LisaBundle\Helper\EntityHelper;
  19. use VisualMedia\LisaBundle\Component\Interfaces\EntityInterface;
  20. use VisualMedia\LisaBundle\Component\ManagerData;
  21. use VisualMedia\LisaBundle\Service\BulkProvider;
  22. use VisualMedia\LisaBundle\Service\DataTableFilterProvider;
  23. use VisualMedia\TranslationBundle\Service\ChannelProvider;
  24. /**
  25. * Crud Controller
  26. * @see https://nl.wikipedia.org/wiki/CRUD
  27. */
  28. abstract class CrudController extends BaseController implements CrudControllerInterface
  29. {
  30. public const REQUESTSTACK_SERVICE_ID = 'request_stack';
  31. /**
  32. * @var array
  33. */
  34. protected $data = array();
  35. /**
  36. * @param string $key
  37. * @return string
  38. * @throws Exception
  39. */
  40. protected function getTemplate(string $key): string
  41. {
  42. $templates = $this->getTemplates();
  43. if (!isset($templates[$key])) {
  44. if (isset($templates[static::KEY_FORM]) && ($key == static::KEY_ADD || $key == static::KEY_EDIT)) {
  45. return $templates[static::KEY_FORM];
  46. }
  47. throw new Exception($this->get('translator')->trans('crud_controller.template_not_found', array(
  48. '%templatekey%' => $key,
  49. '%templatekey_form%' => static::KEY_FORM,
  50. ), 'exception'));
  51. }
  52. return $templates[$key];
  53. }
  54. /**
  55. * @param string $key
  56. * @param mixed $value
  57. * @return void
  58. */
  59. protected function setData(string $key, $value): void
  60. {
  61. $this->data[$key] = $value;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function setExtraData(Request $request, string $key): void
  67. {
  68. // ...
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function queryValueToSession(string $key): void
  74. {
  75. $request = $this->get(static::REQUESTSTACK_SERVICE_ID)->getMasterRequest();
  76. $sessionKey = get_class($this) . '.' . $key;
  77. $menuId = $request->query->get($key, $request->getSession()->get($sessionKey));
  78. $request->query->set($key, $menuId);
  79. $request->getSession()->set($sessionKey, $menuId);
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public function save(EntityInterface $entity, FormInterface $form): Response
  85. {
  86. $request = $this->get(static::REQUESTSTACK_SERVICE_ID)->getMasterRequest();
  87. $translator = $this->get('translator');
  88. $manager = $this->get($this->getManagerClass());
  89. $manager->persist($entity);
  90. $manager->flush();
  91. $query = $request->query->all();
  92. $editLink = $this->generateUrl(sprintf('manage_%s__edit', $this->getKey()), array_merge($query, array(
  93. 'id' => $entity->getId(),
  94. )));
  95. if ($form->get('save')->isClicked()) {
  96. $this->addFlash('success', $translator->trans(sprintf('%s.saved', $this->getKey()), array(), 'flashmessage'));
  97. return $this->redirect($editLink);
  98. }
  99. else {
  100. $this->addFlash('success', $translator->trans(sprintf('%s.saved_edit_again', $this->getKey()), array(
  101. '%link%' => $editLink,
  102. ), 'flashmessage'));
  103. return $this->redirect($this->generateUrl(sprintf('manage_%s__index', $this->getKey()), $query));
  104. }
  105. }
  106. /**
  107. * {@inheritdoc}
  108. */
  109. public function indexAction(Request $request): Response
  110. {
  111. if (null !== $datatableClass = $this->getDataTableClass()) {
  112. $datatable = $this->get($datatableClass);
  113. $datatable->initialize($this->container, $request, $this->getKey());
  114. $this->setData(static::DATATABLE, $datatable);
  115. $managerData = $datatable->getManagerData($request);
  116. $conditions = $managerData->getConditions();
  117. if(null !== $excludeFilterConditions = $datatable->excludeFilterConditions()) {
  118. $conditions = array_diff_key($conditions, array_flip((array)$excludeFilterConditions));
  119. }
  120. $managerData->setConditions($conditions);
  121. $dataTableFilterProvider = $this->get(DataTableFilterProvider::class);
  122. $dataTableFilterProvider->setKey($this->getKey());
  123. $dataTableFilterProvider->setDataTableFilters($managerData);
  124. $this->setData('datatable_filters', $dataTableFilterProvider);
  125. }
  126. $this->setExtraData($request, static::KEY_INDEX);
  127. return $this->render($this->getTemplate(static::KEY_INDEX), $this->data);
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. public function addAction(Request $request, EntityInterface $entity = null): Response
  133. {
  134. $translator = $this->get('translator');
  135. $channelProvider = $this->get(ChannelProvider::class);
  136. $class = $this->getEntityName();
  137. $entity = $entity ?? new $class();
  138. if (property_exists($entity, 'channels')) {
  139. //dd($channelProvider->getChannels());
  140. foreach ($channelProvider->getChannels() as $channel) {
  141. $entity->channels->add($channel);
  142. }
  143. }
  144. $form = $this->createForm($this->getFormTypeClass(), $entity);
  145. $form->handleRequest($request);
  146. $submitted = $form->isSubmitted();
  147. // $form = $this->createForm($this->getFormTypeClass(), $entity);
  148. // $form->handleRequest($request);
  149. if ($form->isSubmitted() && $form->isValid()) {
  150. return $this->save($entity, $form);
  151. }
  152. elseif ($submitted) {
  153. $this->addFlash('danger', $translator->trans('form.not_valid', [], 'flashmessage'));
  154. }
  155. $this->setData(static::FORM, $form->createView());
  156. $this->setData(static::TITLE, $translator->trans($this->getKey() . '.' . static::KEY_ADD . '.' . static::TITLE, [], 'backend'));
  157. $this->setExtraData($request, static::KEY_ADD);
  158. return $this->render($this->getTemplate(static::KEY_ADD), $this->data);
  159. }
  160. /**
  161. * {@inheritdoc}
  162. */
  163. public function editAction(Request $request, $id): Response
  164. {
  165. $translator = $this->get('translator');
  166. $channelProvider = $this->get(ChannelProvider::class);
  167. $manager = $this->get($this->getManagerClass());
  168. if (null === $entity = $manager->getFirst(new ManagerData(array('id' => $id)))) {
  169. dd($manager, $id);
  170. throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
  171. }
  172. if (!$channelProvider->hasMultiple() && property_exists($entity, 'channels')) {
  173. foreach ($channelProvider->getChannels() as $channel) {
  174. $entity->channels->add($channel);
  175. }
  176. }
  177. $form = $this->createForm($this->getFormTypeClass(), $entity);
  178. $form->handleRequest($request);
  179. $submitted = $form->isSubmitted();
  180. // $form = $this->createForm($this->getFormTypeClass(), $entity);
  181. // $form->handleRequest($request);
  182. if ($form->isSubmitted() && $form->isValid()) {
  183. return $this->save($entity, $form);
  184. }
  185. elseif ($submitted) {
  186. $this->addFlash('danger', $translator->trans('form.not_valid', [], 'flashmessage'));
  187. }
  188. $this->setData(static::FORM, $form->createView());
  189. $this->setData(static::ENTITY, $entity);
  190. $this->setData(static::TITLE, $translator->trans($this->getKey() . '.' . static::KEY_EDIT . '.' . static::TITLE, [], 'backend'));
  191. $this->setData(static::SUBTITLE, (string)$entity ?: $translator->trans(sprintf('%s.missing', $this->getKey()), [ '%id%' => $entity->id ], 'backend'));
  192. $this->setExtraData($request, static::KEY_EDIT);
  193. return $this->render($this->getTemplate(static::KEY_EDIT), $this->data);
  194. }
  195. /**
  196. * {@inheritdoc}
  197. */
  198. public function refreshAction(Request $request, int $id = null): Response
  199. {
  200. $twig = $this->get('twig');
  201. $translator = $this->get('translator');
  202. $channelProvider = $this->get(ChannelProvider::class);
  203. $manager = $this->get($this->getManagerClass());
  204. if (!empty($id) && null === $entity = $manager->getFirst(new ManagerData([ 'id' => $id ]))) {
  205. throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
  206. }
  207. elseif (empty($id)) {
  208. $class = $this->getEntityName();
  209. $entity = new $class();
  210. }
  211. if (property_exists($entity, 'contents')) {
  212. $data = $request->get($this->getKey());
  213. unset($data['contents']);
  214. $request->request->set($this->getKey(), $data);
  215. $contents = clone($entity->contents);
  216. }
  217. $form = $this->createForm($this->getFormTypeClass(), $entity);
  218. $form->handleRequest($request);
  219. if (property_exists($entity, 'contents')) {
  220. $entity->contents = $contents;
  221. }
  222. $form = $this->createForm($this->getFormTypeClass(), $entity);
  223. $this->setData(static::FORM, $form->createView());
  224. $this->setData(static::ENTITY, $entity);
  225. $this->addFlash('info', $translator->trans('form.refresh', [], 'flashmessage'));
  226. $template = $twig->loadTemplate($this->getTemplate(static::KEY_FORM));
  227. $block = $template->renderBlock('main', array_merge($twig->getGlobals(), $this->data));
  228. return new JsonResponse([ 'html' => $block ]);
  229. }
  230. /**
  231. * {@inheritdoc}
  232. */
  233. public function removeAction(Request $request, $id): Response
  234. {
  235. $translator = $this->get('translator');
  236. $manager = $this->get($this->getManagerClass());
  237. if (null === $entity = $manager->getFirst(new ManagerData(array('id' => $id)))) {
  238. throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
  239. }
  240. /*
  241. * fix for force eventlisteners on removal of children when deleting a parentobject with children
  242. * without this routes of child entities wil not be deleted
  243. */
  244. //if a parent-child relation exists
  245. if(property_exists($entity, "children")){
  246. foreach($entity->children as $child){
  247. $manager->remove($child);
  248. }
  249. }
  250. $manager->remove($entity);
  251. $manager->flush();
  252. $this->addFlash('success', $translator->trans($this->getKey() . '.removed', array(), 'flashmessage'));
  253. return $this->redirectToRoute('manage_' . $this->getKey() . '__index');
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function duplicateAction(Request $request, $id): Response
  259. {
  260. $translator = $this->get('translator');
  261. $manager = $this->get($this->getManagerClass());
  262. $managerData = new ManagerData([ 'id' => $id ]);
  263. if (null === $entity = $manager->getFirst($managerData)) {
  264. throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
  265. }
  266. $cloneHelper = CloneHelper::getInstance($entity);
  267. $duplicate = clone $entity;
  268. $formClass = get_class($this->get($this->getFormTypeClass()));
  269. $form = $this->createForm($formClass, $duplicate, [
  270. CrudControllerInterface::KEY_DUPLICATE => true,
  271. ]);
  272. $form->handleRequest($request);
  273. if ($form->isSubmitted() && $form->isValid()) {
  274. $duplicate = $form->getData();
  275. $reflection = new ReflectionClass($duplicate);
  276. if ($reflection->hasMethod('setCreated')) {
  277. $duplicate->setCreated(new DateTime());
  278. }
  279. if ($reflection->hasMethod('setUpdated')) {
  280. $duplicate->setUpdated(new DateTime());
  281. }
  282. if ($reflection->hasMethod('setOrdering')) {
  283. $duplicate->setOrdering(0);
  284. }
  285. $manager->getEntityManager()->persist($duplicate);
  286. $manager->getEntityManager()->flush();
  287. $query = $request->query->all();
  288. $this->addFlash('success', $translator->trans(sprintf('%s.duplicated', $this->getKey()), [], 'flashmessage'));
  289. return $this->redirect($this->generateUrl(sprintf('manage_%s__index', $this->getKey()), $query));
  290. }
  291. $this->setData(static::FORM, $form->createView());
  292. $this->setData(static::TITLE, $translator->trans($this->getKey() . '.' . static::KEY_DUPLICATE . '.' . static::TITLE, [], 'backend'));
  293. $this->setExtraData($request, static::KEY_DUPLICATE);
  294. return $this->render($this->getTemplate(static::KEY_DUPLICATE), $this->data);
  295. }
  296. /**
  297. * {@inheritdoc}
  298. */
  299. public function toggleAction(Request $request, $id, $field): Response
  300. {
  301. $translator = $this->get('translator');
  302. $manager = $this->get($this->getManagerClass());
  303. if (null === $entity = $manager->getFirst(new ManagerData(array('id' => $id)))) {
  304. throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
  305. }
  306. $setter = EntityHelper::setter($field);
  307. $getter = EntityHelper::getter($field);
  308. if (method_exists($entity, $setter)) {
  309. $entity->{ $setter }(!(bool)$entity->{ $getter }());
  310. }
  311. elseif (property_exists($entity, $field)) {
  312. $entity->{ $field } = !(bool)$entity->{ $field };
  313. }
  314. $manager->persist($entity);
  315. $manager->flush();
  316. $this->addFlash('success', $translator->trans($this->getKey() . '.saved', [], 'flashmessage'));
  317. if (null !== $route = $request->query->get('route', null)) {
  318. $params = $request->query->get('params');
  319. $url = $this->generateUrl($route, $params);
  320. return $this->redirect($url);
  321. }
  322. return $this->redirectToRoute('manage_' . $this->getKey() . '__index');
  323. }
  324. /**
  325. * {@inheritdoc}
  326. */
  327. public function upAction(Request $request, $id): Response
  328. {
  329. $translator = $this->get('translator');
  330. $manager = $this->get($this->getManagerClass());
  331. if (null === $entity = $manager->getFirst(new ManagerData([ 'id' => $id ]))) {
  332. throw $this->createNotFoundException($translator->trans(sprintf('%s.not_found', $this->getKey()), [], 'exception'));
  333. }
  334. $manager->moveUp($entity, 1);
  335. $this->addFlash('success', $translator->trans(sprintf('%s.saved', $this->getKey()), [], 'flashmessage'));
  336. return $this->redirectToRoute(sprintf('manage_%s__index', $this->getKey()));
  337. }
  338. /**
  339. * {@inheritdoc}
  340. */
  341. public function downAction(Request $request, $id): Response
  342. {
  343. $translator = $this->get('translator');
  344. $manager = $this->get($this->getManagerClass());
  345. if (null === $entity = $manager->getFirst(new ManagerData([ 'id' => $id ]))) {
  346. throw $this->createNotFoundException($translator->trans(sprintf('%s.not_found', $this->getKey()), [], 'exception'));
  347. }
  348. $manager->moveDown($entity, 1);
  349. $this->addFlash('success', $translator->trans(sprintf('%s.saved', $this->getKey()), [], 'flashmessage'));
  350. return $this->redirectToRoute(sprintf('manage_%s__index', $this->getKey()));
  351. }
  352. /**
  353. * Function that acts as hatch for serving request to correct bulk factory.
  354. * @param Request $request
  355. * @return JsonResponse
  356. */
  357. public function bulkAjaxAction(Request $request): JsonResponse
  358. {
  359. $translator = $this->get('translator');
  360. $manager = $this->get($this->getManagerClass());
  361. $action = $request->request->get('action');
  362. $ids = $request->request->get('ids');
  363. if (empty($action)) {
  364. $this->addFlash('warning', $translator->trans('bulk.empty_action', [], 'flashmessage'));
  365. }
  366. else {
  367. if(!empty($ids)) {
  368. $bulkProvider = $this->get(BulkProvider::class);
  369. list($factoryKey, $field) = array_pad(explode('#', $action), 2, '');
  370. /** @var BulkFactory $bulkFactory */
  371. $bulkFactory = $bulkProvider->getFactoryActions()[$factoryKey] ?? null;
  372. if ($bulkFactory !== null) {
  373. $bulkFactory->handleBulk($ids, $field, $manager);
  374. $bulkFactory->postSuccessMessage($this->getKey(), $field);
  375. }
  376. }
  377. else {
  378. $this->addFlash('warning', $translator->trans($this->getKey() . '.bulk.empty_ids', [], 'flashmessage'));
  379. }
  380. }
  381. return new JsonResponse(array(
  382. 'redirect_url' => $this->generateUrl('manage_' . $this->getKey() . '__index')
  383. ));
  384. }
  385. /**
  386. * {@inheritdoc}
  387. */
  388. public function searchAction(Request $request): Response
  389. {
  390. // ...
  391. }
  392. }