ApiTrait::renderJson()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 11
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 3
crap 2
1
<?php
2
3
namespace App\Controller\Traits;
4
5
use Psr\Http\Message\ResponseInterface;
6
7
/**
8
 * Utility trait for API controllers
9
 *
10
 * @author Ronan Chilvers <[email protected]>
11
 */
12
trait ApiTrait
13
{
14
    /**
15
     * Render an API response
16
     *
17
     * @param ResponseInterface $response
18
     * @param array $data
19
     * @return ResponseInterface
20
     * @author Ronan Chilvers <[email protected]>
21
     */
22
    protected function apiResponse(
23
        ResponseInterface $response,
24
        array $data
25
    ): ResponseInterface {
26
        return $this->renderJson(
27
            $response,
28
            'ok',
29
            $data
30
        );
31
    }
32
33
    /**
34
     * Render an API error response
35
     *
36
     * @param ResponseInterface $response
37
     * @param string $message
38
     * @param integer $code The HTTP response code to use
39
     * @return ResponseInterface
40
     * @author Ronan Chilvers <[email protected]>
41
     */
42
    protected function apiError(
43
        ResponseInterface $response,
44
        string $message,
45
        int $code = null
46
    ): ResponseInterface {
47
        if (is_null($code) || 0 == $code) {
48
            $code = 400;
49
        }
50
        $data = ['message' => $message];
51
        return $this->renderJson(
52
            $response,
53
            'error',
54
            $data
55
        )->withStatus($code);
56
    }
57
58
    /**
59
     * Render a json response
60
     *
61
     * @param ResponseInterface $response
62
     * @param array $data
63
     * @return ResponseInterface
64
     * @author Ronan Chilvers <[email protected]>
65
     */
66
    protected function renderJson(
67
        ResponseInterface $response,
68
        string $status,
69
        array $data
70
    ): ResponseInterface {
71
        $data = [
72
            'status' => $status,
73
            'data' => $data,
74
        ];
75
76
        return $response->withJson($data);
0 ignored issues
show
Bug introduced by
The method withJson() does not exist on Psr\Http\Message\ResponseInterface. It seems like you code against a sub-type of Psr\Http\Message\ResponseInterface such as Slim\Http\Response. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

76
        return $response->/** @scrutinizer ignore-call */ withJson($data);
Loading history...
77
    }
78
}
79