Completed
Pull Request — master (#37)
by Eugene
08:41
created

MiddlewareHandler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 17
dl 0
loc 42
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getPacker() 0 3 2
A create() 0 14 3
A handle() 0 3 1
A __construct() 0 4 1
A getConnection() 0 3 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Tarantool Client package.
7
 *
8
 * (c) Eugene Leonovich <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Tarantool\Client\Handler;
15
16
use Tarantool\Client\Connection\Connection;
17
use Tarantool\Client\Middleware\Middleware;
18
use Tarantool\Client\Packer\Packer;
19
use Tarantool\Client\Request\Request;
20
use Tarantool\Client\Response;
21
22
final class MiddlewareHandler implements Handler
23
{
24
    private $middleware;
25
    private $handler;
26
    private $connection;
27
    private $packer;
28
29
    public function __construct(Middleware $middleware, Handler $handler)
30
    {
31
        $this->middleware = $middleware;
32
        $this->handler = $handler;
33
    }
34
35
    public static function create(Handler $handler, array $middlewares) : Handler
36
    {
37
        if (!$middlewares) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $middlewares of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
38
            return $handler;
39
        }
40
41
        $middleware = \end($middlewares);
42
43
        while ($middleware) {
44
            $handler = new self($middleware, $handler);
45
            $middleware = \prev($middlewares);
46
        }
47
48
        return $handler;
49
    }
50
51
    public function getConnection() : Connection
52
    {
53
        return $this->connection ?: $this->connection = $this->handler->getConnection();
54
    }
55
56
    public function getPacker() : Packer
57
    {
58
        return $this->packer ?: $this->packer = $this->handler->getPacker();
59
    }
60
61
    public function handle(Request $request) : Response
62
    {
63
        return $this->middleware->process($request, $this->handler);
64
    }
65
}
66