File size: 1,389 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php

declare(strict_types=1);

namespace Presentation;

use Easy\Http\Server\DispatcherInterface;
use Easy\Http\Server\Exceptions\DispatcherExceptionInterface;
use Easy\Http\Server\Exceptions\MethodNotAllowedExceptionInterface;
use Easy\Http\Server\Exceptions\RouteNotFoundExceptionInterface;
use Easy\HttpServerHandler\HttpServerHandler;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ServerRequestHandler implements RequestHandlerInterface
{
    public function __construct(
        private DispatcherInterface $dispatcher
    ) {
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws DispatcherExceptionInterface
     * @throws MethodNotAllowedExceptionInterface
     * @throws RouteNotFoundExceptionInterface
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $route = $this->dispatcher->dispatch($request);

        foreach ($route->getParams() as $param) {
            $request = $request->withAttribute(
                $param->getKey(),
                $param->getValue()
            );
        }

        $handler = new HttpServerHandler(
            $route->getRequestHandler(),
            ...$route->getMiddlewares()
        );

        return $handler->handle($request);
    }
}