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\Processor; |
14
|
|
|
|
15
|
|
|
use Amp\Coroutine; |
16
|
|
|
use PHPinnacle\Ensign\Token; |
17
|
|
|
use PHPinnacle\Ensign\Processor; |
18
|
|
|
|
19
|
|
|
final class SimpleProcessor extends Processor |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* {@inheritdoc} |
23
|
|
|
*/ |
24
|
|
|
protected function process(callable $handler, array $arguments, Token $token): callable |
25
|
|
|
{ |
26
|
8 |
|
return function () use ($handler, $arguments, $token) { |
27
|
8 |
|
return $this->adapt($handler(...$arguments), $token); |
28
|
8 |
|
}; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param mixed $value |
33
|
|
|
* @param Token $token |
34
|
|
|
* |
35
|
|
|
* @return mixed |
36
|
|
|
*/ |
37
|
7 |
|
private function adapt($value, Token $token) |
38
|
|
|
{ |
39
|
7 |
|
return $value instanceof \Generator ? new Coroutine($this->recoil($value, $token)) : $value; |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param \Generator $generator |
44
|
|
|
* @param Token $token |
45
|
|
|
* |
46
|
|
|
* @return mixed |
47
|
|
|
*/ |
48
|
3 |
|
private function recoil(\Generator $generator, Token $token) |
49
|
|
|
{ |
50
|
3 |
|
while ($generator->valid()) { |
51
|
3 |
|
$token->guard(); |
52
|
|
|
|
53
|
|
|
try { |
54
|
3 |
|
$value = $this->intercept($generator->key(), $generator->current()); |
55
|
|
|
|
56
|
3 |
|
$generator->send(yield $this->adapt($value, $token)); |
57
|
2 |
|
} catch (\Exception $error) { |
58
|
|
|
/** @scrutinizer ignore-call */ |
59
|
1 |
|
$generator->throw($error); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
return $this->adapt($generator->getReturn(), $token); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param int|string $key |
68
|
|
|
* @param mixed $value |
69
|
|
|
* |
70
|
|
|
* @return mixed |
71
|
|
|
*/ |
72
|
3 |
|
private function intercept($key, $value) |
73
|
|
|
{ |
74
|
3 |
|
$interrupt = \is_string($key) ? $key : $value; |
75
|
|
|
|
76
|
3 |
|
if (\is_object($interrupt)) { |
77
|
2 |
|
$interrupt = \get_class($interrupt); |
78
|
|
|
} |
79
|
|
|
|
80
|
3 |
|
if (!\is_string($interrupt) || !isset($this->interruptions[$interrupt])) { |
81
|
2 |
|
return $value; |
82
|
|
|
} |
83
|
|
|
|
84
|
1 |
|
$interceptor = $this->interruptions[$interrupt]; |
85
|
|
|
|
86
|
1 |
|
$value = \is_array($value) ? $value : [$value]; |
87
|
|
|
|
88
|
1 |
|
return $interceptor(...$value); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|