Skip to content

[FrameworkBundle] Separate controller utils from its base class #20730

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 7 additions & 28 deletions src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Form\Extension\Core\Type\FormType;
Expand Down Expand Up @@ -53,7 +52,7 @@ abstract class Controller implements ContainerAwareInterface
*/
protected function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
return $this->container->get('router')->generate($route, $parameters, $referenceType);
return $this->container->get('controller_utils')->generateUrl($route, $parameters, $referenceType);
}

/**
Expand All @@ -67,12 +66,7 @@ protected function generateUrl($route, $parameters = array(), $referenceType = U
*/
protected function forward($controller, array $path = array(), array $query = array())
{
$request = $this->container->get('request_stack')->getCurrentRequest();
$path['_forwarded'] = $request->attributes;
$path['_controller'] = $controller;
$subRequest = $request->duplicate($query, null, $path);

return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
return $this->container->get('controller_utils')->forward($controller, $path, $query);
}

/**
Expand All @@ -85,7 +79,7 @@ protected function forward($controller, array $path = array(), array $query = ar
*/
protected function redirect($url, $status = 302)
{
return new RedirectResponse($url, $status);
return $this->container->get('controller_utils')->redirect($url, $status);
}

/**
Expand All @@ -99,7 +93,7 @@ protected function redirect($url, $status = 302)
*/
protected function redirectToRoute($route, array $parameters = array(), $status = 302)
{
return $this->redirect($this->generateUrl($route, $parameters), $status);
return $this->container->get('controller_utils')->redirectToRoute($route, $parameters, $status);
}

/**
Expand All @@ -114,15 +108,7 @@ protected function redirectToRoute($route, array $parameters = array(), $status
*/
protected function json($data, $status = 200, $headers = array(), $context = array())
{
if ($this->container->has('serializer')) {
$json = $this->container->get('serializer')->serialize($data, 'json', array_merge(array(
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
), $context));

return new JsonResponse($json, $status, $headers, true);
}

return new JsonResponse($data, $status, $headers);
return $this->container->get('controller_utils')->json($data, $status, $headers, $context);
}

/**
Expand All @@ -136,10 +122,7 @@ protected function json($data, $status = 200, $headers = array(), $context = arr
*/
protected function file($file, $fileName = null, $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT)
{
$response = new BinaryFileResponse($file);
$response->setContentDisposition($disposition, $fileName === null ? $response->getFile()->getFileName() : $fileName);

return $response;
return $this->container->get('controller_utils')->file($file, $fileName, $disposition);
}

/**
Expand All @@ -152,11 +135,7 @@ protected function file($file, $fileName = null, $disposition = ResponseHeaderBa
*/
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);
return $this->container->get('controller_utils')->addFlash($type, $message);
}

/**
Expand Down
172 changes: 172 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Controller/ControllerUtils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
<?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\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\SerializerInterface;

/**
* @author Fabien Potencier <fabien@symfony.com>
* @author Roland Franssen <franssen.roland@gmail.com>
*/
class ControllerUtils
{
private $kernel;
private $requestStack;
private $urlGenerator;
private $serializer;

public function __construct(HttpKernelInterface $kernel, RequestStack $requestStack, UrlGeneratorInterface $urlGenerator = null, SerializerInterface $serializer = null)
{
$this->kernel = $kernel;
$this->requestStack = $requestStack;
$this->urlGenerator = $urlGenerator;
$this->serializer = $serializer;
}

/**
* Generates a URL from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
* @param int $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
*
* @return string The generated URL
*
* @throws \LogicException
*
* @see UrlGeneratorInterface
*/
public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
if (null === $this->urlGenerator) {
throw new \LogicException('You can not use the generateUrl method if routing is disabled.');
}

return $this->urlGenerator->generate($route, $parameters, $referenceType);
}

/**
* Forwards the request to another controller.
*
* @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
*/
public function forward($controller, array $path = array(), array $query = array())
{
$request = $this->requestStack->getCurrentRequest();
$path['_forwarded'] = $request->attributes;
$path['_controller'] = $controller;
$subRequest = $request->duplicate($query, null, $path);

return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}

/**
* Returns a RedirectResponse to the given URL.
*
* @param string $url The URL to redirect to
* @param int $status The status code to use for the Response
*
* @return RedirectResponse
*/
public 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
*/
public function redirectToRoute($route, array $parameters = array(), $status = 302)
{
return $this->redirect($this->generateUrl($route, $parameters), $status);
}

/**
* Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
*
* @param mixed $data The response data
* @param int $status The status code to use for the Response
* @param array $headers Array of extra headers to add
* @param array $context Context to pass to serializer when using serializer component
*
* @return JsonResponse
*/
public function json($data, $status = 200, $headers = array(), $context = array())
{
if (null !== $this->serializer) {
$json = $this->serializer->serialize($data, 'json', array_merge(array(
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
), $context));

return new JsonResponse($json, $status, $headers, true);
}

return new JsonResponse($data, $status, $headers);
}

/**
* Returns a BinaryFileResponse object with original or customized file name and disposition header.
*
* @param \SplFileInfo|string $file File object or path to file to be sent as response
* @param string|null $fileName File name to be sent to response or null (will use original file name)
* @param string $disposition Disposition of response ("attachment" is default, other type is "inline")
*
* @return BinaryFileResponse
*/
public function file($file, $fileName = null, $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT)
{
$response = new BinaryFileResponse($file);
$response->setContentDisposition($disposition, $fileName === null ? $response->getFile()->getFileName() : $fileName);

return $response;
}

/**
* Adds a flash message to the current session for type.
*
* @param string $type The type
* @param string $message The message
*
* @throws \LogicException
*/
public function addFlash($type, $message)
{
$session = $this->requestStack->getCurrentRequest()->getSession();
if (null === $session) {
throw new \LogicException('You can not use the addFlash method if sessions are disabled.');
}
if (!$session instanceof Session) {
throw new \LogicException('You can not use the addFlash method for session implementation other then the default one.');
}

$session->getFlashBag()->add($type, $message);
}
}
7 changes: 7 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@
<argument type="service" id="logger" on-invalid="ignore" />
</service>

<service id="controller_utils" class="Symfony\Bundle\FrameworkBundle\Controller\ControllerUtils">
<argument type="service" id="http_kernel" />
<argument type="service" id="request_stack" />
<argument type="service" id="router" on-invalid="ignore" />
<argument type="service" id="serializer" on-invalid="ignore" />
</service>

<service id="argument_metadata_factory" class="Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory" public="false" />

<service id="argument_resolver" class="Symfony\Component\HttpKernel\Controller\ArgumentResolver" public="false">
Expand Down