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
|
|
|
/** @var Handler */ |
25
|
|
|
private $handler; |
26
|
|
|
|
27
|
|
|
/** @var Middleware[] */ |
28
|
|
|
private $middleware; |
29
|
|
|
|
30
|
|
|
/** @var int */ |
31
|
|
|
private $index = 0; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param Handler $handler |
35
|
|
|
* @param Middleware[] $middleware |
36
|
|
|
*/ |
37
|
75 |
|
private function __construct($handler, $middleware) |
38
|
|
|
{ |
39
|
75 |
|
$this->handler = $handler; |
40
|
75 |
|
$this->middleware = $middleware; |
41
|
75 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param Middleware[] $middleware |
45
|
|
|
*/ |
46
|
75 |
|
public static function create(Handler $handler, array $middleware, bool $prepend = false) : Handler |
47
|
|
|
{ |
48
|
75 |
|
if (!$handler instanceof self) { |
49
|
75 |
|
return new self($handler, $middleware); |
50
|
|
|
} |
51
|
|
|
|
52
|
12 |
|
$handler = clone $handler; |
53
|
12 |
|
$handler->middleware = $prepend |
54
|
6 |
|
? \array_merge($middleware, $handler->middleware) |
55
|
6 |
|
: \array_merge($handler->middleware, $middleware); |
56
|
|
|
|
57
|
12 |
|
return $handler; |
58
|
|
|
} |
59
|
|
|
|
60
|
75 |
|
public function handle(Request $request) : Response |
61
|
|
|
{ |
62
|
75 |
|
if (!isset($this->middleware[$this->index])) { |
63
|
60 |
|
return $this->handler->handle($request); |
64
|
|
|
} |
65
|
|
|
|
66
|
75 |
|
$new = clone $this; |
67
|
75 |
|
++$new->index; |
68
|
|
|
|
69
|
75 |
|
return $this->middleware[$this->index]->process($request, $new); |
70
|
|
|
} |
71
|
|
|
|
72
|
39 |
|
public function getConnection() : Connection |
73
|
|
|
{ |
74
|
39 |
|
return $this->handler->getConnection(); |
75
|
|
|
} |
76
|
|
|
|
77
|
3 |
|
public function getPacker() : Packer |
78
|
|
|
{ |
79
|
3 |
|
return $this->handler->getPacker(); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|