vendor/symfony/framework-bundle/Controller/ControllerTrait.php line 233

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\FrameworkBundle\Controller;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Psr\Container\ContainerInterface;
  13. use Psr\Link\LinkInterface;
  14. use Symfony\Component\Form\Extension\Core\Type\FormType;
  15. use Symfony\Component\Form\FormBuilderInterface;
  16. use Symfony\Component\Form\FormInterface;
  17. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  23. use Symfony\Component\HttpFoundation\StreamedResponse;
  24. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  25. use Symfony\Component\HttpKernel\HttpKernelInterface;
  26. use Symfony\Component\Messenger\Envelope;
  27. use Symfony\Component\Messenger\Stamp\StampInterface;
  28. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  29. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  30. use Symfony\Component\Security\Core\User\UserInterface;
  31. use Symfony\Component\Security\Csrf\CsrfToken;
  32. use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
  33. use Symfony\Component\WebLink\GenericLinkProvider;
  34. /**
  35.  * Common features needed in controllers.
  36.  *
  37.  * @author Fabien Potencier <fabien@symfony.com>
  38.  *
  39.  * @internal
  40.  *
  41.  * @property ContainerInterface $container
  42.  */
  43. trait ControllerTrait
  44. {
  45.     /**
  46.      * Returns true if the service id is defined.
  47.      *
  48.      * @final
  49.      */
  50.     protected function has(string $id): bool
  51.     {
  52.         return $this->container->has($id);
  53.     }
  54.     /**
  55.      * Gets a container service by its id.
  56.      *
  57.      * @return object The service
  58.      *
  59.      * @final
  60.      */
  61.     protected function get(string $id)
  62.     {
  63.         return $this->container->get($id);
  64.     }
  65.     /**
  66.      * Generates a URL from the given parameters.
  67.      *
  68.      * @see UrlGeneratorInterface
  69.      *
  70.      * @final
  71.      */
  72.     protected function generateUrl(string $route, array $parameters = [], int $referenceType UrlGeneratorInterface::ABSOLUTE_PATH): string
  73.     {
  74.         return $this->container->get('router')->generate($route$parameters$referenceType);
  75.     }
  76.     /**
  77.      * Forwards the request to another controller.
  78.      *
  79.      * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction)
  80.      *
  81.      * @final
  82.      */
  83.     protected function forward(string $controller, array $path = [], array $query = []): Response
  84.     {
  85.         $request $this->container->get('request_stack')->getCurrentRequest();
  86.         $path['_controller'] = $controller;
  87.         $subRequest $request->duplicate($querynull$path);
  88.         return $this->container->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  89.     }
  90.     /**
  91.      * Returns a RedirectResponse to the given URL.
  92.      *
  93.      * @final
  94.      */
  95.     protected function redirect(string $urlint $status 302): RedirectResponse
  96.     {
  97.         return new RedirectResponse($url$status);
  98.     }
  99.     /**
  100.      * Returns a RedirectResponse to the given route with the given parameters.
  101.      *
  102.      * @final
  103.      */
  104.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  105.     {
  106.         return $this->redirect($this->generateUrl($route$parameters), $status);
  107.     }
  108.     /**
  109.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  110.      *
  111.      * @final
  112.      */
  113.     protected function json($dataint $status 200, array $headers = [], array $context = []): JsonResponse
  114.     {
  115.         if ($this->container->has('serializer')) {
  116.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  117.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  118.             ], $context));
  119.             return new JsonResponse($json$status$headerstrue);
  120.         }
  121.         return new JsonResponse($data$status$headers);
  122.     }
  123.     /**
  124.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  125.      *
  126.      * @param \SplFileInfo|string $file File object or path to file to be sent as response
  127.      *
  128.      * @final
  129.      */
  130.     protected function file($filestring $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  131.     {
  132.         $response = new BinaryFileResponse($file);
  133.         $response->setContentDisposition($disposition$fileName ?? $response->getFile()->getFilename());
  134.         return $response;
  135.     }
  136.     /**
  137.      * Adds a flash message to the current session for type.
  138.      *
  139.      * @throws \LogicException
  140.      *
  141.      * @final
  142.      */
  143.     protected function addFlash(string $type$message)
  144.     {
  145.         if (!$this->container->has('session')) {
  146.             throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
  147.         }
  148.         $this->container->get('session')->getFlashBag()->add($type$message);
  149.     }
  150.     /**
  151.      * Checks if the attributes are granted against the current authentication token and optionally supplied subject.
  152.      *
  153.      * @throws \LogicException
  154.      *
  155.      * @final
  156.      */
  157.     protected function isGranted($attributes$subject null): bool
  158.     {
  159.         if (!$this->container->has('security.authorization_checker')) {
  160.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  161.         }
  162.         return $this->container->get('security.authorization_checker')->isGranted($attributes$subject);
  163.     }
  164.     /**
  165.      * Throws an exception unless the attributes are granted against the current authentication token and optionally
  166.      * supplied subject.
  167.      *
  168.      * @throws AccessDeniedException
  169.      *
  170.      * @final
  171.      */
  172.     protected function denyAccessUnlessGranted($attributes$subject nullstring $message 'Access Denied.')
  173.     {
  174.         if (!$this->isGranted($attributes$subject)) {
  175.             $exception $this->createAccessDeniedException($message);
  176.             $exception->setAttributes($attributes);
  177.             $exception->setSubject($subject);
  178.             throw $exception;
  179.         }
  180.     }
  181.     /**
  182.      * Returns a rendered view.
  183.      *
  184.      * @final
  185.      */
  186.     protected function renderView(string $view, array $parameters = []): string
  187.     {
  188.         if ($this->container->has('templating') && $this->container->get('templating')->supports($view)) {
  189.             @trigger_error('Using the "templating" service is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', \E_USER_DEPRECATED);
  190.             return $this->container->get('templating')->render($view$parameters);
  191.         }
  192.         if (!$this->container->has('twig')) {
  193.             throw new \LogicException('You can not use the "renderView" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
  194.         }
  195.         return $this->container->get('twig')->render($view$parameters);
  196.     }
  197.     /**
  198.      * Renders a view.
  199.      *
  200.      * @final
  201.      */
  202.     protected function render(string $view, array $parameters = [], Response $response null): Response
  203.     {
  204.         if ($this->container->has('templating') && $this->container->get('templating')->supports($view)) {
  205.             @trigger_error('Using the "templating" service is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', \E_USER_DEPRECATED);
  206.             $content $this->container->get('templating')->render($view$parameters);
  207.         } elseif ($this->container->has('twig')) {
  208.             $content $this->container->get('twig')->render($view$parameters);
  209.         } else {
  210.             throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
  211.         }
  212.         if (null === $response) {
  213.             $response = new Response();
  214.         }
  215.         $response->setContent($content);
  216.         return $response;
  217.     }
  218.     /**
  219.      * Streams a view.
  220.      *
  221.      * @final
  222.      */
  223.     protected function stream(string $view, array $parameters = [], StreamedResponse $response null): StreamedResponse
  224.     {
  225.         if ($this->container->has('templating')) {
  226.             @trigger_error('Using the "templating" service is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', \E_USER_DEPRECATED);
  227.             $templating $this->container->get('templating');
  228.             $callback = function () use ($templating$view$parameters) {
  229.                 $templating->stream($view$parameters);
  230.             };
  231.         } elseif ($this->container->has('twig')) {
  232.             $twig $this->container->get('twig');
  233.             $callback = function () use ($twig$view$parameters) {
  234.                 $twig->display($view$parameters);
  235.             };
  236.         } else {
  237.             throw new \LogicException('You can not use the "stream" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
  238.         }
  239.         if (null === $response) {
  240.             return new StreamedResponse($callback);
  241.         }
  242.         $response->setCallback($callback);
  243.         return $response;
  244.     }
  245.     /**
  246.      * Returns a NotFoundHttpException.
  247.      *
  248.      * This will result in a 404 response code. Usage example:
  249.      *
  250.      *     throw $this->createNotFoundException('Page not found!');
  251.      *
  252.      * @final
  253.      */
  254.     protected function createNotFoundException(string $message 'Not Found', \Throwable $previous null): NotFoundHttpException
  255.     {
  256.         return new NotFoundHttpException($message$previous);
  257.     }
  258.     /**
  259.      * Returns an AccessDeniedException.
  260.      *
  261.      * This will result in a 403 response code. Usage example:
  262.      *
  263.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  264.      *
  265.      * @throws \LogicException If the Security component is not available
  266.      *
  267.      * @final
  268.      */
  269.     protected function createAccessDeniedException(string $message 'Access Denied.', \Throwable $previous null): AccessDeniedException
  270.     {
  271.         if (!class_exists(AccessDeniedException::class)) {
  272.             throw new \LogicException('You can not use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  273.         }
  274.         return new AccessDeniedException($message$previous);
  275.     }
  276.     /**
  277.      * Creates and returns a Form instance from the type of the form.
  278.      *
  279.      * @final
  280.      */
  281.     protected function createForm(string $type$data null, array $options = []): FormInterface
  282.     {
  283.         return $this->container->get('form.factory')->create($type$data$options);
  284.     }
  285.     /**
  286.      * Creates and returns a form builder instance.
  287.      *
  288.      * @final
  289.      */
  290.     protected function createFormBuilder($data null, array $options = []): FormBuilderInterface
  291.     {
  292.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  293.     }
  294.     /**
  295.      * Shortcut to return the Doctrine Registry service.
  296.      *
  297.      * @return ManagerRegistry
  298.      *
  299.      * @throws \LogicException If DoctrineBundle is not available
  300.      *
  301.      * @final
  302.      */
  303.     protected function getDoctrine()
  304.     {
  305.         if (!$this->container->has('doctrine')) {
  306.             throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
  307.         }
  308.         return $this->container->get('doctrine');
  309.     }
  310.     /**
  311.      * Get a user from the Security Token Storage.
  312.      *
  313.      * @return UserInterface|object|null
  314.      *
  315.      * @throws \LogicException If SecurityBundle is not available
  316.      *
  317.      * @see TokenInterface::getUser()
  318.      *
  319.      * @final
  320.      */
  321.     protected function getUser()
  322.     {
  323.         if (!$this->container->has('security.token_storage')) {
  324.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  325.         }
  326.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  327.             return null;
  328.         }
  329.         if (!\is_object($user $token->getUser())) {
  330.             // e.g. anonymous authentication
  331.             return null;
  332.         }
  333.         return $user;
  334.     }
  335.     /**
  336.      * Checks the validity of a CSRF token.
  337.      *
  338.      * @param string      $id    The id used when generating the token
  339.      * @param string|null $token The actual token sent with the request that should be validated
  340.      *
  341.      * @final
  342.      */
  343.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  344.     {
  345.         if (!$this->container->has('security.csrf.token_manager')) {
  346.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  347.         }
  348.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  349.     }
  350.     /**
  351.      * Dispatches a message to the bus.
  352.      *
  353.      * @param object|Envelope  $message The message or the message pre-wrapped in an envelope
  354.      * @param StampInterface[] $stamps
  355.      *
  356.      * @final
  357.      */
  358.     protected function dispatchMessage($message, array $stamps = []): Envelope
  359.     {
  360.         if (!$this->container->has('messenger.default_bus')) {
  361.             $message class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' 'Try running "composer require symfony/messenger".';
  362.             throw new \LogicException('The message bus is not enabled in your application. '.$message);
  363.         }
  364.         return $this->container->get('messenger.default_bus')->dispatch($message$stamps);
  365.     }
  366.     /**
  367.      * Adds a Link HTTP header to the current response.
  368.      *
  369.      * @see https://tools.ietf.org/html/rfc5988
  370.      *
  371.      * @final
  372.      */
  373.     protected function addLink(Request $requestLinkInterface $link)
  374.     {
  375.         if (!class_exists(AddLinkHeaderListener::class)) {
  376.             throw new \LogicException('You can not use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  377.         }
  378.         if (null === $linkProvider $request->attributes->get('_links')) {
  379.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  380.             return;
  381.         }
  382.         $request->attributes->set('_links'$linkProvider->withLink($link));
  383.     }
  384. }
dobrowin | betleao | moverbet | winzada 777 | supremo | casadeapostas | dobrowin | betleao | moverbet | wazamba | fezbet | betsson | lvbet | dobrowin | betsul | pixbet | bwin | betobet | dobrowin | bet7 | betcris | blaze | 888 | betano | stake | stake | esportesdasorte | betmotion | rivalry | novibet | pinnacle | cbet | dobrowin | betleao | moverbet | gogowin | jogos win | campobet | mesk bet | infinity bet | betfury | doce | bet7k | jogowin | lobo888 | iribet | leao | dobrowin | allwin | aajogo | pgwin | greenbets | brapub | moverbet | onebra | flames | brdice | brwin | poplottery | queens | winbrl | omgbet | winbra | goinbet | codbet | betleao | fuwin | allwin568 | wingdus | juntosbet | today | talon777 | brlwin | fazobetai | pinup bet | bet sport | bet esporte | mrbet | premier bet | apostebet | spicy bet | prosport bet | bet nacional | luck | jogodeouro | heads bet | marjack bet | apostaganha | gbg bet | esoccer bet | esport bet | realbet | aposte e ganhe | aviator aposta | bet vitoria | imperador bet | realsbet | bet favorita | esportenet | flames bet | pague bet | betsury | doce888 | obabet | winzada | globalbet | bet77 | lottoland | 7gamesbet | dicasbet | esportivabet | tvbet | sportbet | misterjackbet | esportebet | nacionalbet | simplesbet | betestrela | batbet | Pk55 | Bet61 | Upsports Bet | roleta online | roleta | poker online | poker | blackjack online | bingo | 12bet | 33win | bet168 | bk8 | bong88 | bong99 | fcb8 | hb88 | hotlive | ibet888 | k8 | kubet77 | kubet | lode88 | mig8 | nbet | onebox63 | oxbet | s666 | sbobet | suncity | vwin | w88 | win2888 | zbet | xoso66 | zowin | sun | top88 | vnloto | 11bet | bet69 | 8xbet | Ceará | Paysandu | Juventude | Bahia | Sport | Cuiabá | Coritiba | Criciúma | Vitória | Fortaleza | Corinthians | São Paulo | Vasco | Grêmio | Fluminense | Cruzeiro | Botafogo | Flamengo | bingo slots | slots slots | hacker do slot | pg slot demo | slot win | pg slot soft | arne slot | riqueza slots | slots 777 | pg slot | 777 slot game | slot pg soft | hacker slot | 777 slots | slot-pg-soft | fortune ox demo grátis | demo fortune ox | fortune mouse demo | fortune ox demo | jogo fortune tiger | fortune tiger grátis | fortune tiger baixar | fortune tiger demo grátis | fortune tiger demo | fortune tiger 777 | 580bet | bet 7k | leao | luck 2 | john bet | 7755 bet | cbet | bet7 | pk55 | 8800 bet | doce | bet 4 | f12bet | bet7 | ggbet | bet77 | mrbet | bet61 | tvbet | pgwin | today | fuwin | brwin | bet7k | tv bet | allwin | stake | bwin 789 | lvbet | blaze | dj bet | umbet | b1bet | 20bet | bk bet | h2bet | 7kbet | fbbet | 9d bet | 9k bet | 73 bet | ktobet | 74 bet | betpix | betvip | batbet | onabet | f12bet | codbet | winbra | b2xbet | obabet | brlwin | onebra | winbrl | omgbet | queens | brdice | brapub | flames | betano | aajogo | iribet | pixbet | betsul | fezbet | curso beta | betway | bkbet | peixe beta | bet365 | pixbet | 4 play bet | 365bet | brxbet | 939 bet | seubet | cnc bet | gbg bet | 522bet | brl bet | pagbet | jonbet | jqk bet | 166bet | abc bet | bggbet | obabet | 136bet | mmabet | win bet | ir6 bet | 667bet | qqq bet | 193 bet | 3ss bet | 317 bet | kkk bet | 585 bet | 569 bet | vai bet | aaa bet | 969 bet | z11 bet | kw bet | 26 bet | mj bet | betio | 01 bet | ut bet | 9y bet | bet70 | f9 bet | hw bet | kg bet | 5e bet | bet br | hr bet | br bet | 75 bet | 03 bet | 6z bet | 6r bet | v6 bet | 78 bet | bt bet | 80 bet | 8g bet | 72 bet | xp bet | f12 bet | p9 bet | 5 bet | 4 bet | bet 4 | r7 bet | um bet | 29 bet | 5s bet | ck bet | pg bet | ea bet | 23 bet | bl bet | 3l bet | 2a bet | p7 bet | 888 bet | 707 bet | 361 bet | bet29 | 700 bet | 161 bet | bet777 | up bet | 58 bet | nn bet | 67 bet | 22 bet | 9g bet | 1x bet | bet10 | 70 bet | 2h bet | 9r bet | 16 bet | 81 bet | 7 bet | 5u bet | 6k bet | mg bet | b1 bet | 5h bet | je- bet | joya | hopa | nomini | ls bet | 1xbit | platin | ice bet | rant | bet us | bet go | 31 bet | slingo | flush | ice36 | weiss | bet9 | rabona | i bet | starda | dreams | bongo | snatch | 10 bet | daddy | metal | zep bet | drip | gama | drake | verde | shazam | wish | thor | exclusive | sol | highway | 500 casino | jazz | howl | supernova | sherbet | fresh | daddy | jet | wish | eclipse | inplay | drip | marvel | stake | scorpion | luxebet | drake | thor | puma | winzir | loki | shazam | rivalry | f1 casino | xgbet | sushi | bk8 | art casino | manga | pgasia | gemini | bingoplus | slot vip | help slot win | 8k8 slot | tadhana slot | jili slot | 55bmw slot | vip slot | nn777 slot | jili slot 777 | tg777 slot | w500 slot | phfun slot | bmw55 slot | sg777 slot | wj slot | slot free 100 | lucky cola slot | cc6 slot | taya777 slot | ph444 slot | slot games | fb777 slot | okebet slot | help slot | tg77 slot | phwin slot | vvjl slot | fc777 slot | slot vin | yy777 slot | define slot | define slot | inplay | 99bet | 60win | melbet | jollibet | jili slot | rich711 | tayabet | phl63 | unobet | 63jili | mwplay888 | gold99 | jolibet | ubet95 | nice88 | jili777 | nn777 | phlove | jiliko | 55bmw | phoenix game | 8k8 | cgebet | 7up gaming | diamond game | hellowin | win88 | big win | kabibe game | sabong bet | phcity | colorplay | tongits go | slotsgo | spinph | go perya | casino frenzy | aurora game | escala gaming | winning plus | bingo plus | ph dream | 747 live | niceph | lucky cola | pera play