-
Notifications
You must be signed in to change notification settings - Fork 0
/
Runner.php
78 lines (70 loc) · 1.87 KB
/
Runner.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Altair\Middleware;
use Altair\Middleware\Contracts\MiddlewareInterface;
use Altair\Middleware\Contracts\MiddlewareResolverInterface;
use Altair\Middleware\Contracts\MiddlewareRunnerInterface;
use Altair\Middleware\Contracts\PayloadInterface;
use Altair\Structure\Queue;
class Runner implements MiddlewareRunnerInterface
{
/**
* The middleware queue.
*
* @var Queue
*/
protected $queue;
/**
*
* A callable to convert queue entries to callables.
*
* @var callable|MiddlewareResolverInterface
*
*/
protected $resolver;
/**
*
* Constructor.
*
* @param Queue $queue The middleware queue.
*
* @param callable|MiddlewareResolverInterface $resolver Converts queue entries to callables.
*
*/
public function __construct(Queue $queue, callable $resolver = null)
{
$this->queue = $queue;
$this->resolver = $resolver;
}
/**
* Calls the next entry in the queue.
*
* @param PayloadInterface $payload
*
* @return PayloadInterface
*/
public function __invoke(PayloadInterface $payload): PayloadInterface
{
$entry = !$this->queue->isEmpty() ? $this->queue->pop() : null;
$middleware = $this->resolve($entry);
return $middleware($payload, $this);
}
/**
* Converts a queue entry to a callable, using the resolver if present.
*
* @param mixed|callable|MiddlewareInterface $entry the queue entry.
*
* @return callable|MiddlewareInterface
*/
protected function resolve($entry)
{
if (!$entry) {
return function (PayloadInterface $payload, callable $next) {
return $payload;
};
}
if (!$this->resolver) {
return $entry;
}
return call_user_func($this->resolver, $entry);
}
}