Repository navigation
Expand file tree
/
Copy pathExceptionHandler.php
More file actions
98 lines (83 loc) · 1.87 KB
/
Copy pathExceptionHandler.php
File metadata and controls
98 lines (83 loc) · 1.87 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
95
96
97
98
<?php namespace Dingo\Api;
use Closure;
use ReflectionFunction;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionHandler {
/**
* Array of exception handlers.
*
* @var array
*/
protected $handlers = [];
/**
* Register a new exception handler.
*
* @param \Closure $callback
* @return void
*/
public function register(Closure $callback)
{
$hint = $this->handlerHint($callback);
$this->handlers[$hint] = $callback;
}
/**
* Handle an exception if it has an existing handler.
*
* @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception
* @return \Illuminate\Http\Response
*/
public function handle(HttpExceptionInterface $exception)
{
foreach ($this->handlers as $hint => $handler)
{
if ($exception instanceof $hint)
{
$response = call_user_func($handler, $exception);
if ( ! $response instanceof Response)
{
$response = new Response($response, $exception->getStatusCode());
}
return $response;
}
}
}
/**
* Determine if the handler will handle the given exception.
*
* @param \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception
* @return bool
*/
public function willHandle(HttpExceptionInterface $exception)
{
foreach ($this->handlers as $hint => $handler)
{
if ($exception instanceof $hint)
{
return true;
}
}
return false;
}
/**
* Get the hint for an exception handler.
*
* @param \Closure $callback
* @return string
*/
protected function handlerHint(Closure $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;
}
}