src/FMT/Application/Controller/AbstractBaseController.php line 206

Open in your IDE?
  1. <?php
  2. namespace FMT\Application\Controller;
  3. use FMT\Application\Controller\Admin\DashboardController;
  4. use FMT\Data\Entity\User;
  5. use FMT\Domain\Service\Mapper\ObjectToArrayMapper;
  6. use FMT\Infrastructure\Helper\FormHelper;
  7. use FMT\Application\Controller\Common\PublicDashboardController;
  8. use FMT\Application\Controller\Donor\DashboardController as DonorDashboardController;
  9. use FMT\Application\Controller\Donor\ProfileController as DonorProfileController;
  10. use FMT\Application\Controller\Student\DashboardController as StudentDashboardController;
  11. use FMT\Application\Controller\Student\ProfileController as StudentProfileController;
  12. use Knp\Component\Pager\Pagination\PaginationInterface;
  13. use Knp\Component\Pager\PaginatorInterface;
  14. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  15. use Symfony\Component\Form\Form;
  16. use Symfony\Component\Form\FormFactoryInterface;
  17. use Symfony\Component\Form\FormInterface;
  18. use Symfony\Component\Form\FormTypeInterface;
  19. use Symfony\Component\HttpFoundation\JsonResponse;
  20. use Symfony\Component\HttpFoundation\RedirectResponse;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  23. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  24. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  25. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  26. use Symfony\Component\Routing\RouterInterface;
  27. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  28. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  29. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  30. use Symfony\Component\Security\Core\User\UserInterface;
  31. use Symfony\Component\Serializer\Normalizer\NormalizableInterface;
  32. use Symfony\Contracts\Translation\TranslatorInterface;
  33. use Twig\Environment;
  34. /**
  35.  * Class AbstractBaseController
  36.  * @package FMT\Application\Controller
  37.  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  38.  * @SuppressWarnings(PHPMD.NumberOfChildren)
  39.  */
  40. abstract class AbstractBaseController
  41. {
  42.     /**
  43.      * @var SessionInterface
  44.      */
  45.     private $session;
  46.     /**
  47.      * @var FormFactoryInterface
  48.      */
  49.     private $formFactory;
  50.     /**
  51.      * @var TokenStorageInterface
  52.      */
  53.     private $tokenStorage;
  54.     /**
  55.      * @var RouterInterface
  56.      */
  57.     private $router;
  58.     /**
  59.      * @var Environment
  60.      */
  61.     private $templating;
  62.     /**
  63.      * @var AuthorizationCheckerInterface
  64.      */
  65.     private $authorizationChecker;
  66.     /**
  67.      * @var EventDispatcherInterface
  68.      */
  69.     private $eventDispatcher;
  70.     /**
  71.      * @var TranslatorInterface
  72.      */
  73.     private $translator;
  74.     /**
  75.      * @var PaginatorInterface $paginator
  76.      */
  77.     protected $paginator;
  78.     /**
  79.      * @required
  80.      * @param AuthorizationCheckerInterface $authorizationChecker
  81.      * @return AbstractBaseController
  82.      * @required
  83.      */
  84.     public function setAuthorizationChecker(AuthorizationCheckerInterface $authorizationChecker)
  85.     {
  86.         $this->authorizationChecker $authorizationChecker;
  87.         return $this;
  88.     }
  89.     /**
  90.      * @param SessionInterface $session
  91.      * @return AbstractBaseController
  92.      * @required
  93.      */
  94.     public function setSession(SessionInterface $session)
  95.     {
  96.         $this->session $session;
  97.         return $this;
  98.     }
  99.     /**
  100.      * @param FormFactoryInterface $formFactory
  101.      * @return AbstractBaseController
  102.      * @required
  103.      */
  104.     public function setFormFactory(FormFactoryInterface $formFactory)
  105.     {
  106.         $this->formFactory $formFactory;
  107.         return $this;
  108.     }
  109.     /**
  110.      * @param TokenStorageInterface $tokenStorage
  111.      * @return AbstractBaseController
  112.      * @required
  113.      */
  114.     public function setTokenStorage(TokenStorageInterface $tokenStorage)
  115.     {
  116.         $this->tokenStorage $tokenStorage;
  117.         return $this;
  118.     }
  119.     /**
  120.      * @param RouterInterface $router
  121.      * @return AbstractBaseController
  122.      * @required
  123.      */
  124.     public function setRouter(RouterInterface $router)
  125.     {
  126.         $this->router $router;
  127.         return $this;
  128.     }
  129.     /**
  130.      * @param Environment $templating
  131.      * @return AbstractBaseController
  132.      * @required
  133.      */
  134.     public function setTemplating(Environment $templating)
  135.     {
  136.         $this->templating $templating;
  137.         return $this;
  138.     }
  139.     /**
  140.      * @param EventDispatcherInterface $eventDispatcher
  141.      * @return $this
  142.      * @required
  143.      */
  144.     public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
  145.     {
  146.         $this->eventDispatcher $eventDispatcher;
  147.         return $this;
  148.     }
  149.     /**
  150.      * @required
  151.      * @param TranslatorInterface $translator
  152.      * @return $this
  153.      */
  154.     public function setTranslator(TranslatorInterface $translator)
  155.     {
  156.         $this->translator $translator;
  157.         return $this;
  158.     }
  159.     /**
  160.      * @required
  161.      * @param PaginatorInterface $paginator
  162.      */
  163.     public function setPaginator(PaginatorInterface  $paginator)
  164.     {
  165.         $this->paginator $paginator;
  166.     }
  167.     /**
  168.      * Creates and returns a Form instance from the type of the form.
  169.      *
  170.      * @param string|FormTypeInterface $type The built type of the form
  171.      * @param mixed $data The initial data for the form
  172.      * @param array $options Options for the form
  173.      *
  174.      * @return FormInterface|Form
  175.      */
  176.     protected function createForm($type$data null, array $options = [])
  177.     {
  178.         return $this->formFactory->create($type$data$options);
  179.     }
  180.     /**
  181.      * Get a user from the Security Token Storage.
  182.      *
  183.      * @return UserInterface|null|User|NormalizableInterface
  184.      *
  185.      * @throws \LogicException If SecurityBundle is not available
  186.      *
  187.      * @see TokenInterface::getUser()
  188.      */
  189.     protected function getUser()
  190.     {
  191.         if (null === $token $this->tokenStorage->getToken()) {
  192.             return null;
  193.         }
  194.         if (!is_object($user $token->getUser())) {
  195.             return null;
  196.         }
  197.         return $user;
  198.     }
  199.     /**
  200.      * Generates a URL from the given parameters.
  201.      *
  202.      * @param string $route The name of the route
  203.      * @param mixed $parameters An array of parameters
  204.      * @param int $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
  205.      *
  206.      * @return string The generated URL
  207.      *
  208.      * @see UrlGeneratorInterface
  209.      */
  210.     protected function generateUrl($route$parameters = [], $referenceType UrlGeneratorInterface::ABSOLUTE_PATH)
  211.     {
  212.         return $this->router->generate($route$parameters$referenceType);
  213.     }
  214.     /**
  215.      * Returns a RedirectResponse to the given URL.
  216.      *
  217.      * @param string $url The URL to redirect to
  218.      * @param int $status The status code to use for the Response
  219.      *
  220.      * @return RedirectResponse
  221.      */
  222.     protected function redirect($url$status 302)
  223.     {
  224.         return new RedirectResponse($url$status);
  225.     }
  226.     /**
  227.      * Returns a RedirectResponse to the given route with the given parameters.
  228.      *
  229.      * @param string $route The name of the route
  230.      * @param array $parameters An array of parameters
  231.      * @param int $status The status code to use for the Response
  232.      *
  233.      * @return RedirectResponse
  234.      */
  235.     protected function redirectToRoute($route, array $parameters = [], $status 302)
  236.     {
  237.         return $this->redirect($this->generateUrl($route$parameters), $status);
  238.     }
  239.     /**
  240.      * Returns a NotFoundHttpException.
  241.      *
  242.      * This will result in a 404 response code. Usage example:
  243.      *
  244.      *     throw $this->createNotFoundException('Page not found!');
  245.      *
  246.      * @param string $message A message
  247.      * @param \Exception|null $previous The previous exception
  248.      *
  249.      * @return NotFoundHttpException
  250.      */
  251.     protected function createNotFoundException($message 'Not Found'\Exception $previous null)
  252.     {
  253.         return new NotFoundHttpException($message$previous);
  254.     }
  255.     /**
  256.      * Returns a rendered view.
  257.      *
  258.      * @param string $view The view name
  259.      * @param array $parameters An array of parameters to pass to the view
  260.      *
  261.      * @return string The rendered view
  262.      */
  263.     protected function renderView($view, array $parameters = [])
  264.     {
  265.         return $this->templating->render($view$parameters);
  266.     }
  267.     /**
  268.      * @param mixed $attributes The attributes
  269.      * @param mixed $object The object
  270.      *
  271.      * @return bool
  272.      *
  273.      * @throws \LogicException
  274.      */
  275.     protected function isGranted($attributes$object null)
  276.     {
  277.         return $this->authorizationChecker->isGranted($attributes$object);
  278.     }
  279.     /**
  280.      * @param mixed $attributes The attributes
  281.      * @param mixed $object The object
  282.      * @param string $message The message passed to the exception
  283.      *
  284.      * @throws AccessDeniedException
  285.      */
  286.     protected function denyAccessUnlessGranted($attributes$object null$message 'Access Denied.')
  287.     {
  288.         if (!$this->isGranted($attributes$object)) {
  289.             throw new AccessDeniedException($message);
  290.         }
  291.     }
  292.     /**
  293.      * @param $message
  294.      * @param bool $translate
  295.      * @param array $parameters
  296.      */
  297.     protected function addFlashBagNotice($message$translate true$parameters = [])
  298.     {
  299.         if ($translate) {
  300.             $message $this->translate($message$parameters);
  301.         }
  302.         $this->session->getFlashBag()->add("success"$message);
  303.     }
  304.     /**
  305.      * @param $message
  306.      * @param bool $translate
  307.      * @param array $parameters
  308.      */
  309.     protected function addFlashBagError($message$translate true$parameters = [])
  310.     {
  311.         if ($translate) {
  312.             $message $this->translate($message$parameters);
  313.         }
  314.         $this->session->getFlashBag()->add("error"$message);
  315.     }
  316.     /**
  317.      * @param $message
  318.      * @param bool $translate
  319.      * @param array $parameters
  320.      * @return void
  321.      */
  322.     protected function addFlashBagWarning($message$translate true$parameters = [])
  323.     {
  324.         if ($translate) {
  325.             $message $this->translate($message$parameters);
  326.         }
  327.         $this->session->getFlashBag()->add("warning"$message);
  328.     }
  329.     /**
  330.      * @param string|null $type
  331.      */
  332.     protected function clearFlashBag($type)
  333.     {
  334.         if ($type) {
  335.             $this->session->getFlashBag()->get($type);
  336.         } else {
  337.             $this->session->getFlashBag()->all();
  338.         }
  339.     }
  340.     /**
  341.      * @param string $name
  342.      * @param mixed $default
  343.      * @return mixed
  344.      */
  345.     protected function getSessionVariable($name$default null)
  346.     {
  347.         return $this->session->get($name$default);
  348.     }
  349.     /**
  350.      * @param string $name
  351.      * @param mixed $value
  352.      * @return $this
  353.      */
  354.     protected function setSessionVariable($name$value)
  355.     {
  356.         if (is_null($value)) {
  357.             $this->session->remove($name);
  358.         } else {
  359.             $this->session->set($name$value);
  360.         }
  361.         return $this;
  362.     }
  363.     /**
  364.      * @param string $name
  365.      * @return bool
  366.      */
  367.     protected function hasSessionVariable($name)
  368.     {
  369.         return $this->session->has($name);
  370.     }
  371.     /**
  372.      * @param Request $request
  373.      */
  374.     protected function checkAjaxRequest(Request $request)
  375.     {
  376.         if (!$request->isXmlHttpRequest()) {
  377.             throw new BadRequestHttpException('fmt.ajax.ajax_only');
  378.         }
  379.     }
  380.     /**
  381.      * @param $data
  382.      * @return JsonResponse
  383.      */
  384.     protected function createFailureAjaxResponse($data null)
  385.     {
  386.         return $this->createAjaxResponse($datafalse);
  387.     }
  388.     /**
  389.      * @param $data
  390.      * @return JsonResponse
  391.      */
  392.     protected function createSuccessAjaxResponse($data null)
  393.     {
  394.         return $this->createAjaxResponse($datatrue);
  395.     }
  396.     /**
  397.      * @param $data
  398.      * @param $status
  399.      * @param $urlRedirect
  400.      * @return JsonResponse
  401.      */
  402.     protected function createAjaxResponse($data$status$urlRedirect false)
  403.     {
  404.         $messages $this->session->getFlashBag()->all();
  405.         $response = [
  406.             'success' => $status,
  407.         ];
  408.         if (!empty($data)) {
  409.             $response['data'] = $data;
  410.         }
  411.         if (!empty($messages)) {
  412.             $response['messages'] = $messages;
  413.         }
  414.         if ($urlRedirect !== false) {
  415.             $response['redirect'] = $urlRedirect;
  416.         }
  417.         return new JsonResponse($response);
  418.     }
  419.     /**
  420.      * @param FormInterface $form
  421.      * @param array $data
  422.      * @return JsonResponse
  423.      */
  424.     protected function createValidationErrorsResponse(FormInterface $form$data = [])
  425.     {
  426.         $errors = [
  427.             'errors' => FormHelper::collectErrors($form)
  428.         ];
  429.         return $this->createAjaxResponse(array_merge($data$errors), false);
  430.     }
  431.     /**
  432.      * @param $source
  433.      * @param int $maxLevel
  434.      * @param int $level
  435.      * @return array
  436.      */
  437.     protected function normalizeObjectsForAjax($source$maxLevel 1$level 1)
  438.     {
  439.         $result = [];
  440.         if (!is_array($source) && $source instanceof \Traversable) {
  441.             return $result;
  442.         }
  443.         foreach ($source as $item) {
  444.             $result[] = $this->normalizeObjectForAjax($item$maxLevel$level);
  445.         }
  446.         return $result;
  447.     }
  448.     /**
  449.      * @param $item
  450.      * @param int $maxLevel
  451.      * @param int $level
  452.      * @return array
  453.      */
  454.     protected function normalizeObjectForAjax($item$maxLevel 1$level 1)
  455.     {
  456.         if (!is_object($item)) {
  457.             return [];
  458.         }
  459.         return ObjectToArrayMapper::map($item$maxLevel$level);
  460.     }
  461.     /**
  462.      * @param string $message
  463.      * @param array $parameters
  464.      * @param string|null $domain
  465.      * @return string
  466.      */
  467.     protected function translate($message$parameters = [], $domain null)
  468.     {
  469.         return $this->translator->trans($message$parameters$domain);
  470.     }
  471.     /**
  472.      * @param $target
  473.      * @param int $page
  474.      * @param int $limit
  475.      * @param array $options
  476.      * @return PaginationInterface
  477.      */
  478.     protected function paginate($targetint $page 1int $limit 10$options = [])
  479.     {
  480.         return $this->paginator->paginate($target$page$limit$options);
  481.     }
  482.     /**
  483.      * @param User $user
  484.      * @return string
  485.      */
  486.     protected function generateSuccessRedirectHref(User $user): string
  487.     {
  488.         $roleRouteMap = [
  489.             User::ROLE_DONOR              => DonorDashboardController::ROUTE_INDEX,
  490.             User::ROLE_STUDENT            => StudentDashboardController::ROUTE_INDEX,
  491.             User::ROLE_INCOMPLETE_DONOR   => DonorProfileController::ROUTE_INDEX,
  492.             User::ROLE_INCOMPLETE_STUDENT => StudentProfileController::ROUTE_INDEX,
  493.         ];
  494.         $roles $user->getRoles();
  495.         foreach ($roleRouteMap as $role => $routeName) {
  496.             if (in_array($role$roles)) {
  497.                 $resultRouteName $routeName;
  498.                 break;
  499.             }
  500.         }
  501.         if (empty($resultRouteName)) {
  502.             $resultRouteName PublicDashboardController::ROUTE_INDEX;
  503.         }
  504.         if ($user->isInternal()) {
  505.             $resultRouteName DashboardController::ROUTE_INDEX;
  506.         }
  507.         return $this->generateUrl($resultRouteName, [], UrlGeneratorInterface::ABSOLUTE_URL);
  508.     }
  509. }