Controller   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 28
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A customAction() 0 3 1
A __invoke() 0 9 2
A customHeaders() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
require_once \dirname(__DIR__) . '/vendor/autoload.php';
6
7
use Gacela\Router\Configure\Routes;
8
use Gacela\Router\Entities\Request;
9
use Gacela\Router\Entities\Response;
10
use Gacela\Router\Router;
11
12
# To run this example locally, you can run in your terminal:
13
# $ composer serve
14
15
class Controller
16
{
17
    public function __construct(
18
        private Request $request,
19
    ) {
20
    }
21
22
    public function __invoke(): string
23
    {
24
        $number = $this->request->get('number');
25
26
        if (!empty($number)) {
27
            return sprintf("__invoke with 'number'=%d", $number);
28
        }
29
30
        return '__invoke';
31
    }
32
33
    public function customAction(int $number = 0): string
34
    {
35
        return "customAction(number: {$number})";
36
    }
37
38
    public function customHeaders(): Response
39
    {
40
        return new Response('{"custom": "headers"}', [
41
            'Access-Control-Allow-Origin: *',
42
            'Content-Type: application/json',
43
        ]);
44
    }
45
}
46
47
$router = new Router(static function (Routes $routes): void {
48
    # Try it out: http://localhost:8081/docs
49
    $routes->redirect('docs', 'https://gacela-project.com/');
50
51
    # Try it out: http://localhost:8081?number=456
52
    $routes->match(['GET', 'POST'], '/', Controller::class);
53
54
    # Try it out: http://localhost:8081/custom/123
55
    $routes->get('custom/{number}', Controller::class, 'customAction');
56
57
    # Try it out: http://localhost:8081/custom
58
    $routes->any('custom', Controller::class);
59
60
    # Try it out: http://localhost:8081/headers
61
    $routes->any('headers', Controller::class, 'customHeaders');
62
});
63
64
$router->run();
65