Browse Source

Redirects, forwards, JSON output pp.11-12.

Frederic G. MARAND 6 years ago
parent
commit
4feeef91a5
1 changed files with 40 additions and 2 deletions
  1. 40 2
      src/controllers.php

+ 40 - 2
src/controllers.php

@@ -4,19 +4,39 @@ use demo\Controllers\BlogController;
 use demo\Controllers\FeedbackController;
 use demo\Controllers\UserController;
 use Silex\Application;
+use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpKernel\Exception\HttpException;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
 
 //Request::setTrustedProxies(array('127.0.0.1'));
 
 // Fixed parameters for after() global middleware.
 $afterAllMiddleware = function (Request $request, Response $response, Application $app) {
-  echo "<p>In aAM</p>\n";
+  $MESSAGE = "<p>In aAM</p>\n";
+  if ($response instanceof JsonResponse) {
+    $content = $response->getContent();
+    $raw = json_decode($content, TRUE);
+    $raw[] = $MESSAGE;
+    $newContent = json_encode($raw);
+    $response->setContent($newContent);
+    return $response;
+  }
+
+  // Only echo info on text responses.
+  $ct = $response->headers->get('Content-Type');
+  if (isset($ct) && strpos($ct, 'text') !== 0) {
+    return;
+  }
+  echo $MESSAGE;
 };
 
 $beforeAllMiddleware = function (Request $request, Application $app) {
-  echo "<p>In bAM</p>\n";
+  // Only add info on requests URIs containing "json".
+  if (!preg_match('/json/', $request->getRequestUri())) {
+    echo "<p>In bAM</p>\n";
+  }
 };
 
 // This type of global configuration does not apply to mounted controllers,
@@ -27,6 +47,21 @@ $app->after($afterAllMiddleware);
 $app->get('/', function () use ($app) {
   return $app['twig']->render('index.html.twig', []);
 })->bind('homepage');
+// Redirect via response header
+$app->get('/hello', function ()  use ($app) {
+  return $app->redirect('/', Response::HTTP_TEMPORARY_REDIRECT); // Default 302.
+});
+// Forward to another controller to avoid redirection.
+$app->get('/blogz', function () use ($app) {
+  $subRequest = Request::create('/blogs', 'GET');
+  return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
+});
+$app->get('/all_blogs', function () use ($app) {
+  /** @var \Symfony\Component\Routing\Generator\UrlGeneratorInterface $generator */
+  $generator = $app['url_generator'];
+  $subRequest = Request::create($generator->generate('blog_list', 'GET'));
+  return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
+});
 
 $blogPosts = [
   1 => [
@@ -52,6 +87,9 @@ $app->get('/blogs', function () use ($blogPosts) {
   $output .= "</ul>\n";
   return $output;
 })->bind('blog_list');
+$app->get('/blogs-json', function () use ($app, $blogPosts) {
+  return $app->json($blogPosts);
+});
 $app->get('/blogs-json-view', function () use ($blogPosts) {
   return $blogPosts; // Rely on the view handler.
 });