ErrorHandler::handle()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 0 Features 5
Metric Value
c 9
b 0
f 5
dl 0
loc 20
rs 9.2
cc 4
eloc 13
nc 3
nop 5
1
<?php
2
3
namespace Vinelab\Api;
4
5
/*
6
 * @author Mahmoud Zalt <[email protected]>
7
 * @author Abed Halawi <[email protected]>
8
 */
9
10
use Exception;
11
use RuntimeException;
12
13
class ErrorHandler
14
{
15
    /**
16
     * @var Responder instance
17
     */
18
    protected $responder;
19
20
    /**
21
     * @param \Vinelab\Api\Responder $responder
22
     */
23
    public function __construct(Responder $responder)
24
    {
25
        $this->responder = $responder;
26
    }
27
28
    /**
29
     * @param       $exception
30
     * @param int   $code
31
     * @param int   $status
32
     * @param array $headers
33
     * @param int   $options
34
     *
35
     * @return \Illuminate\Http\JsonResponse|string
36
     *
37
     * @throws \Vinelab\Api\ApiException
38
     */
39
    public function handle($exception, $code = 0, $status = 500, $headers = [], $options = 0)
40
    {
41
        if (is_string($exception)) {
42
            $message = $exception;
43
        } // This is a generic, non-supported exception so we'll just treat it as so.
44
        elseif ($exception instanceof Exception || $exception instanceof RuntimeException) {
45
            $code = $exception->getCode();
46
            $message = $exception->getMessage();
47
        } // if not Exception or RuntimeException or a string then throw and API exception
48
        else {
49
            throw new ApiException('Argument 1 passed Vinelab\Api\ErrorHandler::handle() must be an instance of
50
                                    Exception or RuntimeException or a string, '.get_class($exception).' is given.');
51
        }
52
        $response = [
53
            'status' => $status,
54
            'error' => compact('message', 'code'),
55
        ];
56
57
        return $this->responder->respond($response, $status, $headers, $options);
58
    }
59
}
60