MethodHandler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
eloc 13
dl 0
loc 50
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A checkAllowedMethods() 0 10 3
A run() 0 6 2
A __construct() 0 6 1
A error() 0 4 3
1
<?php
2
3
namespace kalanis\Restful\Application\Events;
4
5
6
use Exception;
7
use kalanis\Restful\Application\Exceptions\BadRequestException;
8
use kalanis\Restful\Application\MethodOptions;
9
use Nette\Application\Application;
10
use Nette\Application\BadRequestException as NetteBadRequestException;
11
use Nette\Http\IRequest;
12
use Nette\Http\IResponse;
13
use Throwable;
14
15
16
/**
17
 * MethodHandler
18
 * @package kalanis\Restful\Application
19
 */
20
class MethodHandler
21
{
22
23 1
    public function __construct(
24
        private readonly IRequest      $request,
25
        private readonly IResponse     $response,
26
        private readonly MethodOptions $methods,
27
    )
28
    {
29 1
    }
30
31
    /**
32
     * On application run
33
     *
34
     * @throws BadRequestException
35
     */
36
    public function run(Application $application): void
37
    {
38 1
        $router = $application->getRouter();
39 1
        $appRequest = $router->match($this->request);
40 1
        if (!$appRequest) {
41 1
            $this->checkAllowedMethods();
42
        }
43 1
    }
44
45
    /**
46
     * Check allowed methods
47
     *
48
     * @throws BadRequestException If method is not supported but another one can be used
49
     */
50
    protected function checkAllowedMethods(): void
51
    {
52 1
        $availableMethods = $this->methods->getOptions($this->request->getUrl());
53 1
        if (!$availableMethods || in_array($this->request->getMethod(), $availableMethods)) {
54 1
            return;
55
        }
56
57 1
        $allow = implode(', ', $availableMethods);
58 1
        $this->response->setHeader('Allow', $allow);
59 1
        throw BadRequestException::methodNotSupported('Method not supported. Available methods: ' . $allow);
60
    }
61
62
    /**
63
     * On application error
64
     * @param Exception|Throwable $e
65
     */
66
    public function error(Application $application, $e): void
67
    {
68 1
        if ($e instanceof NetteBadRequestException && 404 === $e->getCode()) {
69 1
            $this->checkAllowedMethods();
70
        }
71 1
    }
72
}
73