1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Tarantool Client package. |
5
|
|
|
* |
6
|
|
|
* (c) Eugene Leonovich <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
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 $handler; |
25
|
|
|
private $middlewares; |
26
|
|
|
private $index = 0; |
27
|
|
|
|
28
|
15 |
|
private function __construct(Handler $handler, array $middlewares) |
29
|
|
|
{ |
30
|
15 |
|
$this->handler = $handler; |
31
|
15 |
|
$this->middlewares = $middlewares; |
32
|
15 |
|
} |
33
|
|
|
|
34
|
15 |
|
public static function create(Handler $handler, Middleware $middleware, Middleware ...$middlewares) : Handler |
35
|
|
|
{ |
36
|
15 |
|
if (!$handler instanceof self) { |
37
|
15 |
|
return $middlewares |
38
|
2 |
|
? new self($handler, \array_merge([$middleware], $middlewares)) |
39
|
15 |
|
: new self($handler, [$middleware]); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
$handler = clone $handler; |
43
|
1 |
|
$handler->middlewares[] = $middleware; |
44
|
1 |
|
if ($middlewares) { |
|
|
|
|
45
|
|
|
$handler->middlewares = \array_merge($handler->middlewares, $middlewares); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
return $handler; |
49
|
|
|
} |
50
|
|
|
|
51
|
15 |
|
public function handle(Request $request) : Response |
52
|
|
|
{ |
53
|
15 |
|
if (!isset($this->middlewares[$this->index])) { |
54
|
15 |
|
return $this->handler->handle($request); |
55
|
|
|
} |
56
|
|
|
|
57
|
15 |
|
$new = clone $this; |
58
|
15 |
|
++$new->index; |
59
|
|
|
|
60
|
15 |
|
return $this->middlewares[$this->index]->process($request, $new); |
61
|
|
|
} |
62
|
|
|
|
63
|
7 |
|
public function getConnection() : Connection |
64
|
|
|
{ |
65
|
7 |
|
return $this->handler->getConnection(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function getPacker() : Packer |
69
|
|
|
{ |
70
|
|
|
return $this->handler->getPacker(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
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.