HttpServer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
namespace Nopolabs\Yabot\Http;
3
4
use Exception;
5
use Psr\Log\LoggerInterface;
6
use React\EventLoop\LoopInterface;
7
use React\Http\Server;
8
use React\Socket\Server as SocketServer;
9
use React\Http\Request as HttpRequest;
10
use React\Http\Response as HttpResponse;
11
12
class HttpServer
13
{
14
    private $socket;
15
    private $http;
16
    private $logger;
17
    private $handlers;
18
19
    public function __construct($port, LoopInterface $loop, LoggerInterface $logger)
20
    {
21
        $this->logger = $logger;
22
        $this->handlers = [];
23
24
        $this->socket = new SocketServer($port, $loop);
25
        $this->http = new Server($this->socket);
26
27
        $this->http->on('request', [$this, 'request']);
28
        $this->http->on('error', [$this, 'error']);
29
        $this->socket->on('error', [$this, 'error']);
30
    }
31
32
    public function addHandler(callable $handler)
33
    {
34
        $this->handlers[] = $handler;
35
    }
36
37
    public function request(HttpRequest $request, HttpResponse $response)
38
    {
39
        foreach ($this->handlers as $handler) {
40
            try {
41
                call_user_func_array($handler, [$request, $response]);
42
            } catch (Exception $e) {
43
                $this->error($e);
44
            }
45
        }
46
    }
47
48
    public function error(Exception $exception)
49
    {
50
        $this->logger->warning($exception->getMessage());
51
        $this->logger->warning($exception->getTraceAsString());
52
    }
53
}
54