|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of PHPinnacle/Ensign. |
|
4
|
|
|
* |
|
5
|
|
|
* (c) PHPinnacle Team <[email protected]> |
|
6
|
|
|
* |
|
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
8
|
|
|
* file that was distributed with this source code. |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
declare(strict_types = 1); |
|
12
|
|
|
|
|
13
|
|
|
namespace PHPinnacle\Ensign; |
|
14
|
|
|
|
|
15
|
|
|
use Amp; |
|
16
|
|
|
use Amp\Promise; |
|
17
|
|
|
use Amp\Success; |
|
18
|
|
|
|
|
19
|
|
|
final class Processor |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @var Executor |
|
23
|
|
|
*/ |
|
24
|
|
|
private $executor; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @var callable |
|
28
|
|
|
*/ |
|
29
|
|
|
private $resolver; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @var callable[] |
|
33
|
|
|
*/ |
|
34
|
|
|
private $interruptions = []; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param Executor $executor |
|
38
|
|
|
*/ |
|
39
|
9 |
|
public function __construct(Executor $executor = null) |
|
40
|
|
|
{ |
|
41
|
9 |
|
$this->executor = $executor ?: new Executor\SimpleExecutor; |
|
42
|
3 |
|
$this->resolver = function (string $interrupt, array $arguments) { |
|
43
|
3 |
|
if (!isset($this->interruptions[$interrupt])) { |
|
44
|
1 |
|
throw new Exception\UnknownInterrupt($interrupt); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
return $this->execute($this->interruptions[$interrupt], $arguments); |
|
48
|
|
|
}; |
|
49
|
9 |
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param string $interrupt |
|
53
|
|
|
* @param callable $handler |
|
54
|
|
|
* |
|
55
|
|
|
* @return void |
|
56
|
|
|
*/ |
|
57
|
6 |
|
public function interrupt(string $interrupt, callable $handler): void |
|
58
|
|
|
{ |
|
59
|
6 |
|
$this->interruptions[$interrupt] = $handler; |
|
60
|
6 |
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* @param callable $handler |
|
64
|
|
|
* @param array $arguments |
|
65
|
|
|
* |
|
66
|
|
|
* @return Promise |
|
67
|
|
|
*/ |
|
68
|
|
|
public function execute(callable $handler, array $arguments): Promise |
|
69
|
|
|
{ |
|
70
|
9 |
|
return Amp\call(function () use ($handler, $arguments) { |
|
|
|
|
|
|
71
|
9 |
|
$result = $this->executor->execute($handler, $arguments); |
|
72
|
|
|
|
|
73
|
8 |
|
if ($result instanceof \Generator) { |
|
74
|
4 |
|
return new Subroutine($result, $this->resolver); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
6 |
|
return $result; |
|
78
|
9 |
|
}); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|