ecommerce121/util-bundle/Controller/ControllerBase.php line 457

Open in your IDE?
  1. <?php
  2. namespace Ecommerce121\UtilBundle\Controller;
  3. use App\Entity\User;
  4. use App\Security\Voter\UserPermissionVoter;
  5. use App\ValueObject\UserPermission;
  6. use App\ValueObject\UserRoles;
  7. use Ecommerce121\UtilBundle\Http\JsonResponse;
  8. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  9. use Symfony\Component\Form\Form;
  10. use Symfony\Component\Form\FormBuilder;
  11. use Symfony\Component\Form\FormTypeInterface;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpFoundation\StreamedResponse;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  19. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  20. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  21. use Symfony\Component\Validator\Validator\ValidatorInterface;
  22. /**
  23.  * Base class with convenient utility methods for controllers.
  24.  */
  25. class ControllerBase
  26. {
  27.     /**
  28.      * @var ControllerUtil
  29.      */
  30.     private $controllerUtil;
  31.     /**
  32.      * Constructor.
  33.      *
  34.      * @param ControllerUtil $controllerUtil
  35.      */
  36.     public function __construct(ControllerUtil $controllerUtil)
  37.     {
  38.         $this->controllerUtil $controllerUtil;
  39.     }
  40.     /**
  41.      * Returns a NotFoundHttpException.
  42.      *
  43.      * This will result in a 404 response code. Usage example:
  44.      * <code>
  45.      *     throw $this->createNotFoundException('Page not found!');
  46.      * </code>
  47.      *
  48.      * @param string          $message  An error message
  49.      * @param \Exception|null $previous The previous exception
  50.      *
  51.      * @return NotFoundHttpException
  52.      */
  53.     protected function createNotFoundException($message 'Not Found', \Exception $previous null)
  54.     {
  55.         return new NotFoundHttpException($message$previous);
  56.     }
  57.     /**
  58.      * Returns an AccessDeniedException.
  59.      *
  60.      * This will result in a 403 response code. Usage example:
  61.      * <code>
  62.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  63.      * </code>
  64.      *
  65.      * @param string          $message  An error message
  66.      * @param \Exception|null $previous The previous exception
  67.      *
  68.      * @return AccessDeniedException
  69.      */
  70.     protected function createAccessDeniedException($message 'Access Denied', \Exception $previous null)
  71.     {
  72.         return new AccessDeniedException($message$previous);
  73.     }
  74.     /**
  75.      * Returns a RedirectResponse to the given URL.
  76.      *
  77.      * @param string $url    The URL to redirect to
  78.      * @param int    $status The status code to use for the Response
  79.      *
  80.      * @return RedirectResponse
  81.      */
  82.     protected function redirect($url$status 302)
  83.     {
  84.         return new RedirectResponse($url$status);
  85.     }
  86.     /**
  87.      * Redirects user to 404 page unless the request is an Ajax request.
  88.      *
  89.      * @param Request $request Http request.
  90.      *
  91.      * @throws NotFoundHttpException if the request is not an ajax request
  92.      */
  93.     protected function forward404UnlessIsAjaxRequest(Request $request)
  94.     {
  95.         if (!$request->isXmlHttpRequest()) {
  96.             throw $this->createNotFoundException();
  97.         }
  98.     }
  99.     /**
  100.      * Redirects user to 404 page if the condition is met.
  101.      *
  102.      * @param bool   $condition Condition
  103.      * @param string $message   Message to return in the 404 error
  104.      *
  105.      * @throws NotFoundHttpException if the $condition is met
  106.      */
  107.     protected function forward404If($condition$message 'Not Found')
  108.     {
  109.         if ($condition) {
  110.             throw $this->createNotFoundException($message);
  111.         }
  112.     }
  113.     /**
  114.      * Redirects user to 404 page unless the condition is met.
  115.      *
  116.      * @param mixed  $condition Condition
  117.      * @param string $message   Message to return in the 404 error
  118.      *
  119.      * @throws NotFoundHttpException if the $condition is not met
  120.      */
  121.     protected function forward404Unless($condition$message 'Not Found')
  122.     {
  123.         if (!$condition) {
  124.             throw $this->createNotFoundException($message);
  125.         }
  126.     }
  127.     /**
  128.      * Returns a json response with a json encoded array.
  129.      *
  130.      * @param array $result Array to encode to Json
  131.      *
  132.      * @return JsonResponse Json encoded response
  133.      */
  134.     protected function json(array $result = array())
  135.     {
  136.         return new JsonResponse($result);
  137.     }
  138.     /**
  139.      * Returns a json response that contains an html view and a json encoded array.
  140.      *
  141.      * @param string $viewName       View name to render
  142.      * @param array  $viewParameters View parameters
  143.      * @param array  $result         Array to encode to Json
  144.      *
  145.      * @return JsonResponse Json encoded response
  146.      */
  147.     protected function jsonView($viewName, array $viewParameters = array(), array $result = array())
  148.     {
  149.         $html $this->renderView($viewName$viewParameters);
  150.         $result array_merge($result, ['html' => $html]);
  151.         return $this->jsonResult($result);
  152.     }
  153.     /**
  154.      * Returns an excel file to be downloaded.
  155.      *
  156.      * @param string $viewName       Excel html view name to render
  157.      * @param string $filename       Downloaded file name
  158.      * @param array  $viewParameters View parameters
  159.      *
  160.      * @return Response
  161.      */
  162.     protected function excelView($viewName$filename$viewParameters = array())
  163.     {
  164.         $response $this->render($viewName$viewParameters);
  165.         $response->headers->set('Content-Type''application/vnd.ms-excel;charset=utf-8');
  166.         $response->headers->set('Content-Disposition''attachment;filename='.$filename);
  167.         return $response;
  168.     }
  169.     /**
  170.      * Generates a URL from the given parameters.
  171.      *
  172.      * @param string         $route         The name of the route
  173.      * @param mixed          $parameters    An array of parameters
  174.      * @param Boolean|string $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
  175.      *
  176.      * @return string The generated URL
  177.      *
  178.      * @see UrlGeneratorInterface
  179.      */
  180.     protected function generateUrl($route$parameters = array(), $referenceType UrlGeneratorInterface::ABSOLUTE_PATH)
  181.     {
  182.         return $this->controllerUtil->generateUrl($route$parameters$referenceType);
  183.     }
  184.     /**
  185.      * Forwards the request to another controller.
  186.      *
  187.      * @param Request $request    The current request
  188.      * @param string  $controller The controller name (a string like BlogBundle:Post:index)
  189.      * @param array   $path       An array of path parameters
  190.      * @param array   $query      An array of query parameters
  191.      *
  192.      * @return Response A Response instance
  193.      */
  194.     protected function forward(Request $request$controller, array $path = array(), array $query = array())
  195.     {
  196.         return $this->controllerUtil->forward($request$controller$path$query);
  197.     }
  198.     /**
  199.      * Returns a rendered view.
  200.      *
  201.      * @param string $view       The view name
  202.      * @param array  $parameters An array of parameters to pass to the view
  203.      *
  204.      * @return string The rendered view
  205.      */
  206.     protected function renderView($view, array $parameters = array())
  207.     {
  208.         return $this->controllerUtil->renderView($view$parameters);
  209.     }
  210.     /**
  211.      * Renders a view.
  212.      *
  213.      * @param string   $view       The view name
  214.      * @param array    $parameters An array of parameters to pass to the view
  215.      * @param Response $response   A response instance
  216.      *
  217.      * @return Response A Response instance
  218.      */
  219.     protected function render($view, array $parameters = array(), Response $response null)
  220.     {
  221.         return $this->controllerUtil->render($view$parameters$response);
  222.     }
  223.     /**
  224.      * Streams a view.
  225.      *
  226.      * @param string           $view       The view name
  227.      * @param array            $parameters An array of parameters to pass to the view
  228.      * @param StreamedResponse $response   A response instance
  229.      *
  230.      * @return StreamedResponse A StreamedResponse instance
  231.      */
  232.     protected function stream($view, array $parameters = array(), StreamedResponse $response null)
  233.     {
  234.         return $this->controllerUtil->stream($view$parameters$response);
  235.     }
  236.     /**
  237.      * Creates and returns a Form instance from the type of the form.
  238.      *
  239.      * @param string|FormTypeInterface $type    The built type of the form
  240.      * @param mixed                    $data    The initial data for the form
  241.      * @param array                    $options Options for the form
  242.      *
  243.      * @return Form
  244.      */
  245.     protected function createForm($type$data null, array $options = array())
  246.     {
  247.         return $this->controllerUtil->createForm($type$data$options);
  248.     }
  249.     /**
  250.      * Creates and returns a form builder instance.
  251.      *
  252.      * @param mixed $data    The initial data for the form
  253.      * @param array $options Options for the form
  254.      *
  255.      * @return FormBuilder
  256.      */
  257.     protected function createFormBuilder($data null, array $options = array())
  258.     {
  259.         return $this->controllerUtil->createFormBuilder($data$options);
  260.     }
  261.     /**
  262.      * Gets doctrine entity manager.
  263.      *
  264.      * @return \Doctrine\ORM\EntityManagerInterface Doctrine's entity manager
  265.      */
  266.     protected function getEntityManager()
  267.     {
  268.         return $this->controllerUtil->getEntityManager();
  269.     }
  270.     /**
  271.      * Gets a doctrine's entity proxy for use without loading object from database.
  272.      *
  273.      * @param string $entityName Entity class name (e.g. MyNeeds:User)
  274.      * @param string $id         Entity database identifier
  275.      *
  276.      * @return object Entity proxy
  277.      */
  278.     protected function getEntityReference($entityName$id)
  279.     {
  280.         return $this->controllerUtil->getEntityReference($entityName$id);
  281.     }
  282.     /**
  283.      * Translates the given message.
  284.      *
  285.      * @param string $id         The message id (may also be an object that can be cast to string)
  286.      * @param array  $parameters An array of parameters for the message
  287.      * @param string $domain     The domain for the message
  288.      * @param string $locale     The locale
  289.      *
  290.      * @return string The translated string
  291.      */
  292.     protected function trans($id, array $parameters = array(), $domain 'messages'$locale null)
  293.     {
  294.         return $this->controllerUtil->trans($id$parameters$domain$locale);
  295.     }
  296.     /**
  297.      * Translates the given choice message by choosing a translation according to a number.
  298.      *
  299.      * @param string $id         The message id (may also be an object that can be cast to string)
  300.      * @param int    $number     The number to use to find the indice of the message
  301.      * @param array  $parameters An array of parameters for the message
  302.      * @param string $domain     The domain for the message
  303.      * @param string $locale     The locale
  304.      *
  305.      * @return string The translated string
  306.      */
  307.     protected function transChoice($id$number, array $parameters = array(), $domain 'messages'$locale null)
  308.     {
  309.         return $this->controllerUtil->transChoice($id$number$parameters$domain$locale);
  310.     }
  311.     /**
  312.      * Get a user from the TokenStorage.
  313.      *
  314.      * @return mixed
  315.      *
  316.      * @throws \LogicException If SecurityBundle is not available
  317.      *
  318.      * @see Symfony\Component\Security\Core\Authentication\Token\TokenInterface::getUser()
  319.      */
  320.     protected function getUser(): ?User
  321.     {
  322.         return $this->controllerUtil->getUser();
  323.     }
  324.     /**
  325.      * Gets the validator component.
  326.      *
  327.      * @return ValidatorInterface
  328.      */
  329.     protected function getValidator()
  330.     {
  331.         return $this->controllerUtil->getValidator();
  332.     }
  333.     /**
  334.      * Gets the event dispatcher component.
  335.      *
  336.      * @return EventDispatcherInterface
  337.      */
  338.     protected function getEventDispatcher()
  339.     {
  340.         return $this->controllerUtil->getEventDispatcher();
  341.     }
  342.     /**
  343.      * Dispatchs an event in the event dispatcher.
  344.      *
  345.      * @param string     $eventName The name of the event
  346.      * @param object|null $event     The event object to be dispatched
  347.      */
  348.     protected function dispatchEvent($eventName$event null)
  349.     {
  350.         $this->controllerUtil->getEventDispatcher()->dispatch($event$eventName);
  351.     }
  352.     /**
  353.      * Gets the controllerUtil object.
  354.      *
  355.      * @return ControllerUtil
  356.      */
  357.     protected function getControllerUtil()
  358.     {
  359.         return $this->controllerUtil;
  360.     }
  361.     /**
  362.      * Gets the token storage component.
  363.      *
  364.      * @return TokenStorageInterface
  365.      */
  366.     protected function getTokenStorage()
  367.     {
  368.         return $this->controllerUtil->getTokenStorage();
  369.     }
  370.     /**
  371.      * Gets the Symfony kernel root dir.
  372.      *
  373.      * @return string
  374.      */
  375.     protected function getKernelRootDir()
  376.     {
  377.         return $this->controllerUtil->getKernelRootDir();
  378.     }
  379.     /**
  380.      * Gets the project uploads path.
  381.      *
  382.      * @return string
  383.      */
  384.     protected function getUploadsPath()
  385.     {  
  386.         return $this->getKernelRootDir().'/publc/uploads/';
  387.     }
  388.     
  389.     /**
  390.      * @return JsonResponse
  391.      */
  392.     protected function jsonResult(array $data = [])
  393.     {
  394.         return $this->json([
  395.             'hasError' => false,
  396.             'result' => $data
  397.         ]);
  398.     }
  399.     /**
  400.      * @return JsonResponse
  401.      */    
  402.     protected function jsonError($message ''$code = -1)
  403.     {
  404.         $data = [
  405.             'hasError' => true,
  406.             'error' => [
  407.                 'message' => $message,
  408.                 'code' => $code
  409.             ]
  410.         ];
  411.         return $this->json($data);
  412.     }
  413.     /**
  414.      * @param string|UserRoles|UserPermission $attribute
  415.      * @param mixed $subject
  416.      */
  417.     public function denyAccessUnlessGranted($attribute$subject nullstring $message 'Access Denied.'): void
  418.     {
  419.             $this->denyAccessUnlessGrantedCheck($attribute$subject$message);
  420.     }
  421.     protected function denyAccessUnlessGrantedCheck($attribute$subject nullstring $message 'Access Denied.'): void
  422.     {
  423.         if (!$this->isGranted($attribute$subject)) {
  424.             $exception $this->createAccessDeniedException($message);
  425.             $exception->setAttributes([$attribute]);
  426.             $exception->setSubject($subject);
  427.             throw $exception;
  428.         }
  429.     }
  430.     public function getAdmin(): ?User
  431.     {
  432.         $user $this->getUser();
  433.         if (null === $user) {
  434.             return null;
  435.         }
  436.         if (!($user instanceof User)) {
  437.             throw new AuthenticationException('User must be of User type');
  438.         }
  439.         return $user;
  440.     }
  441.     /**
  442.      * @param string|UserRoles|UserPermission $attribute
  443.      * @param mixed $subject
  444.      */
  445.     protected function isGranted($attribute$subject null): bool
  446.     {
  447.         return $this->getControllerUtil()->getAuthorizationChecker()->isGranted($attribute$subject);
  448.     }
  449. }