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\Request\RequestFactory\RequestFactory; |
9
|
|
|
use LunixREST\Request\URLParser\Exceptions\InvalidRequestURLException; |
10
|
|
|
use LunixREST\Response\Exceptions\UnknownResponseTypeException; |
11
|
|
|
|
12
|
|
|
class HTTPServer { |
13
|
|
|
/** |
14
|
|
|
* @var Server |
15
|
|
|
*/ |
16
|
|
|
protected $server; |
17
|
|
|
/** |
18
|
|
|
* @var RequestFactory |
19
|
|
|
*/ |
20
|
|
|
private $requestFactory; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* HTTPServer constructor. |
24
|
|
|
* @param Server $server |
25
|
|
|
* @param RequestFactory $requestFactory |
26
|
|
|
*/ |
27
|
|
|
public function __construct(Server $server, RequestFactory $requestFactory) { |
28
|
|
|
$this->server = $server; |
29
|
|
|
$this->requestFactory = $requestFactory; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function handleSAPIRequest() { |
|
|
|
|
33
|
|
|
try { |
34
|
|
|
$request = $this->requestFactory->create($_SERVER['REQUEST_METHOD'], getallheaders(), |
35
|
|
|
file_get_contents("php://input"), $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI']); |
36
|
|
|
|
37
|
|
|
try { |
38
|
|
|
$response = $this->server->handleRequest($request); |
39
|
|
|
echo $response->getAsString(); |
40
|
|
|
} catch(InvalidAPIKeyException $e){ |
41
|
|
|
header('400 Bad Request', true, 400); |
42
|
|
|
} catch(UnknownEndpointException $e){ |
43
|
|
|
header('404 Not Found', true, 404); |
44
|
|
|
} catch(UnknownResponseTypeException $e){ |
45
|
|
|
header('404 Not Found', true, 404); |
46
|
|
|
} catch(AccessDeniedException $e){ |
47
|
|
|
header('403 Access Denied', true, 403); |
48
|
|
|
} catch(ThrottleLimitExceededException $e){ |
49
|
|
|
header('429 Too Many Requests', true, 429); |
50
|
|
|
} catch (\Exception $e) { |
51
|
|
|
header('500 Internal Server Error', true, 500); |
52
|
|
|
} |
53
|
|
|
} catch(InvalidRequestURLException $e){ |
54
|
|
|
header('400 Bad Request', true, 400); |
55
|
|
|
} catch(\Exception $e){ |
56
|
|
|
header('500 Internal Server Error', true, 500); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: