Completed
Push — master ( 3a869f...beb3fd )
by John
12s
created

HTTPServer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
namespace LunixREST;
3
4
use LunixREST\RequestFactory\Exceptions\UnableToCreateRequestException;
5
use LunixREST\Server\APIResponse\APIResponse;
6
use LunixREST\Server\Exceptions\UnableToHandleRequestException;
7
use LunixREST\RequestFactory\RequestFactory;
8
use LunixREST\Server\Server;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Log\LoggerAwareTrait;
12
use Psr\Log\LoggerInterface;
13
use Psr\Log\LogLevel;
14
15
/**
16
 * A class that interfaces PSR-7 with our APIRequests and uses a Server to handle the APIRequest. Handles the PSR-7 response building as well.
17
 * Class HTTPServer
18
 * @package LunixREST
19
 */
20
class HTTPServer
21
{
22
    use LoggerAwareTrait;
23
24
    /**
25
     * @var Server
26
     */
27
    protected $server;
28
    /**
29
     * @var RequestFactory
30
     */
31
    protected $requestFactory;
32
33
    /**
34
     * HTTPServer constructor.
35
     * @param Server $server
36
     * @param RequestFactory $requestFactory
37
     * @param LoggerInterface $logger
38
     */
39 35
    public function __construct(Server $server, RequestFactory $requestFactory, LoggerInterface $logger)
40
    {
41 35
        $this->server = $server;
42 35
        $this->requestFactory = $requestFactory;
43 35
        $this->logger = $logger;
44 35
    }
45
46
    /**
47
     * Clones a response, changing contents based on the handling of a given request.
48
     * Taking in a response allows us not to define a specific response implementation to create.
49
     * @param ServerRequestInterface $serverRequest
50
     * @param ResponseInterface $response
51
     * @return ResponseInterface
52
     */
53 35
    public function handleRequest(ServerRequestInterface $serverRequest, ResponseInterface $response): ResponseInterface
54
    {
55 35
        $response = $response->withProtocolVersion($serverRequest->getProtocolVersion());
56
57
        try {
58
            try {
59 35
                $APIRequest = $this->requestFactory->create($serverRequest);
60 6
            } catch (UnableToCreateRequestException $exception) {
61 3
                return $this->handleRequestFactoryException($exception, $response);
62
            }
63
64
            try {
65 29
                $APIResponse = $this->server->handleRequest($APIRequest);
66 25
            } catch (UnableToHandleRequestException $exception) {
67 22
                return $this->handleServerException($exception, $response);
68
            }
69
70 4
            return $this->buildResponse($APIResponse, $response);
71 7
        } catch (\Throwable $e) {
72 7
            $this->logCaughtThrowableResultingInHTTPCode(500, $e, LogLevel::CRITICAL);
73 7
            return $response->withStatus(500, "Internal Server Error");
74
        }
75
    }
76
77
    /**
78
     * Takes an APIResponse and builds a PSR-7 Response
79
     * @param APIResponse $APIResponse
80
     * @param ResponseInterface $response
81
     * @return ResponseInterface
82
     */
83 4
    protected function buildResponse(APIResponse $APIResponse, ResponseInterface $response): ResponseInterface
84
    {
85 4
        $response = $response->withStatus(200, "200 OK");
86 4
        $response = $response->withAddedHeader("Content-Type", $APIResponse->getMIMEType());
87 4
        $response = $response->withAddedHeader("Content-Length", $APIResponse->getAsDataStream()->getSize());
88 4
        $this->logger->debug("Responding to request successfully");
89 4
        return $response->withBody($APIResponse->getAsDataStream());
90
    }
91
92
    /**
93
     * @param UnableToCreateRequestException $exception
94
     * @param ResponseInterface $response
95
     * @return ResponseInterface
96
     */
97 3
    protected function handleRequestFactoryException(UnableToCreateRequestException $exception, ResponseInterface $response): ResponseInterface
98
    {
99 3
        $this->logCaughtThrowableResultingInHTTPCode(400, $exception, LogLevel::INFO);
100 3
        return $response->withStatus(400, "Bad Request");
101
    }
102
103
    /**
104
     * @param UnableToHandleRequestException $exception
105
     * @param ResponseInterface $response
106
     * @return ResponseInterface
107
     */
108 3
    protected function handleServerException(UnableToHandleRequestException $exception, ResponseInterface $response): ResponseInterface
109
    {
110 3
        $this->logCaughtThrowableResultingInHTTPCode(500, $exception, LogLevel::CRITICAL);
111 3
        return $response->withStatus(500, "Internal Server Error");
112
    }
113
114
    /**
115
     * Dumps a PSR-7 ResponseInterface to the SAPI.
116
     * @param ResponseInterface $response
117
     */
118 9
    public static function dumpResponse(ResponseInterface $response)
119
    {
120 9
        $statusLine = sprintf(
121 9
            "HTTP/%s %d %s",
122 9
            $response->getProtocolVersion(),
123 9
            $response->getStatusCode(),
124 9
            $response->getReasonPhrase()
125
        );
126
127 9
        header($statusLine, true, $response->getStatusCode());
128
129 9
        foreach ($response->getHeaders() as $name => $values) {
130 3
            foreach ($values as $value) {
131 3
                header(sprintf('%s: %s', $name, $value), false);
132
            }
133
        }
134
135 9
        $body = $response->getBody();
136 9
        while(!$body->eof()) {
137 9
            echo $body->read(1024);
138
        }
139 9
    }
140
141
    /**
142
     * @param int $code
143
     * @param \Throwable $exception
144
     * @param $level
145
     */
146 32
    protected function logCaughtThrowableResultingInHTTPCode(int $code, \Throwable $exception, $level): void
147
    {
148 32
        $this->logger->log($level, "Returning HTTP {code}: {message}", ["code" => $code, "message" => $exception->getMessage()]);
149 32
    }
150
}
151