<?php
/**
* Crud Controller
*
* @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
*/
namespace VisualMedia\LisaBundle\Controller;
use DateTime;
use Exception;
use ReflectionClass;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use VisualMedia\LisaBundle\Bulk\BulkFactory;
use VisualMedia\LisaBundle\Form\Type\DuplicateType;
use VisualMedia\LisaBundle\Helper\CloneHelper;
use VisualMedia\LisaBundle\Helper\EntityHelper;
use VisualMedia\LisaBundle\Component\Interfaces\EntityInterface;
use VisualMedia\LisaBundle\Component\ManagerData;
use VisualMedia\LisaBundle\Service\BulkProvider;
use VisualMedia\LisaBundle\Service\DataTableFilterProvider;
use VisualMedia\TranslationBundle\Service\ChannelProvider;
/**
* Crud Controller
* @see https://nl.wikipedia.org/wiki/CRUD
*/
abstract class CrudController extends BaseController implements CrudControllerInterface
{
public const REQUESTSTACK_SERVICE_ID = 'request_stack';
/**
* @var array
*/
protected $data = array();
/**
* @param string $key
* @return string
* @throws Exception
*/
protected function getTemplate(string $key): string
{
$templates = $this->getTemplates();
if (!isset($templates[$key])) {
if (isset($templates[static::KEY_FORM]) && ($key == static::KEY_ADD || $key == static::KEY_EDIT)) {
return $templates[static::KEY_FORM];
}
throw new Exception($this->get('translator')->trans('crud_controller.template_not_found', array(
'%templatekey%' => $key,
'%templatekey_form%' => static::KEY_FORM,
), 'exception'));
}
return $templates[$key];
}
/**
* @param string $key
* @param mixed $value
* @return void
*/
protected function setData(string $key, $value): void
{
$this->data[$key] = $value;
}
/**
* {@inheritdoc}
*/
public function setExtraData(Request $request, string $key): void
{
// ...
}
/**
* {@inheritdoc}
*/
public function queryValueToSession(string $key): void
{
$request = $this->get(static::REQUESTSTACK_SERVICE_ID)->getMasterRequest();
$sessionKey = get_class($this) . '.' . $key;
$menuId = $request->query->get($key, $request->getSession()->get($sessionKey));
$request->query->set($key, $menuId);
$request->getSession()->set($sessionKey, $menuId);
}
/**
* {@inheritdoc}
*/
public function save(EntityInterface $entity, FormInterface $form): Response
{
$request = $this->get(static::REQUESTSTACK_SERVICE_ID)->getMasterRequest();
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
$manager->persist($entity);
$manager->flush();
$query = $request->query->all();
$editLink = $this->generateUrl(sprintf('manage_%s__edit', $this->getKey()), array_merge($query, array(
'id' => $entity->getId(),
)));
if ($form->get('save')->isClicked()) {
$this->addFlash('success', $translator->trans(sprintf('%s.saved', $this->getKey()), array(), 'flashmessage'));
return $this->redirect($editLink);
}
else {
$this->addFlash('success', $translator->trans(sprintf('%s.saved_edit_again', $this->getKey()), array(
'%link%' => $editLink,
), 'flashmessage'));
return $this->redirect($this->generateUrl(sprintf('manage_%s__index', $this->getKey()), $query));
}
}
/**
* {@inheritdoc}
*/
public function indexAction(Request $request): Response
{
if (null !== $datatableClass = $this->getDataTableClass()) {
$datatable = $this->get($datatableClass);
$datatable->initialize($this->container, $request, $this->getKey());
$this->setData(static::DATATABLE, $datatable);
$managerData = $datatable->getManagerData($request);
$conditions = $managerData->getConditions();
if(null !== $excludeFilterConditions = $datatable->excludeFilterConditions()) {
$conditions = array_diff_key($conditions, array_flip((array)$excludeFilterConditions));
}
$managerData->setConditions($conditions);
$dataTableFilterProvider = $this->get(DataTableFilterProvider::class);
$dataTableFilterProvider->setKey($this->getKey());
$dataTableFilterProvider->setDataTableFilters($managerData);
$this->setData('datatable_filters', $dataTableFilterProvider);
}
$this->setExtraData($request, static::KEY_INDEX);
return $this->render($this->getTemplate(static::KEY_INDEX), $this->data);
}
/**
* {@inheritdoc}
*/
public function addAction(Request $request, EntityInterface $entity = null): Response
{
$translator = $this->get('translator');
$channelProvider = $this->get(ChannelProvider::class);
$class = $this->getEntityName();
$entity = $entity ?? new $class();
if (property_exists($entity, 'channels')) {
//dd($channelProvider->getChannels());
foreach ($channelProvider->getChannels() as $channel) {
$entity->channels->add($channel);
}
}
$form = $this->createForm($this->getFormTypeClass(), $entity);
$form->handleRequest($request);
$submitted = $form->isSubmitted();
// $form = $this->createForm($this->getFormTypeClass(), $entity);
// $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->save($entity, $form);
}
elseif ($submitted) {
$this->addFlash('danger', $translator->trans('form.not_valid', [], 'flashmessage'));
}
$this->setData(static::FORM, $form->createView());
$this->setData(static::TITLE, $translator->trans($this->getKey() . '.' . static::KEY_ADD . '.' . static::TITLE, [], 'backend'));
$this->setExtraData($request, static::KEY_ADD);
return $this->render($this->getTemplate(static::KEY_ADD), $this->data);
}
/**
* {@inheritdoc}
*/
public function editAction(Request $request, $id): Response
{
$translator = $this->get('translator');
$channelProvider = $this->get(ChannelProvider::class);
$manager = $this->get($this->getManagerClass());
if (null === $entity = $manager->getFirst(new ManagerData(array('id' => $id)))) {
dd($manager, $id);
throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
}
if (!$channelProvider->hasMultiple() && property_exists($entity, 'channels')) {
foreach ($channelProvider->getChannels() as $channel) {
$entity->channels->add($channel);
}
}
$form = $this->createForm($this->getFormTypeClass(), $entity);
$form->handleRequest($request);
$submitted = $form->isSubmitted();
// $form = $this->createForm($this->getFormTypeClass(), $entity);
// $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->save($entity, $form);
}
elseif ($submitted) {
$this->addFlash('danger', $translator->trans('form.not_valid', [], 'flashmessage'));
}
$this->setData(static::FORM, $form->createView());
$this->setData(static::ENTITY, $entity);
$this->setData(static::TITLE, $translator->trans($this->getKey() . '.' . static::KEY_EDIT . '.' . static::TITLE, [], 'backend'));
$this->setData(static::SUBTITLE, (string)$entity ?: $translator->trans(sprintf('%s.missing', $this->getKey()), [ '%id%' => $entity->id ], 'backend'));
$this->setExtraData($request, static::KEY_EDIT);
return $this->render($this->getTemplate(static::KEY_EDIT), $this->data);
}
/**
* {@inheritdoc}
*/
public function refreshAction(Request $request, int $id = null): Response
{
$twig = $this->get('twig');
$translator = $this->get('translator');
$channelProvider = $this->get(ChannelProvider::class);
$manager = $this->get($this->getManagerClass());
if (!empty($id) && null === $entity = $manager->getFirst(new ManagerData([ 'id' => $id ]))) {
throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
}
elseif (empty($id)) {
$class = $this->getEntityName();
$entity = new $class();
}
if (property_exists($entity, 'contents')) {
$data = $request->get($this->getKey());
unset($data['contents']);
$request->request->set($this->getKey(), $data);
$contents = clone($entity->contents);
}
$form = $this->createForm($this->getFormTypeClass(), $entity);
$form->handleRequest($request);
if (property_exists($entity, 'contents')) {
$entity->contents = $contents;
}
$form = $this->createForm($this->getFormTypeClass(), $entity);
$this->setData(static::FORM, $form->createView());
$this->setData(static::ENTITY, $entity);
$this->addFlash('info', $translator->trans('form.refresh', [], 'flashmessage'));
$template = $twig->loadTemplate($this->getTemplate(static::KEY_FORM));
$block = $template->renderBlock('main', array_merge($twig->getGlobals(), $this->data));
return new JsonResponse([ 'html' => $block ]);
}
/**
* {@inheritdoc}
*/
public function removeAction(Request $request, $id): Response
{
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
if (null === $entity = $manager->getFirst(new ManagerData(array('id' => $id)))) {
throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
}
/*
* fix for force eventlisteners on removal of children when deleting a parentobject with children
* without this routes of child entities wil not be deleted
*/
//if a parent-child relation exists
if(property_exists($entity, "children")){
foreach($entity->children as $child){
$manager->remove($child);
}
}
$manager->remove($entity);
$manager->flush();
$this->addFlash('success', $translator->trans($this->getKey() . '.removed', array(), 'flashmessage'));
return $this->redirectToRoute('manage_' . $this->getKey() . '__index');
}
/**
* {@inheritdoc}
*/
public function duplicateAction(Request $request, $id): Response
{
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
$managerData = new ManagerData([ 'id' => $id ]);
if (null === $entity = $manager->getFirst($managerData)) {
throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
}
$cloneHelper = CloneHelper::getInstance($entity);
$duplicate = clone $entity;
$formClass = get_class($this->get($this->getFormTypeClass()));
$form = $this->createForm($formClass, $duplicate, [
CrudControllerInterface::KEY_DUPLICATE => true,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$duplicate = $form->getData();
$reflection = new ReflectionClass($duplicate);
if ($reflection->hasMethod('setCreated')) {
$duplicate->setCreated(new DateTime());
}
if ($reflection->hasMethod('setUpdated')) {
$duplicate->setUpdated(new DateTime());
}
if ($reflection->hasMethod('setOrdering')) {
$duplicate->setOrdering(0);
}
$manager->getEntityManager()->persist($duplicate);
$manager->getEntityManager()->flush();
$query = $request->query->all();
$this->addFlash('success', $translator->trans(sprintf('%s.duplicated', $this->getKey()), [], 'flashmessage'));
return $this->redirect($this->generateUrl(sprintf('manage_%s__index', $this->getKey()), $query));
}
$this->setData(static::FORM, $form->createView());
$this->setData(static::TITLE, $translator->trans($this->getKey() . '.' . static::KEY_DUPLICATE . '.' . static::TITLE, [], 'backend'));
$this->setExtraData($request, static::KEY_DUPLICATE);
return $this->render($this->getTemplate(static::KEY_DUPLICATE), $this->data);
}
/**
* {@inheritdoc}
*/
public function toggleAction(Request $request, $id, $field): Response
{
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
if (null === $entity = $manager->getFirst(new ManagerData(array('id' => $id)))) {
throw $this->createNotFoundException($translator->trans($this->getKey() . '.not_found', [], 'exception'));
}
$setter = EntityHelper::setter($field);
$getter = EntityHelper::getter($field);
if (method_exists($entity, $setter)) {
$entity->{ $setter }(!(bool)$entity->{ $getter }());
}
elseif (property_exists($entity, $field)) {
$entity->{ $field } = !(bool)$entity->{ $field };
}
$manager->persist($entity);
$manager->flush();
$this->addFlash('success', $translator->trans($this->getKey() . '.saved', [], 'flashmessage'));
if (null !== $route = $request->query->get('route', null)) {
$params = $request->query->get('params');
$url = $this->generateUrl($route, $params);
return $this->redirect($url);
}
return $this->redirectToRoute('manage_' . $this->getKey() . '__index');
}
/**
* {@inheritdoc}
*/
public function upAction(Request $request, $id): Response
{
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
if (null === $entity = $manager->getFirst(new ManagerData([ 'id' => $id ]))) {
throw $this->createNotFoundException($translator->trans(sprintf('%s.not_found', $this->getKey()), [], 'exception'));
}
$manager->moveUp($entity, 1);
$this->addFlash('success', $translator->trans(sprintf('%s.saved', $this->getKey()), [], 'flashmessage'));
return $this->redirectToRoute(sprintf('manage_%s__index', $this->getKey()));
}
/**
* {@inheritdoc}
*/
public function downAction(Request $request, $id): Response
{
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
if (null === $entity = $manager->getFirst(new ManagerData([ 'id' => $id ]))) {
throw $this->createNotFoundException($translator->trans(sprintf('%s.not_found', $this->getKey()), [], 'exception'));
}
$manager->moveDown($entity, 1);
$this->addFlash('success', $translator->trans(sprintf('%s.saved', $this->getKey()), [], 'flashmessage'));
return $this->redirectToRoute(sprintf('manage_%s__index', $this->getKey()));
}
/**
* Function that acts as hatch for serving request to correct bulk factory.
* @param Request $request
* @return JsonResponse
*/
public function bulkAjaxAction(Request $request): JsonResponse
{
$translator = $this->get('translator');
$manager = $this->get($this->getManagerClass());
$action = $request->request->get('action');
$ids = $request->request->get('ids');
if (empty($action)) {
$this->addFlash('warning', $translator->trans('bulk.empty_action', [], 'flashmessage'));
}
else {
if(!empty($ids)) {
$bulkProvider = $this->get(BulkProvider::class);
list($factoryKey, $field) = array_pad(explode('#', $action), 2, '');
/** @var BulkFactory $bulkFactory */
$bulkFactory = $bulkProvider->getFactoryActions()[$factoryKey] ?? null;
if ($bulkFactory !== null) {
$bulkFactory->handleBulk($ids, $field, $manager);
$bulkFactory->postSuccessMessage($this->getKey(), $field);
}
}
else {
$this->addFlash('warning', $translator->trans($this->getKey() . '.bulk.empty_ids', [], 'flashmessage'));
}
}
return new JsonResponse(array(
'redirect_url' => $this->generateUrl('manage_' . $this->getKey() . '__index')
));
}
/**
* {@inheritdoc}
*/
public function searchAction(Request $request): Response
{
// ...
}
}