LuckyController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Controller;
  3. use Psr\Log\LoggerInterface;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. class LuckyController extends Controller {
  9. /**
  10. * @Route(
  11. * name="lucky-number",
  12. * path="/lucky/number",
  13. * methods={"GET", "POST", "PUT", "PATCH"}
  14. * )
  15. *
  16. * @see config/services.yaml
  17. *
  18. * Notice how we overrode auto-wiring to receive an instance of App\Logger.
  19. */
  20. public function number(LoggerInterface $logger, Request $request) {
  21. $number = $request->query->has('value')
  22. ? (int) $request->query->get('value')
  23. : mt_rand(0, 100);
  24. /* Example features of the Request */
  25. assert(false === $request->isXmlHttpRequest());
  26. // Uses Accept-Language header.
  27. $preferred = $request->getPreferredLanguage(['en', 'fr']);
  28. // Empty on GET, valid on PATH, POST, PUT.
  29. $requestValue = $request->request->get('value');
  30. $logger->notice("We sent $number on GET, $requestValue on POST/PUT/PATCH");
  31. return $this->render("lucky/number.html.twig", [
  32. "number" => $number,
  33. // No need for cookies->all(): Twig can use {% for %} on iterators.
  34. "cookies" => $request->cookies,
  35. ]);
  36. }
  37. /**
  38. * @\Symfony\Component\Routing\Annotation\Route(
  39. * name = "lucky-not-found",
  40. * path = "/lucky/not-found"
  41. * )
  42. */
  43. public function notFound() {
  44. $notFound = $this->createNotFoundException();
  45. throw $this->createAccessDeniedException("Denied because it was not found", $notFound);
  46. }
  47. /**
  48. * @\Symfony\Component\Routing\Annotation\Route(
  49. * name = "lucky-denied",
  50. * path = "/lucky/denied"
  51. * )
  52. */
  53. public function denied() {
  54. $denied = $this->createAccessDeniedException();
  55. throw $this->createNotFoundException("Not found because it was denied", $denied);
  56. }
  57. }