RequestHandler::output()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace MatthiasMullie\Api;
4
5
use GuzzleHttp\Psr7\Response;
6
use League\Route\RouteCollection;
7
use League\Route\Strategy\JsonStrategy;
8
use MatthiasMullie\Api\Routes\Providers\RouteProviderInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
12
/**
13
 * @author Matthias Mullie <[email protected]>
14
 * @copyright Copyright (c) 2016, Matthias Mullie. All rights reserved
15
 * @license LICENSE MIT
16
 */
17
class RequestHandler
18
{
19
    /**
20
     * @var RouteCollection
21
     */
22
    protected $router;
23
24
    /**
25
     * @param RouteProviderInterface $routes
26
     */
27
    public function __construct(RouteProviderInterface $routes)
28
    {
29
        $this->router = new RouteCollection();
30
        $this->router->setStrategy(new JsonStrategy());
31
        foreach ($routes->getRoutes() as $route) {
32
            $this->router->map(
33
                $route->getMethods(),
34
                $route->getPath(),
35
                $route->getHandler()
36
            );
37
        }
38
    }
39
40
    /**
41
     * @param ServerRequestInterface $request
42
     *
43
     * @return ResponseInterface
44
     */
45
    public function route(ServerRequestInterface $request): ResponseInterface
46
    {
47
        $response = $this->router->dispatch($request, new Response());
48
49
        // JsonStrategy will automatically add a Content-Type: application/json
50
        // header to the response, but without it being capitalized
51
        $contentType = $response->getHeader('content-type');
52
        if ($contentType) {
53
            $response = $response->withoutHeader('content-type');
54
            $response = $response->withHeader('Content-Type', $contentType);
55
        }
56
57
        return $response;
58
    }
59
60
    /**
61
     * @param ResponseInterface $response
62
     */
63
    public function output(ResponseInterface $response)
64
    {
65
        http_response_code($response->getStatusCode());
66
        foreach ($response->getHeaders() as $name => $values) {
67
            foreach ($values as $value) {
68
                header(sprintf('%s: %s', $name, $value), false);
69
            }
70
        }
71
        echo $response->getBody();
72
    }
73
}
74