Completed
Push — master ( ccb503...769203 )
by Dawid
02:33
created

HttpServer   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 65.31%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 4
dl 0
loc 93
ccs 32
cts 49
cp 0.6531
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A createHandler() 0 13 2
A addListener() 0 5 1
A createListeners() 0 5 1
B createOnRequestListener() 0 54 10
1
<?php declare(strict_types=1);
2
3
namespace Igni\Network\Server;
4
5
use Igni\Network\Exception\HttpException;
6
use Igni\Network\Http\Response;
7
use Igni\Network\Http\ServerRequest;
8
use Igni\Network\Server;
9
use Psr\Log\LoggerInterface;
10
use Swoole\Http\Request as SwooleHttpRequest;
11
use Swoole\Http\Response as SwooleHttpResponse;
12
use Swoole\Http\Server as SwooleHttpServer;
13
14
use function explode;
15
use function gzdeflate;
16
use function implode;
17
use function in_array;
18
use function strtolower;
19
20
class HttpServer extends Server implements HandlerFactory
21
{
22
    /**
23
     * @var int
24
     */
25
    private $compressionLevel = 0;
26
27 3
    public function __construct(Configuration $settings = null, LoggerInterface $logger = null, HandlerFactory $handlerFactory = null)
28
    {
29 3
        parent::__construct($settings, $logger, $handlerFactory ?? $this);
30 3
    }
31
32
    public function createHandler(Configuration $configuration)
33
    {
34
        $flags = SWOOLE_TCP;
35
        if ($configuration->isSslEnabled()) {
36
            $flags |= SWOOLE_SSL;
37
        }
38
        $settings = $configuration->toArray();
39
        $this->compressionLevel = $settings['compression_level'] ?? 0;
40
        $handler = new SwooleHttpServer($settings['address'], $settings['port'], SWOOLE_PROCESS, $flags);
41
        $handler->set($settings);
42
43
        return $handler;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $handler; (Swoole\Http\Server) is incompatible with the return type of the parent method Igni\Network\Server::createHandler of type Swoole\Server.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
44
    }
45
46 2
    public function addListener(Listener $listener): void
47
    {
48 2
        $this->addListenerByType($listener, OnRequestListener::class);
49 2
        parent::addListener($listener);
50 2
    }
51
52 2
    protected function createListeners(): void
53
    {
54 2
        $this->createOnRequestListener();
55 2
        parent::createListeners();
56 2
    }
57
58 2
    protected function createOnRequestListener(): void
59
    {
60
        /**  */
61
        $this->handler->on('Request', function(SwooleHttpRequest $request, SwooleHttpResponse $response) {
62 2
            $psrRequest = ServerRequest::fromSwoole($request);
63 2
            $psrResponse = Response::empty();
64
65 2
            $queue = clone $this->listeners[OnRequestListener::class];
66
67
            try {
68
                /** @var OnRequestListener $listener */
69 2
                while (!$queue->isEmpty() && $listener = $queue->pop()) {
70 2
                    $psrResponse = $listener->onRequest($this->getClient($request->fd), $psrRequest, $psrResponse);
71
                }
72
            } catch (HttpException $exception) {
0 ignored issues
show
Bug introduced by
The class Igni\Network\Exception\HttpException 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...
73
                $psrResponse = $exception->toResponse();
74
            } catch (\Throwable $throwable) {
75
                $this->logger->error($throwable->getMessage());
76
                $psrResponse = Response::empty(Response::HTTP_INTERNAL_SERVER_ERROR);
77
            }
78
79
            // Set headers
80 2
            foreach ($psrResponse->getHeaders() as $name => $values) {
81 1
                foreach ($values as $value) {
82 1
                    $response->header($name, $value);
83
                }
84
            }
85
86
            // Response body.
87 2
            $body = $psrResponse->getBody()->getContents();
88
89
            // Status code
90 2
            $response->status($psrResponse->getStatusCode());
91
92
            // Protect server software header.
93 2
            $response->header('software-server', '');
94 2
            $response->header('server', '');
95
96
            // Support gzip/deflate encoding.
97 2
            if ($psrRequest->hasHeader('accept-encoding')) {
98 1
                $encoding = explode(',', strtolower(implode(',', $psrRequest->getHeader('accept-encoding'))));
99
100 1
                if (in_array('gzip', $encoding, true)) {
101 1
                    $response->header('content-encoding', 'gzip');
102 1
                    $body = gzencode($body, $this->compressionLevel);
103
                } elseif (in_array('deflate', $encoding, true)) {
104
                    $response->header('content-encoding', 'deflate');
105
                    $body = gzdeflate($body, $this->compressionLevel);
106
                }
107
            }
108
109 2
            $response->end($body);
110 2
        });
111 2
    }
112
}
113