ErrorHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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