Browse Source

Ch. 4: Access request content, cookies, headers.

Frederic G. MARAND 6 years ago
parent
commit
600dadc103
2 changed files with 31 additions and 2 deletions
  1. 14 2
      src/Controller/LuckyController.php
  2. 17 0
      templates/lucky/number.html.twig

+ 14 - 2
src/Controller/LuckyController.php

@@ -14,7 +14,8 @@ class LuckyController extends Controller {
   /**
    * @Route(
    *   name="lucky-number",
-   *   path="/lucky/number"
+   *   path="/lucky/number",
+   *   methods={"GET", "POST", "PUT", "PATCH"}
    * )
    *
    * @see config/services.yaml
@@ -26,9 +27,20 @@ class LuckyController extends Controller {
       ? (int) $request->query->get('value')
       : mt_rand(0, 100);
 
-    $logger->notice("We sent $number");
+    /* Example features of the Request */
+    assert(false === $request->isXmlHttpRequest());
+
+    // Uses Accept-Language header.
+    $preferred = $request->getPreferredLanguage(['en', 'fr']);
+
+    // Empty on GET, valid on PATH, POST, PUT.
+    $requestValue = $request->request->get('value');
+
+    $logger->notice("We sent $number on GET, $requestValue on POST/PUT/PATCH");
     return $this->render("lucky/number.html.twig", [
       "number" => $number,
+      // No need for cookies->all(): Twig can use {% for %} on iterators.
+      "cookies" => $request->cookies,
     ]);
   }
 

+ 17 - 0
templates/lucky/number.html.twig

@@ -1,5 +1,22 @@
 {% extends 'base.html.twig' %}
 
 {% block body %}
+{% if cookies %}
+    <h2>Cookies</h2>
+    <table>
+        <tr>
+            <th>Name</th>
+            <th>Value</th>
+        </tr>
+        {% for name, value in cookies %}
+        <tr>
+            <td>{{ name }}</td>
+            <td>{{ value }}</td>
+        </tr>
+        {% endfor %}
+    </table>
+{% endif %}
+
+    <h2>Luck</h2>
 <p>Your lucky number is {{ number }}.</p>
 {% endblock %}