Completed
Branch dev (20d83f)
by Arina
01:20
created

ExceptionAttributeBuilder::build()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 8.6417
c 0
b 0
f 0
cc 6
nc 9
nop 1
1
<?php
2
3
namespace ArinaSystems\JsonResponse\Builders;
4
5
use Throwable;
6
use Illuminate\Auth\AuthenticationException;
7
use Illuminate\Validation\ValidationException;
8
use ArinaSystems\JsonResponse\Facades\JsonResponse;
9
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
10
11
class ExceptionAttributeBuilder extends Builder
12
{
13
    /**
14
     * @var int
15
     */
16
    protected $http_code;
17
18
    /**
19
     * @var int
20
     */
21
    protected $code;
22
23
    /**
24
     * @var \Illuminate\Contracts\Translation\Translator|string|array|null
25
     */
26
    protected $message;
27
28
    /**
29
     * @var array
30
     */
31
    protected $errors;
32
33
    /**
34
     * Build a value of the exception attribute.
35
     *
36
     * @param  \Throwable $exception
37
     * @return mixed
38
     */
39
    public function build($exception)
40
    {
41
        if (!is_a($exception, Throwable::class)) {
42
            return $exception;
43
        }
44
45
        $exceptionName = class_basename(get_class($exception));
46
47
        $this->message = $exception->getMessage();
48
49
        if ($exception instanceof AuthenticationException) {
50
            $this->http_code = 401;
51
            $this->code = 401;
52
            $this->message = __('Unauthenticated.');
53
        } elseif ($exception instanceof ValidationException) {
54
            $this->http_code = $exception->status;
55
            $this->code = $exception->status;
56
            $errors = $exception->errors();
57
        } elseif ($exception instanceof HttpExceptionInterface) {
58
            $this->http_code = $exception->getStatusCode();
59
            $this->code = $exception->getStatusCode();
60
        } else {
61
            $this->http_code = 500;
62
            $this->code = 500;
63
        }
64
65
        if (method_exists($this, $handle = 'handle' . $exceptionName)) {
66
            $this->{$handle}($exception);
67
        }
68
69
        JsonResponse::setAttributes([
70
            'success'   => false,
71
            'http_code' => $this->http_code,
72
            'code'      => $this->code,
73
            'message'   => $this->message,
74
            'errors'    => $errors ?? [],
75
            'debug'     => $exception->getTrace(),
76
        ]);
77
78
        return $exceptionName;
79
    }
80
}
81