Completed
Push — master ( f9ded0...b13d5b )
by John
02:58 queued 01:00
created

HTTPServer::handleSAPIRequest()   C

Complexity

Conditions 12
Paths 83

Size

Total Lines 35
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 2
Bugs 0 Features 1
Metric Value
dl 0
loc 35
rs 5.1612
c 2
b 0
f 1
ccs 0
cts 33
cp 0
cc 12
eloc 29
nc 83
nop 5
crap 156

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace LunixREST\Server;
3
4
use LunixREST\Endpoint\Exceptions\UnknownEndpointException;
5
use LunixREST\Exceptions\AccessDeniedException;
6
use LunixREST\Exceptions\InvalidAPIKeyException;
7
use LunixREST\Exceptions\ThrottleLimitExceededException;
8
use LunixREST\APIRequest\RequestFactory\RequestFactory;
9
use LunixREST\APIRequest\URLParser\Exceptions\InvalidRequestURLException;
10
use LunixREST\APIResponse\Exceptions\NotAcceptableResponseTypeException;
11
use LunixREST\Server\Exceptions\MethodNotFoundException;
12
use Psr\Http\Message\ResponseInterface;
13
use Psr\Http\Message\ServerRequestInterface;
14
15
class HTTPServer
16
{
17
    /**
18
     * @var Server
19
     */
20
    protected $server;
21
    /**
22
     * @var RequestFactory
23
     */
24
    private $requestFactory;
25
26
    /**
27
     * HTTPServer constructor.
28
     * @param Server $server
29
     * @param RequestFactory $requestFactory
30
     */
31
    //TODO: Add RequestLogger that we can pass through to log requests
32
    //TODO: Add ErrorLogger to log errors (500s)
33
    public function __construct(Server $server, RequestFactory $requestFactory)
34
    {
35
        $this->server = $server;
36
        $this->requestFactory = $requestFactory;
37
    }
38
39
    /**
40
     * clones a response, changing contents based on the handling of a given request
41
     * Taking in a response allows us not to define a specific response implementation to create
42
     * @param ServerRequestInterface $serverRequest
43
     * @param ResponseInterface $response
44
     * @return ResponseInterface
45
     */
46
    public function handleRequest(ServerRequestInterface $serverRequest, ResponseInterface $response): ResponseInterface
47
    {
48
        $response = $response->withProtocolVersion($serverRequest->getProtocolVersion());
49
50
        try {
51
            $APIRequest = $this->requestFactory->create($serverRequest);
52
53
            try {
54
                $APIResponse = $this->server->handleRequest($APIRequest);
55
56
                $response = $response->withStatus(200, "200 OK");
57
                $response = $response->withAddedHeader("Content-Type", $APIResponse->getMIMEType());
58
                $response = $response->withAddedHeader("Content-Length", $APIResponse->getAsDataStream()->getSize());
59
                $response = $response->withBody($APIResponse->getAsDataStream());
60
            } catch (InvalidAPIKeyException $e) {
61
                $response = $response->withStatus(400, "400 Bad Request");
62
            } catch (UnknownEndpointException $e) {
63
                $response = $response->withStatus(404, "404 Not Found");
64
            } catch (NotAcceptableResponseTypeException $e) {
65
                $response = $response->withStatus(406, "406 Not Acceptable");
66
            } catch (AccessDeniedException $e) {
67
                $response = $response->withStatus(403, "403 Access Denied");
68
            } catch (ThrottleLimitExceededException $e) {
69
                $response = $response->withStatus(429, "429 Too Many Requests");
70
            } catch (MethodNotFoundException | \Throwable $e) {
1 ignored issue
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
71
                $response = $response->withStatus(500, "500 Internal Server Error");
72
            }
73
        } catch (InvalidRequestURLException $e) {
74
            $response = $response->withStatus(400, "400 Bad Request");
75
        } catch (MethodNotFoundException | \Throwable $e) {
1 ignored issue
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
76
            $response = $response->withStatus(500, "500 Internal Server Error");
77
        }
78
        return $response;
79
    }
80
81
    public function dumpResponse(ResponseInterface $response) {
82
        header(sprintf("HTTP/%s", $response->getProtocolVersion()));
83
84
        header($response->getReasonPhrase(), true, $response->getStatusCode());
85
86
        foreach ($response->getHeaders() as $name => $values) {
87
            foreach ($values as $value) {
88
                header(sprintf('%s: %s', $name, $value), false);
89
            }
90
        }
91
92
        $body = $response->getBody();
93
        while(!$body->eof()) {
94
            echo $body->read(1024);
95
        }
96
    }
97
}
98