<?php
declare(strict_types=1);

namespace App\Middleware;

use Core\Middleware;
use Core\Tool;

/** Validate CSRF token on state-changing web requests. */
final class Csrf implements Middleware
{
    public function handle(array $context): void
    {
        $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        if (in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) return;

        $token = $_POST['_csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? null;
        if (!Tool::checkCsrf($token)) {
            http_response_code(419);
            echo 'CSRF token mismatch';
            exit;
        }
    }
}
