This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php

403 lines
13 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
[HttpFoundation] added support for streamed responses To stream a Response, use the StreamedResponse class instead of the standard Response class: $response = new StreamedResponse(function () { echo 'FOO'; }); $response = new StreamedResponse(function () { echo 'FOO'; }, 200, array('Content-Type' => 'text/plain')); As you can see, a StreamedResponse instance takes a PHP callback instead of a string for the Response content. It's up to the developer to stream the response content from the callback with standard PHP functions like echo. You can also use flush() if needed. From a controller, do something like this: $twig = $this->get('templating'); return new StreamedResponse(function () use ($templating) { $templating->stream('BlogBundle:Annot:streamed.html.twig'); }, 200, array('Content-Type' => 'text/html')); If you are using the base controller, you can use the stream() method instead: return $this->stream('BlogBundle:Annot:streamed.html.twig'); You can stream an existing file by using the PHP built-in readfile() function: new StreamedResponse(function () use ($file) { readfile($file); }, 200, array('Content-Type' => 'image/png'); Read http://php.net/flush for more information about output buffering in PHP. Note that you should do your best to move all expensive operations to be "activated/evaluated/called" during template evaluation. Templates --------- If you are using Twig as a template engine, everything should work as usual, even if are using template inheritance! However, note that streaming is not supported for PHP templates. Support is impossible by design (as the layout is rendered after the main content). Exceptions ---------- Exceptions thrown during rendering will be rendered as usual except that some content might have been rendered already. Limitations ----------- As the getContent() method always returns false for streamed Responses, some event listeners won't work at all: * Web debug toolbar is not available for such Responses (but the profiler works fine); * ESI is not supported. Also note that streamed responses cannot benefit from HTTP caching for obvious reasons.
2011-10-17 16:17:34 +01:00
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Csrf\CsrfToken;
2011-06-01 09:45:51 +01:00
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Doctrine\Bundle\DoctrineBundle\Registry;
/**
2010-08-28 08:39:04 +01:00
* Controller is a simple implementation of a Controller.
*
* It provides methods to common features needed in controllers.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class Controller extends ContainerAware
{
/**
* Generates a URL from the given parameters.
*
2014-11-30 13:33:44 +00:00
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
* @param bool|string $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
*
* @return string The generated URL
*
* @see UrlGeneratorInterface
*/
protected function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
return $this->container->get('router')->generate($route, $parameters, $referenceType);
}
/**
* Forwards the request to another controller.
*
2012-05-14 16:06:14 +01:00
* @param string $controller The controller name (a string like BlogBundle:Post:index)
* @param array $path An array of path parameters
* @param array $query An array of query parameters
*
* @return Response A Response instance
*/
protected function forward($controller, array $path = array(), array $query = array())
{
$path['_controller'] = $controller;
$subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate($query, null, $path);
return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
/**
* Returns a RedirectResponse to the given URL.
*
2014-11-30 13:33:44 +00:00
* @param string $url The URL to redirect to
* @param int $status The status code to use for the Response
*
* @return RedirectResponse
*/
protected function redirect($url, $status = 302)
{
return new RedirectResponse($url, $status);
}
/**
* Returns a RedirectResponse to the given route with the given parameters.
*
* @param string $route The name of the route
* @param array $parameters An array of parameters
* @param int $status The status code to use for the Response
*
* @return RedirectResponse
*/
protected function redirectToRoute($route, array $parameters = array(), $status = 302)
{
return $this->redirect($this->generateUrl($route, $parameters), $status);
}
/**
* Adds a flash message to the current session for type.
*
* @param string $type The type
* @param string $message The message
*
* @throws \LogicException
*/
protected function addFlash($type, $message)
{
if (!$this->container->has('session')) {
throw new \LogicException('You can not use the addFlash method if sessions are disabled.');
}
$this->container->get('session')->getFlashBag()->add($type, $message);
}
/**
* Checks if the attributes are granted against the current authentication token and optionally supplied object.
*
* @param mixed $attributes The attributes
* @param mixed $object The object
*
* @return bool
*
* @throws \LogicException
*/
protected function isGranted($attributes, $object = null)
{
if (!$this->container->has('security.authorization_checker')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
return $this->container->get('security.authorization_checker')->isGranted($attributes, $object);
}
/**
* Throws an exception unless the attributes are granted against the current authentication token and optionally
* supplied object.
*
* @param mixed $attributes The attributes
* @param mixed $object The object
* @param string $message The message passed to the exception
*
* @throws AccessDeniedException
*/
protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
{
if (!$this->isGranted($attributes, $object)) {
throw $this->createAccessDeniedException($message);
}
}
/**
* Returns a rendered view.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
*
2012-12-08 13:22:45 +00:00
* @return string The rendered view
*/
protected function renderView($view, array $parameters = array())
{
if ($this->container->has('templating')) {
return $this->container->get('templating')->render($view, $parameters);
}
if (!$this->container->has('twig')) {
2015-09-14 07:46:24 +01:00
throw new \LogicException('You can not use the "renderView" method if the Templating Component or the Twig Bundle are not available.');
}
return $this->container->get('twig')->render($view, $parameters);
}
/**
* Renders a view.
*
2012-05-14 16:06:14 +01:00
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
2012-05-14 16:06:14 +01:00
* @param Response $response A response instance
*
* @return Response A Response instance
*/
protected function render($view, array $parameters = array(), Response $response = null)
{
if ($this->container->has('templating')) {
return $this->container->get('templating')->renderResponse($view, $parameters, $response);
}
if (!$this->container->has('twig')) {
2015-09-14 07:46:24 +01:00
throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available.');
}
if (null === $response) {
$response = new Response();
}
$response->setContent($this->container->get('twig')->render($view, $parameters));
return $response;
}
[HttpFoundation] added support for streamed responses To stream a Response, use the StreamedResponse class instead of the standard Response class: $response = new StreamedResponse(function () { echo 'FOO'; }); $response = new StreamedResponse(function () { echo 'FOO'; }, 200, array('Content-Type' => 'text/plain')); As you can see, a StreamedResponse instance takes a PHP callback instead of a string for the Response content. It's up to the developer to stream the response content from the callback with standard PHP functions like echo. You can also use flush() if needed. From a controller, do something like this: $twig = $this->get('templating'); return new StreamedResponse(function () use ($templating) { $templating->stream('BlogBundle:Annot:streamed.html.twig'); }, 200, array('Content-Type' => 'text/html')); If you are using the base controller, you can use the stream() method instead: return $this->stream('BlogBundle:Annot:streamed.html.twig'); You can stream an existing file by using the PHP built-in readfile() function: new StreamedResponse(function () use ($file) { readfile($file); }, 200, array('Content-Type' => 'image/png'); Read http://php.net/flush for more information about output buffering in PHP. Note that you should do your best to move all expensive operations to be "activated/evaluated/called" during template evaluation. Templates --------- If you are using Twig as a template engine, everything should work as usual, even if are using template inheritance! However, note that streaming is not supported for PHP templates. Support is impossible by design (as the layout is rendered after the main content). Exceptions ---------- Exceptions thrown during rendering will be rendered as usual except that some content might have been rendered already. Limitations ----------- As the getContent() method always returns false for streamed Responses, some event listeners won't work at all: * Web debug toolbar is not available for such Responses (but the profiler works fine); * ESI is not supported. Also note that streamed responses cannot benefit from HTTP caching for obvious reasons.
2011-10-17 16:17:34 +01:00
/**
* Streams a view.
*
2012-05-15 21:19:31 +01:00
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
2012-05-15 21:19:31 +01:00
* @param StreamedResponse $response A response instance
[HttpFoundation] added support for streamed responses To stream a Response, use the StreamedResponse class instead of the standard Response class: $response = new StreamedResponse(function () { echo 'FOO'; }); $response = new StreamedResponse(function () { echo 'FOO'; }, 200, array('Content-Type' => 'text/plain')); As you can see, a StreamedResponse instance takes a PHP callback instead of a string for the Response content. It's up to the developer to stream the response content from the callback with standard PHP functions like echo. You can also use flush() if needed. From a controller, do something like this: $twig = $this->get('templating'); return new StreamedResponse(function () use ($templating) { $templating->stream('BlogBundle:Annot:streamed.html.twig'); }, 200, array('Content-Type' => 'text/html')); If you are using the base controller, you can use the stream() method instead: return $this->stream('BlogBundle:Annot:streamed.html.twig'); You can stream an existing file by using the PHP built-in readfile() function: new StreamedResponse(function () use ($file) { readfile($file); }, 200, array('Content-Type' => 'image/png'); Read http://php.net/flush for more information about output buffering in PHP. Note that you should do your best to move all expensive operations to be "activated/evaluated/called" during template evaluation. Templates --------- If you are using Twig as a template engine, everything should work as usual, even if are using template inheritance! However, note that streaming is not supported for PHP templates. Support is impossible by design (as the layout is rendered after the main content). Exceptions ---------- Exceptions thrown during rendering will be rendered as usual except that some content might have been rendered already. Limitations ----------- As the getContent() method always returns false for streamed Responses, some event listeners won't work at all: * Web debug toolbar is not available for such Responses (but the profiler works fine); * ESI is not supported. Also note that streamed responses cannot benefit from HTTP caching for obvious reasons.
2011-10-17 16:17:34 +01:00
*
* @return StreamedResponse A StreamedResponse instance
*/
protected function stream($view, array $parameters = array(), StreamedResponse $response = null)
[HttpFoundation] added support for streamed responses To stream a Response, use the StreamedResponse class instead of the standard Response class: $response = new StreamedResponse(function () { echo 'FOO'; }); $response = new StreamedResponse(function () { echo 'FOO'; }, 200, array('Content-Type' => 'text/plain')); As you can see, a StreamedResponse instance takes a PHP callback instead of a string for the Response content. It's up to the developer to stream the response content from the callback with standard PHP functions like echo. You can also use flush() if needed. From a controller, do something like this: $twig = $this->get('templating'); return new StreamedResponse(function () use ($templating) { $templating->stream('BlogBundle:Annot:streamed.html.twig'); }, 200, array('Content-Type' => 'text/html')); If you are using the base controller, you can use the stream() method instead: return $this->stream('BlogBundle:Annot:streamed.html.twig'); You can stream an existing file by using the PHP built-in readfile() function: new StreamedResponse(function () use ($file) { readfile($file); }, 200, array('Content-Type' => 'image/png'); Read http://php.net/flush for more information about output buffering in PHP. Note that you should do your best to move all expensive operations to be "activated/evaluated/called" during template evaluation. Templates --------- If you are using Twig as a template engine, everything should work as usual, even if are using template inheritance! However, note that streaming is not supported for PHP templates. Support is impossible by design (as the layout is rendered after the main content). Exceptions ---------- Exceptions thrown during rendering will be rendered as usual except that some content might have been rendered already. Limitations ----------- As the getContent() method always returns false for streamed Responses, some event listeners won't work at all: * Web debug toolbar is not available for such Responses (but the profiler works fine); * ESI is not supported. Also note that streamed responses cannot benefit from HTTP caching for obvious reasons.
2011-10-17 16:17:34 +01:00
{
if ($this->container->has('templating')) {
$templating = $this->container->get('templating');
$callback = function () use ($templating, $view, $parameters) {
$templating->stream($view, $parameters);
};
} elseif ($this->container->has('twig')) {
$twig = $this->container->get('twig');
$callback = function () use ($twig, $view, $parameters) {
$twig->display($view, $parameters);
};
} else {
2015-09-14 07:46:24 +01:00
throw new \LogicException('You can not use the "stream" method if the Templating Component or the Twig Bundle are not available.');
}
if (null === $response) {
return new StreamedResponse($callback);
}
$response->setCallback($callback);
return $response;
[HttpFoundation] added support for streamed responses To stream a Response, use the StreamedResponse class instead of the standard Response class: $response = new StreamedResponse(function () { echo 'FOO'; }); $response = new StreamedResponse(function () { echo 'FOO'; }, 200, array('Content-Type' => 'text/plain')); As you can see, a StreamedResponse instance takes a PHP callback instead of a string for the Response content. It's up to the developer to stream the response content from the callback with standard PHP functions like echo. You can also use flush() if needed. From a controller, do something like this: $twig = $this->get('templating'); return new StreamedResponse(function () use ($templating) { $templating->stream('BlogBundle:Annot:streamed.html.twig'); }, 200, array('Content-Type' => 'text/html')); If you are using the base controller, you can use the stream() method instead: return $this->stream('BlogBundle:Annot:streamed.html.twig'); You can stream an existing file by using the PHP built-in readfile() function: new StreamedResponse(function () use ($file) { readfile($file); }, 200, array('Content-Type' => 'image/png'); Read http://php.net/flush for more information about output buffering in PHP. Note that you should do your best to move all expensive operations to be "activated/evaluated/called" during template evaluation. Templates --------- If you are using Twig as a template engine, everything should work as usual, even if are using template inheritance! However, note that streaming is not supported for PHP templates. Support is impossible by design (as the layout is rendered after the main content). Exceptions ---------- Exceptions thrown during rendering will be rendered as usual except that some content might have been rendered already. Limitations ----------- As the getContent() method always returns false for streamed Responses, some event listeners won't work at all: * Web debug toolbar is not available for such Responses (but the profiler works fine); * ESI is not supported. Also note that streamed responses cannot benefit from HTTP caching for obvious reasons.
2011-10-17 16:17:34 +01:00
}
/**
* Returns a NotFoundHttpException.
*
* This will result in a 404 response code. Usage example:
*
* throw $this->createNotFoundException('Page not found!');
*
* @param string $message A message
* @param \Exception|null $previous The previous exception
2012-05-14 16:06:14 +01:00
*
* @return NotFoundHttpException
*/
protected function createNotFoundException($message = 'Not Found', \Exception $previous = null)
{
return new NotFoundHttpException($message, $previous);
}
/**
* Returns an AccessDeniedException.
*
* This will result in a 403 response code. Usage example:
*
* throw $this->createAccessDeniedException('Unable to access this page!');
*
* @param string $message A message
* @param \Exception|null $previous The previous exception
*
* @return AccessDeniedException
*/
Merge branch '2.8' * 2.8: (65 commits) [VarDumper] Fix tests for HHVM Update DateTimeToArrayTransformer.php Mock microtime() and time() in transient tests Azerbaijani language pluralization rule Move HHVM tests out of the allowed failures Fix merge [2.6] Towards 100% HHVM compat [Security/Http] Fix test [Stopwatch] Fix test Minor fixes [Validator] Added missing error codes and turned codes into UUIDs Towards 100% HHVM compat Warmup twig templates in non-standard paths (closes #12507) [Bridge/PhpUnit] Enforce a consistent locale Fix param order of assertEquals (expected, actual) in test for Finder\Glob Fix choice translation domain for expanded choice widget unify default AccessDeniedExeption message trigger event with right user (add test) [Security] Initialize SwitchUserEvent::targetUser on attemptExitUser fixed CS ... Conflicts: UPGRADE-2.8.md src/Symfony/Bridge/ProxyManager/composer.json src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/JsonDescriptor.php src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/MarkdownDescriptor.php src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/XmlDescriptor.php src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php src/Symfony/Bundle/FrameworkBundle/Resources/config/old_assets.xml src/Symfony/Bundle/FrameworkBundle/Resources/config/test.xml src/Symfony/Bundle/FrameworkBundle/Resources/config/validator.xml src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_public.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_services.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tag1.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tags.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tags.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/builder_1_tags.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.txt src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_1.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.txt src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/definition_2.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.txt src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_1.xml src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.json src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.md src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.txt src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Descriptor/legacy_synchronized_service_definition_2.xml src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/CsrfFormLoginBundle/Form/UserLoginFormType.php src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/CsrfFormLogin/config.yml src/Symfony/Bundle/SecurityBundle/composer.json src/Symfony/Component/Debug/ErrorHandler.php src/Symfony/Component/DependencyInjection/Compiler/CheckDefinitionValidityPass.php src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php src/Symfony/Component/DependencyInjection/Definition.php src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php src/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/legacy-container9.php src/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/legacy-services9.dot src/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/legacy-services6.xml src/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/legacy-services9.xml src/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/legacy-services6.yml src/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/legacy-services9.yml src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php src/Symfony/Component/Form/ResolvedFormType.php src/Symfony/Component/Form/Tests/CompoundFormTest.php src/Symfony/Component/Process/Tests/AbstractProcessTest.php src/Symfony/Component/VarDumper/Tests/CliDumperTest.php src/Symfony/Component/VarDumper/Tests/HtmlDumperTest.php
2015-07-01 21:40:29 +01:00
protected function createAccessDeniedException($message = 'Access Denied.', \Exception $previous = null)
{
return new AccessDeniedException($message, $previous);
}
/**
* Creates and returns a Form instance from the type of the form.
*
2011-06-01 09:45:51 +01:00
* @param string|FormTypeInterface $type The built type of the form
2012-05-14 16:06:14 +01:00
* @param mixed $data The initial data for the form
* @param array $options Options for the form
*
* @return Form
*/
protected function createForm($type, $data = null, array $options = array())
{
return $this->container->get('form.factory')->create($type, $data, $options);
}
/**
2014-12-21 17:00:50 +00:00
* Creates and returns a form builder instance.
*
2012-05-14 16:06:14 +01:00
* @param mixed $data The initial data for the form
* @param array $options Options for the form
*
* @return FormBuilder
*/
protected function createFormBuilder($data = null, array $options = array())
{
if (method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')) {
$type = 'Symfony\Component\Form\Extension\Core\Type\FormType';
} else {
// not using the class name is deprecated since Symfony 2.8 and
// is only used for backwards compatibility with older versions
// of the Form component
$type = 'form';
}
return $this->container->get('form.factory')->createBuilder($type, $data, $options);
}
/**
* Shortcut to return the Doctrine Registry service.
*
2012-03-01 22:47:51 +00:00
* @return Registry
*
* @throws \LogicException If DoctrineBundle is not available
*/
protected function getDoctrine()
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application.');
}
return $this->container->get('doctrine');
}
/**
* Get a user from the Security Token Storage.
*
* @return mixed
*
* @throws \LogicException If SecurityBundle is not available
*
* @see TokenInterface::getUser()
*/
protected function getUser()
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->container->get('security.token_storage')->getToken()) {
2014-04-16 08:15:58 +01:00
return;
}
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
2014-04-16 08:15:58 +01:00
return;
}
return $user;
}
/**
* Returns true if the service id is defined.
*
2012-05-14 16:06:14 +01:00
* @param string $id The service id
*
2014-11-30 13:33:44 +00:00
* @return bool true if the service id is defined, false otherwise
*/
protected function has($id)
{
return $this->container->has($id);
}
/**
* Gets a container service by its id.
*
2012-05-14 16:06:14 +01:00
* @param string $id The service id
*
* @return object The service
*/
protected function get($id)
{
return $this->container->get($id);
}
/**
* Gets a container configuration parameter by its name.
*
* @param string $name The parameter name
*
* @return mixed
*/
protected function getParameter($name)
{
return $this->container->getParameter($name);
}
/**
* Checks the validity of a CSRF token.
*
* @param string $id The id used when generating the token
* @param string $token The actual token sent with the request that should be validated
*
* @return bool
*/
protected function isCsrfTokenValid($id, $token)
{
if (!$this->container->has('security.csrf.token_manager')) {
throw new \LogicException('CSRF protection is not enabled in your application.');
}
return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token));
}
}