ExceptionAttributeBuilder   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 35
c 1
b 0
f 0
dl 0
loc 72
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B build() 0 44 7
1
<?php
2
3
namespace ArinaSystems\JsonResponse\Builders;
4
5
use ArinaSystems\JsonResponse\Facades\JsonResponse;
6
use Illuminate\Auth\AuthenticationException;
7
use Illuminate\Validation\ValidationException;
8
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
9
use Throwable;
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 ?? new \stdClass,
75
            'debug'     => $exception->getTrace(),
76
        ]);
77
78
        if (method_exists($this, $handle = 'handleAny')) {
79
            $this->{$handle}($exception);
80
        }
81
82
        return $exceptionName;
83
    }
84
}
85