-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiddleware.php
More file actions
64 lines (57 loc) · 1.28 KB
/
Middleware.php
File metadata and controls
64 lines (57 loc) · 1.28 KB
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
<?php
namespace alvin\phpmvc;
/**
* Class for registering middlewares
*/
class Middleware {
/**
* The first middleware to execute
* @var callable
*/
public $start;
/**
* Array of middlewares for constructing the start function
*/
public array $middlewares;
/**
* Creates middleware instance and sets initial value of start.
*/
public function __construct() {
$this->middlewares = [];
$this->start = function () {};
}
/**
* Add a middleware
*
* Pushes a middleware to the middleware array
* @param \alvin\phpmvc\Middleware $middleware Middleware instance to add
* @return void
*/
public function add($middleware) {
$this->middlewares[] = $middleware;
}
/**
* Sets reference to first middleware to execute.
*
* Loops over the middleware array and sets each middlewares arguments including next()
*
* @return void
*/
public function setStart() {
for ($i = sizeof($this->middlewares) - 1; $i >= 0; $i--) {
$next = $this->start;
$this->start = function () use ($i, $next) {
return $this->middlewares[$i](Application::$app->request, Application::$app->response, $next);
};
}
}
/**
* Calls the first middleware.
*
* @return void
*/
public function resolve() {
$this->setStart();
return call_user_func($this->start);
}
}