Created
December 7, 2017 02:04
-
-
Save 77web/4b59ffcf9d6d306f5ebb018b9f54e23e to your computer and use it in GitHub Desktop.
最強のControllerTrait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Controller; | |
use Doctrine\Common\Persistence\ManagerRegistry; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\FormFactoryInterface; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\Form\Extension\Core\Type\FormType; | |
use Symfony\Component\HttpFoundation\BinaryFileResponse; | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
use Symfony\Component\HttpFoundation\RequestStack; | |
use Symfony\Component\HttpFoundation\Response; | |
use Symfony\Component\HttpFoundation\ResponseHeaderBag; | |
use Symfony\Component\HttpFoundation\Session\Session; | |
use Symfony\Component\HttpFoundation\Session\SessionInterface; | |
use Symfony\Component\HttpFoundation\StreamedResponse; | |
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; | |
use Symfony\Component\HttpKernel\HttpKernelInterface; | |
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; | |
use Symfony\Component\Routing\RouterInterface; | |
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | |
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; | |
use Symfony\Component\Security\Core\Exception\AccessDeniedException; | |
use Symfony\Component\Security\Csrf\CsrfToken; | |
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; | |
use Symfony\Component\Serializer\SerializerInterface; | |
trait ControllerTrait | |
{ | |
/** | |
* @var RouterInterface | |
*/ | |
protected $router; | |
/** | |
* @var RequestStack | |
*/ | |
protected $requestStack; | |
/** | |
* @var HttpKernelInterface | |
*/ | |
protected $httpKernel; | |
/** | |
* @var SerializerInterface | |
*/ | |
protected $serializer; | |
/** | |
* @var Session | |
*/ | |
protected $session; | |
/** | |
* @var AuthorizationCheckerInterface | |
*/ | |
protected $authorizationChecker; | |
/** | |
* @var \Twig_Environment | |
*/ | |
protected $twig; | |
/** | |
* @var FormFactoryInterface | |
*/ | |
protected $formFactory; | |
/** | |
* @var ManagerRegistry | |
*/ | |
protected $managerRegistry; | |
/** | |
* @var TokenStorageInterface | |
*/ | |
protected $tokenStorage; | |
/** | |
* @var CsrfTokenManagerInterface | |
*/ | |
protected $csrfTokenManager; | |
/** | |
* Generates a URL from the given parameters. | |
* | |
* @param string $route The name of the route | |
* @param array $parameters An array of parameters | |
* @param int $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->router->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 | |
* @throws \Exception | |
*/ | |
protected 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->httpKernel->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 | |
*/ | |
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); | |
} | |
/** | |
* 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 | |
* | |
*/ | |
protected function json($data, $status = 200, $headers = array(), $context = array()) | |
{ | |
if ($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 | |
*/ | |
protected function file($file, $fileName = null, $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT) | |
{ | |
$response = new BinaryFileResponse($file); | |
$response->setContentDisposition($disposition, null === $fileName ? $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 | |
*/ | |
protected function addFlash($type, $message) | |
{ | |
$this->session->getFlashBag()->add($type, $message); | |
} | |
/** | |
* Checks if the attributes are granted against the current authentication token and optionally supplied subject. | |
* | |
* @param mixed $attributes The attributes | |
* @param mixed $subject The subject | |
* | |
* @return bool | |
* | |
* @throws \LogicException | |
*/ | |
protected function isGranted($attributes, $subject = null) | |
{ | |
return $this->authorizationChecker->isGranted($attributes, $subject); | |
} | |
/** | |
* Throws an exception unless the attributes are granted against the current authentication token and optionally | |
* supplied subject. | |
* | |
* @param mixed $attributes The attributes | |
* @param mixed $subject The subject | |
* @param string $message The message passed to the exception | |
* | |
* @throws AccessDeniedException | |
* | |
* @final since version 3.4 | |
*/ | |
protected function denyAccessUnlessGranted($attributes, $subject = null, $message = 'Access Denied.') | |
{ | |
if (!$this->isGranted($attributes, $subject)) { | |
$exception = $this->createAccessDeniedException($message); | |
$exception->setAttributes($attributes); | |
$exception->setSubject($subject); | |
throw $exception; | |
} | |
} | |
/** | |
* Returns a rendered view. | |
* | |
* @param string $view The view name | |
* @param array $parameters An array of parameters to pass to the view | |
* | |
* @return string The rendered view | |
* | |
* @throws \Twig_Error_Loader When the template cannot be found | |
* @throws \Twig_Error_Syntax When an error occurred during compilation | |
* @throws \Twig_Error_Runtime When an error occurred during rendering | |
*/ | |
protected function renderView($view, array $parameters = array()) | |
{ | |
return $this->twig->render($view, $parameters); | |
} | |
/** | |
* Renders a view. | |
* | |
* @param string $view The view name | |
* @param array $parameters An array of parameters to pass to the view | |
* @param Response $response A response instance | |
* | |
* @return Response A Response instance | |
* @throws \Twig_Error_Loader When the template cannot be found | |
* @throws \Twig_Error_Syntax When an error occurred during compilation | |
* @throws \Twig_Error_Runtime When an error occurred during rendering | |
*/ | |
protected function render($view, array $parameters = array(), Response $response = null) | |
{ | |
$content = $this->renderView($view, $parameters); | |
if (null === $response) { | |
$response = new Response(); | |
} | |
$response->setContent($content); | |
return $response; | |
} | |
/** | |
* Streams a view. | |
* | |
* @param string $view The view name | |
* @param array $parameters An array of parameters to pass to the view | |
* @param StreamedResponse $response A response instance | |
* | |
* @return StreamedResponse A StreamedResponse instance | |
* | |
* @final since version 3.4 | |
*/ | |
protected function stream($view, array $parameters = array(), StreamedResponse $response = null) | |
{ | |
$callback = function () use ($view, $parameters) { | |
$this->twig->display($view, $parameters); | |
}; | |
if (null === $response) { | |
return new StreamedResponse($callback); | |
} | |
$response->setCallback($callback); | |
return $response; | |
} | |
/** | |
* 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 | |
* | |
* @return NotFoundHttpException | |
* | |
* @final since version 3.4 | |
*/ | |
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 | |
* | |
* @final since version 3.4 | |
*/ | |
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. | |
* | |
* @param string $type The fully qualified class name of the form type | |
* @param mixed $data The initial data for the form | |
* @param array $options Options for the form | |
* | |
* @return FormInterface | |
*/ | |
protected function createForm($type, $data = null, array $options = array()) | |
{ | |
return $this->formFactory->create($type, $data, $options); | |
} | |
/** | |
* Creates and returns a form builder instance. | |
* | |
* @param mixed $data The initial data for the form | |
* @param array $options Options for the form | |
* | |
* @return FormBuilderInterface | |
*/ | |
protected function createFormBuilder($data = null, array $options = array()) | |
{ | |
return $this->formFactory->createBuilder(FormType::class, $data, $options); | |
} | |
/** | |
* Shortcut to return the Doctrine Registry service. | |
* | |
* @return ManagerRegistry | |
* | |
* @throws \LogicException If DoctrineBundle is not available | |
* | |
*/ | |
protected function getDoctrine() | |
{ | |
return $this->managerRegistry; | |
} | |
/** | |
* Get a user from the Security Token Storage. | |
* | |
* @return mixed | |
* | |
* @throws \LogicException If SecurityBundle is not available | |
* | |
* @see TokenInterface::getUser() | |
*/ | |
protected function getUser() | |
{ | |
if (null === $token = $this->tokenStorage->getToken()) { | |
return; | |
} | |
if (!is_object($user = $token->getUser())) { | |
// e.g. anonymous authentication | |
return; | |
} | |
return $user; | |
} | |
/** | |
* 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) | |
{ | |
return $this->csrfTokenManager->isTokenValid(new CsrfToken($id, $token)); | |
} | |
/** | |
* @param RouterInterface $router | |
* @required | |
*/ | |
public function setRouter(RouterInterface $router) | |
{ | |
$this->router = $router; | |
} | |
/** | |
* @param RequestStack $requestStack | |
* @required | |
*/ | |
public function setRequestStack(RequestStack $requestStack) | |
{ | |
$this->requestStack = $requestStack; | |
} | |
/** | |
* @param HttpKernelInterface $httpKernel | |
* @required | |
*/ | |
public function setHttpKernel(HttpKernelInterface $httpKernel) | |
{ | |
$this->httpKernel = $httpKernel; | |
} | |
/** | |
* @param SerializerInterface $serializer | |
* @required | |
*/ | |
public function setSerializer(SerializerInterface $serializer) | |
{ | |
$this->serializer = $serializer; | |
} | |
/** | |
* @param SessionInterface $session | |
* @required | |
*/ | |
public function setSession(SessionInterface $session) | |
{ | |
$this->session = $session; | |
} | |
/** | |
* @param AuthorizationCheckerInterface $authorizationChecker | |
* @required | |
*/ | |
public function setAuthorizationChecker(AuthorizationCheckerInterface $authorizationChecker) | |
{ | |
$this->authorizationChecker = $authorizationChecker; | |
} | |
/** | |
* @param \Twig_Environment $twig | |
* @required | |
*/ | |
public function setTwig(\Twig_Environment $twig) | |
{ | |
$this->twig = $twig; | |
} | |
/** | |
* @param FormFactoryInterface $formFactory | |
* @required | |
*/ | |
public function setFormFactory(FormFactoryInterface $formFactory) | |
{ | |
$this->formFactory = $formFactory; | |
} | |
/** | |
* @param ManagerRegistry $managerRegistry | |
* @required | |
*/ | |
public function setManagerRegistry(ManagerRegistry $managerRegistry) | |
{ | |
$this->managerRegistry = $managerRegistry; | |
} | |
/** | |
* @param TokenStorageInterface $tokenStorage | |
* @required | |
*/ | |
public function setTokenStorage(TokenStorageInterface $tokenStorage) | |
{ | |
$this->tokenStorage = $tokenStorage; | |
} | |
/** | |
* @param CsrfTokenManagerInterface $csrfTokenManager | |
* @required | |
*/ | |
public function setCsrfTokenManager(CsrfTokenManagerInterface $csrfTokenManager) | |
{ | |
$this->csrfTokenManager = $csrfTokenManager; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment