Success::run()   B
last analyzed

Complexity

Conditions 8
Paths 1

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 8.0515
c 0
b 0
f 0
cc 8
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\Resources\Json\JsonResource;
8
use Illuminate\Http\Resources\Json\ResourceCollection;
9
use Illuminate\Http\Response as HttpResponse;
10
use Illuminate\Pagination\LengthAwarePaginator;
11
use Illuminate\Routing\ResponseFactory;
12
13
class Success implements ResponseMacroInterface
14
{
15
    /**
16
     * @param  ResponseFactory  $factory
17
     */
18
    public function run($factory)
19
    {
20
        $factory->macro('success',
21
            /**
22
             * Return a new success JSON response from the application.
23
             * Called like: response()->success(...)
24
             *
25
             * @param  array  $data
26
             * @param  string  $message
27
             * @param  int  $status
28
             * @param  array  $headers
29
             * @return JsonResponse
30
             */
31
            function ($data = [], $message = '', $status = HttpResponse::HTTP_OK, array $headers = []) use ($factory) {
32
                if ($data instanceof LengthAwarePaginator) {
33
                    $data = $data->toArray();
34
                }
35
36
                if ($data instanceof ResourceCollection || $data instanceof JsonResource) {
37
                    $resourceResponse = $data->response();
38
                    $data = (array) $resourceResponse->getData();
39
                    $status = $resourceResponse->getStatusCode();
40
                    $headers = array_merge($headers, $resourceResponse->headers->all());
41
                }
42
43
                $response = [
44
                    'success' => true,
45
                    'message' => !empty($message) ? $message : 'Data retrieved successfully.',
46
                    'status' => !empty($status) ? (int) $status : HttpResponse::HTTP_OK,
47
                    'data' => $data,
48
                ];
49
50
                if (is_array($data) && isset($data['data'])) {
51
                    unset($response['data']);
52
                    $response = array_merge($response, $data);
53
                }
54
                return $factory->json($response, $response['status'], $headers);
55
            });
56
    }
57
}
58