controllers.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. <?php
  2. use demo\Controllers\BlogController;
  3. use demo\Controllers\FeedbackController;
  4. use demo\Controllers\UserController;
  5. use Silex\Application;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Exception\HttpException;
  10. use Symfony\Component\HttpKernel\HttpKernelInterface;
  11. //Request::setTrustedProxies(array('127.0.0.1'));
  12. // Fixed parameters for after() global middleware.
  13. $afterAllMiddleware = function (Request $request, Response $response, Application $app) {
  14. $MESSAGE = "<p>In aAM</p>\n";
  15. if ($response instanceof JsonResponse) {
  16. $content = $response->getContent();
  17. $raw = json_decode($content, TRUE);
  18. $raw[] = $MESSAGE;
  19. $newContent = json_encode($raw);
  20. $response->setContent($newContent);
  21. return $response;
  22. }
  23. // Only echo info on text responses.
  24. $ct = $response->headers->get('Content-Type');
  25. if (isset($ct) && strpos($ct, 'text') !== 0) {
  26. return;
  27. }
  28. echo $MESSAGE;
  29. };
  30. $beforeAllMiddleware = function (Request $request, Application $app) {
  31. // Only add info on requests URIs containing "json".
  32. if (!preg_match('/json/', $request->getRequestUri())) {
  33. echo "<p>In bAM</p>\n";
  34. }
  35. };
  36. // This type of global configuration does not apply to mounted controllers,
  37. // which have their own "global" configuration.
  38. $app->before($beforeAllMiddleware);
  39. $app->after($afterAllMiddleware);
  40. $app->get('/', function () use ($app) {
  41. return $app['twig']->render('index.html.twig', []);
  42. })->bind('homepage');
  43. // Redirect via response header
  44. $app->get('/hello', function () use ($app) {
  45. return $app->redirect('/', Response::HTTP_TEMPORARY_REDIRECT); // Default 302.
  46. });
  47. // Forward to another controller to avoid redirection.
  48. $app->get('/blogz', function () use ($app) {
  49. $subRequest = Request::create('/blogs', 'GET');
  50. return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  51. });
  52. $app->get('/all_blogs', function () use ($app) {
  53. /** @var \Symfony\Component\Routing\Generator\UrlGeneratorInterface $generator */
  54. $generator = $app['url_generator'];
  55. $subRequest = Request::create($generator->generate('blog_list', 'GET'));
  56. return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  57. });
  58. $blogPosts = [
  59. 1 => [
  60. 'date' => '2011-03-29',
  61. 'author' => 'igorw',
  62. 'title' => 'Using Silex',
  63. 'body' => '...It takes time on version changes...',
  64. ],
  65. 2 => [
  66. 'date' => '2015-03-29',
  67. 'author' => 'igorw',
  68. 'title' => 'Using Silex 2',
  69. 'body' => '...Especialy S1 to S2...',
  70. ],
  71. ];
  72. // Available automatic arguments on controllers: Application, Request.
  73. $app->get('/blogs', function () use ($blogPosts) {
  74. $output = "<ul>\n";
  75. foreach ($blogPosts as $post) {
  76. $output .= "<li>" . $post ['title'] . "</li>\n";
  77. }
  78. $output .= "</ul>\n";
  79. return $output;
  80. })->bind('blog_list');
  81. $app->get('/blogs-json', function () use ($app, $blogPosts) {
  82. return $app->json($blogPosts);
  83. });
  84. $app->get('/blogs-json-view', function () use ($blogPosts) {
  85. return $blogPosts; // Rely on the view handler.
  86. });
  87. // Default: http://blog, not http://blog/
  88. $app->get('/blog/{id}', BlogController::class . '::fifiAction')
  89. ->assert('id', '\d+')
  90. ->when("request.headers.get('User-Agent') matches '/firefox/i'");
  91. $app->get('/blog/{id}', function (Application $app, $id) use ($blogPosts) {
  92. if (!isset ($blogPosts [$id])) {
  93. // Will trigger the error() (or built-in) error handler.1
  94. $app->abort(Response::HTTP_NOT_FOUND, "Post $id does not exist.");
  95. }
  96. $post = $blogPosts [$id];
  97. return "<h1> {$post['title']}</h1>" . "<p> {$post['body']} </p>";
  98. })->assert('id', '\d+')
  99. ->value('id', 1)
  100. ->bind('blog_post');
  101. $app->post('/feedback', FeedbackController::class . '::feedbackAction');
  102. $app->get('/user/{user}', UserController::class . '::itemAction')
  103. ->convert('user', 'converter.user:convert');
  104. // Register a view handler. They can also receive Request $request as 2nd arg,
  105. // e.g. for basic content negotiation.
  106. $app->view(function (array $controllerResult) use ($app) {
  107. return $app->json($controllerResult);
  108. });
  109. // Handlers are examined in order, and called in a chain with the result of the
  110. // previous one. The last one must return a string or Response.
  111. /* Error handlers receive exactly these arguments, in that order. */
  112. $app->error(function (HttpException $e, Request $request, $code) {
  113. $response = new Response('HTTP Error caught: skipping generic error handler.',
  114. // This status is ignored by Silex, which tries to ensure status code
  115. // consistency with the exception.
  116. Response::HTTP_NOT_FOUND,
  117. // But we can force it with this fake header, which is removed before
  118. // sending the response to the user agent.
  119. ['X-Status-Code' => Response::HTTP_OK]);
  120. return $response;
  121. });
  122. /* Custom error handlers registered with error() take precedence over the
  123. built-in error handler provider by Silex, but the formatted error messages it
  124. provides can be accessed in debug mode by returning based on $app['debug']
  125. like this.
  126. */
  127. $app->error(function (\Exception $e, Request $request, $code) use ($app) {
  128. // Use the default handler in debug mode.
  129. if ($app['debug']) {
  130. return;
  131. }
  132. // Use our error formats otherwise.
  133. // 404.html, or 40x.html, or 4xx.html, or error.html
  134. $templates = [
  135. 'errors/' . $code . '.html.twig',
  136. 'errors/' . substr($code, 0, 2) . 'x.html.twig',
  137. 'errors/' . substr($code, 0, 1) . 'xx.html.twig',
  138. 'errors/default.html.twig',
  139. ];
  140. return new Response($app['twig']->resolveTemplate($templates)
  141. ->render(['code' => $code]), $code);
  142. });