1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Everlution\Ajaxcom; |
6
|
|
|
|
7
|
|
|
use Everlution\Ajaxcom\Responder\CallbackFunction; |
8
|
|
|
use Everlution\Ajaxcom\Responder\ChangeUrl; |
9
|
|
|
use Everlution\Ajaxcom\Responder\Container; |
10
|
|
|
use Everlution\Ajaxcom\Responder\ResponderInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class Handler. |
14
|
|
|
* |
15
|
|
|
* @author Everlution s.r.o. <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class Handler |
18
|
|
|
{ |
19
|
|
|
/** @var ResponderInterface[] */ |
20
|
|
|
private $queue = []; |
21
|
|
|
|
22
|
|
|
public function isQueueEmpty(): bool |
23
|
|
|
{ |
24
|
|
|
return empty($this->queue); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function register(ResponderInterface $responder): self |
28
|
|
|
{ |
29
|
|
|
$this->queue[] = $responder; |
30
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function unregister(ResponderInterface $responder): self |
35
|
|
|
{ |
36
|
|
|
if (false === ($key = array_search($responder, $this->queue, true))) { |
37
|
|
|
unset($this->queue[$key]); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function container(string $identifier): Container |
44
|
|
|
{ |
45
|
|
|
$responder = new Container($identifier); |
46
|
|
|
$this->register($responder); |
47
|
|
|
|
48
|
|
|
return $responder; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function callback(string $function, ?array $params): CallbackFunction |
52
|
|
|
{ |
53
|
|
|
$responder = new CallbackFunction($function, $params); |
54
|
|
|
$this->register($responder); |
55
|
|
|
|
56
|
|
|
return $responder; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function changeUrl(string $url, string $method = ChangeUrl::PUSH, int $wait = 0): ChangeUrl |
60
|
|
|
{ |
61
|
|
|
$responder = new ChangeUrl($url, $method, $wait); |
62
|
|
|
$this->register($responder); |
63
|
|
|
|
64
|
|
|
return $responder; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function respond(): array |
68
|
|
|
{ |
69
|
|
|
$response = []; |
70
|
|
|
foreach ($this->queue as $responder) { |
71
|
|
|
$response[] = $responder->render(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $response; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|