Passed
Push — master ( e757bc...0b485a )
by Koen
04:17
created

ResponseFactory::json()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
c 1
b 0
f 1
nc 2
nop 4
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Http\Responses;
6
7
use App\Contracts\Http\Responses\ResponseFactory as ResponseFactoryContract;
8
use Illuminate\Http\JsonResponse;
9
use Illuminate\Http\Response;
10
use Illuminate\Pagination\LengthAwarePaginator;
11
12
final class ResponseFactory implements ResponseFactoryContract
13
{
14
    /**
15
     * @inheritDoc
16
     */
17
    public function make($content = '', $status = Response::HTTP_OK, array $headers = []): Response
18
    {
19
        return new Response($content, $status, $headers);
20
    }
21
22
    /**
23
     * @inheritDoc
24
     */
25
    public function noContent($status = Response::HTTP_NO_CONTENT, array $headers = []): Response
26
    {
27
        return $this->make('', $status, $headers);
28
    }
29
30
    /**
31
     * @inheritDoc
32
     */
33
    public function json($data = [], $status = Response::HTTP_OK, array $headers = [], $options = 0): JsonResponse
34
    {
35
        if (! array_key_exists('data', $data)) {
36
            $data = ['data' => $data];
37
        }
38
39
        return new JsonResponse($data, $status, $headers, $options);
40
    }
41
42
    /**
43
     * @inheritDoc
44
     */
45
    public function paginator(
46
        LengthAwarePaginator $paginator,
47
        int $status = Response::HTTP_OK,
48
        array $headers = [],
49
        int $options = 0
50
    ): JsonResponse {
51
        return $this->json([
52
            'data' => $paginator->items(),
53
            'meta' => [
54
                'current_page' => $paginator->currentPage(),
55
                'last_page'    => $paginator->lastPage(),
56
                'from'         => $paginator->firstItem(),
57
                'to'           => $paginator->lastItem(),
58
                'total'        => $paginator->total(),
59
                'per_page'     => $paginator->perPage(),
60
            ],
61
        ]);
62
    }
63
64
    /**
65
     * @inheritDoc
66
     */
67
    public function mappedPaginator(
68
        LengthAwarePaginator $paginator,
69
        callable $map,
70
        int $status = Response::HTTP_OK,
71
        array $headers = [],
72
        int $options = 0
73
    ): JsonResponse {
74
        $paginator->setCollection($paginator->getCollection()->map($map));
75
76
        return $this->paginator($paginator, $status, $headers, $options);
77
    }
78
}
79