ApiResponseTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 13
c 1
b 0
f 0
dl 0
loc 30
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A errorResponse() 0 11 3
A successResponse() 0 7 1
1
<?php
2
3
namespace CSlant\Blog\Api\Traits;
4
5
use Illuminate\Http\JsonResponse;
6
7
trait ApiResponseTrait
8
{
9
    /**
10
     * Build a success response.
11
     */
12
    public function successResponse(mixed $data = [], ?string $message = 'Success', ?int $code = 200): JsonResponse
13
    {
14
        return response()->json([
15
            'status' => 'success',
16
            'message' => $message,
17
            $data,
18
        ], $code);
19
    }
20
21
    /**
22
     * Build an error response.
23
     *
24
     * @param  array<string, mixed>  $data
25
     */
26
    public function errorResponse(string $message, int|string|null $code, ?array $data = []): JsonResponse
27
    {
28
        if (is_null($code) || (int) $code < 100) {
29
            $code = 400;
30
        }
31
32
        return response()->json([
33
            'status' => 'error',
34
            'message' => $message,
35
            'data' => $data,
36
        ], (int) $code);
37
    }
38
}
39