-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathDispatch.php
79 lines (72 loc) · 2.11 KB
/
Dispatch.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
79
<?php
namespace Phly\Conduit;
use Exception;
/**
* Dispatch middleware
*
* This class is an implementation detail of Next.
*
* @internal
*/
class Dispatch
{
/**
* Dispatch middleware
*
* Given a route (which contains the handler for given middleware),
* the $err value passed to $next, $next, and the request and response
* objects, dispatch a middleware handler.
*
* If $err is non-falsy, and the current handler has an arity of 4,
* it will be dispatched.
*
* If $err is falsy, and the current handler has an arity of < 4,
* it will be dispatched.
*
* In all other cases, the handler will be ignored, and $next will be
* invoked with the current $err value.
*
* If an exception is raised when executing the handler, the exception
* will be assigned as the value of $err, and $next will be invoked
* with it.
*
* @param Route $route
* @param mixed $err
* @param Http\Request $request
* @param Http\Response $response
* @param callable $next
*/
public function __invoke(
Route $route,
$err,
Http\Request $request,
Http\Response $response,
callable $next
) {
$handler = $route->handler;
$hasError = (null !== $err);
switch (true) {
case ($handler instanceof ErrorMiddlewareInterface):
$arity = 4;
break;
case ($handler instanceof MiddlewareInterface):
$arity = 3;
break;
default:
$arity = Utils::getArity($handler);
break;
}
// @todo Trigger event with Route, original URL from request?
try {
if ($hasError && $arity === 4) {
return call_user_func($handler, $err, $request, $response, $next);
}
if (! $hasError && $arity < 4) {
return call_user_func($handler, $request, $response, $next);
}
} catch (Exception $e) {
$err = $e;
}
return $next($request, $response, $err);
}
}