TimingMiddleware   A
last analyzed

Complexity

Total Complexity 1

Size/Duplication

Total Lines 9
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 10
c 0
b 0
f 0
eloc 6
wmc 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 7 1
1
<?php
2
3
declare(strict_types=1);
4
5
require_once \dirname(__DIR__) . '/vendor/autoload.php';
6
7
use Gacela\Router\Configure\Middlewares;
8
use Gacela\Router\Configure\Routes;
9
use Gacela\Router\Entities\Request;
10
use Gacela\Router\Entities\Response;
11
use Gacela\Router\Middleware\MiddlewareInterface;
12
use Gacela\Router\Router;
13
14
# To run this example locally, you can run in your terminal:
15
# $ composer serve
16
17
class Controller
18
{
19
    public function __construct(
20
        private Request $request,
21
    ) {
22
    }
23
24
    public function __invoke(): string
25
    {
26
        $number = $this->request->get('number');
27
28
        if (!empty($number)) {
29
            return \sprintf("__invoke with 'number'=%d", $number);
30
        }
31
32
        return '__invoke';
33
    }
34
35
    public function customAction(int $number = 0): string
36
    {
37
        return "customAction(number: {$number})";
38
    }
39
40
    public function customHeaders(): Response
41
    {
42
        return new Response('{"custom": "headers"}', [
43
            'Access-Control-Allow-Origin: *',
44
            'Content-Type: application/json',
45
        ]);
46
    }
47
}
48
49
// Example middleware that adds a custom header to all responses
50
class TimingMiddleware implements MiddlewareInterface
51
{
52
    public function handle(Request $request, Closure $next): string
53
    {
54
        $start = microtime(true);
55
        $response = $next($request);
56
        $time = round((microtime(true) - $start) * 1000, 2);
57
        header("X-Response-Time: {$time}ms");
58
        return $response;
59
    }
60
}
61
62
$router = new Router(static function (Routes $routes, Middlewares $middlewares): void {
63
    // Add a global middleware that applies to all routes
64
    $middlewares->add(new TimingMiddleware());
65
66
    # Try it out: http://localhost:8081/docs
67
    $routes->redirect('docs', 'https://gacela-project.com/');
68
69
    # Try it out: http://localhost:8081?number=456
70
    $routes->match(['GET', 'POST'], '/', Controller::class);
71
72
    # Try it out: http://localhost:8081/custom/123
73
    $routes->get('custom/{number}', Controller::class, 'customAction');
74
75
    # Try it out: http://localhost:8081/custom
76
    $routes->any('custom', Controller::class);
77
78
    # Try it out: http://localhost:8081/headers
79
    $routes->any('headers', Controller::class, 'customHeaders');
80
});
81
82
$router->run();
83