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

HttpServer::createOnRequestListener()   B

Complexity

Conditions 10
Paths 1

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 12.1001

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 21
cts 29
cp 0.7241
rs 7.1369
c 0
b 0
f 0
cc 10
nc 1
nop 0
crap 12.1001

How to fix   Long Method    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 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