Repository navigation
Expand file tree
/
Copy pathHandler.php
More file actions
94 lines (80 loc) · 2.13 KB
/
Copy pathHandler.php
File metadata and controls
94 lines (80 loc) · 2.13 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace Dingo\Api\Exception;
use Exception;
use ReflectionFunction;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class Handler
{
/**
* Array of exception handlers.
*
* @var array
*/
protected $handlers = [];
/**
* Register a new exception handler.
*
* @param callable $callback
* @return void
*/
public function register(callable $callback)
{
$hint = $this->handlerHint($callback);
$this->handlers[$hint] = $callback;
}
/**
* Handle an exception if it has an existing handler.
*
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function handle(Exception $exception)
{
foreach ($this->handlers as $hint => $handler) {
if (! $exception instanceof $hint) {
continue;
}
$response = $handler($exception);
if (! is_null($response)) {
if (! $response instanceof Response) {
$response = new Response($response, $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 200);
}
return $response;
}
}
}
/**
* Determine if the handler will handle the given exception.
*
* @param \Exception $exception
* @return bool
*/
public function willHandle(Exception $exception)
{
return (bool) array_first($this->handlers, function ($hint) use ($exception) {
return $exception instanceof $hint;
}, false);
}
/**
* Get the hint for an exception handler.
*
* @param callable $callback
* @return string
*/
protected function handlerHint(callable $callback)
{
$reflection = new ReflectionFunction($callback);
$exception = $reflection->getParameters()[0];
return $exception->getClass()->getName();
}
/**
* Get the exception handlers.
*
* @return array
*/
public function getHandlers()
{
return $this->handlers;
}
}