Lost in the post

Exercise 7 of 9 in chapter 5 · 150 XP · 5 objectives checked by tests

Topics covered: HTTP status codes404405http_response_codetryFrom()

Léo, the mayor's grandson, has fun typing anything at all in the address bar: /articles/the-mayor-won-the-lottery, /sections/sport… The gazette answers with a blank page, or crashes. A real website answers “this page does not exist”, with the matching HTTP status code, so that browsers and search engines understand it too.

Your mission

  1. Next to rendre(), add a static method introuvable(): string (not found) to Page: it sets the 404 status code with http_response_code() and returns a page with <main class="lecture">, the heading <h2>Lost in the post</h2>, a word of apology and an <a class="retour"> link to the front page.

  2. When no route matches, show this page.

  3. When the route exists but not for this method (a POST to the front page), respond 405: $route[0] is then Dispatcher::METHOD_NOT_ALLOWED. A simple http_response_code(405); is enough, with or without a page.

  4. An unknown article or section also responds 404:

    • for an unknown article, Redaction::article() returns null;
    • for a section, replace Rubrique::from() with Rubrique::tryFrom(). Both methods exist on every backed enum, but tryFrom('sport') returns null instead of crashing.

    In both cases, test for null and return the not-found page:

    $rubrique = Rubrique::tryFrom($parametres['nom']);
    if ($rubrique === null) {
        return Page::introuvable();
    }
    

Reminder

Every HTTP response carries a status code: 200 all is well, 404 not found, 405 method not allowed, 500 server error. http_response_code(404) sets it. It must be called before the page is sent: that is why the handlers return the HTML instead of displaying it, and why echo comes last. Rubrique::from() throws an error for an unknown value, Rubrique::tryFrom() returns null: it's up to you to decide what to do.