Error::run()   B
last analyzed

Complexity

Conditions 6
Paths 1

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.6897
c 0
b 0
f 0
cc 6
nc 1
nop 1
1
<?php
2
3
namespace Igorsgm\LaravelApiResponses\Macros;
4
5
use Igorsgm\LaravelApiResponses\ResponseMacroInterface;
6
use Illuminate\Http\JsonResponse;
7
use Illuminate\Http\Response as HttpResponse;
8
use Illuminate\Routing\ResponseFactory;
9
10
class Error implements ResponseMacroInterface
11
{
12
    /**
13
     * @param  ResponseFactory  $factory
14
     */
15
    public function run($factory)
16
    {
17
        $factory->macro('error',
18
            /**
19
             * Return a new error JSON response from the application.
20
             * Called like: response()->error(...)
21
             *
22
             * @param  array  $errors
23
             * @param  string  $message
24
             * @param  int  $status
25
             * @param  array  $headers
26
             * @param  array  $debugData
27
             * @return JsonResponse
28
             */
29
            function (
30
                $errors = [],
31
                $message = '',
32
                $status = HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
33
                array $headers = [],
34
                $debugData = []
35
            ) use ($factory) {
36
                $response = [
37
                    'success' => false,
38
                    'message' => !empty($message) ? $message : 'Server error',
39
                    'status' => !empty($status) ? $status : HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
40
                ];
41
42
                if (!empty($errors)) {
43
                    $response['errors'] = $errors;
44
                }
45
46
                if (!empty($debugData) && config('app.debug')) {
47
                    $response['debug'] = $debugData;
48
                }
49
50
                return $factory->json($response, $response['status'], $headers);
51
            });
52
    }
53
}
54