Passed
Push — master ( 82fd68...df3c7c )
by Melech
10:31 queued 10s
created

ApiController   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 42
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getApi() 0 3 1
A createApiJsonResponse() 0 13 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Valkyrja\Routing\Support;
15
16
use Valkyrja\Api\Api;
17
use Valkyrja\Api\Constants\Status;
18
use Valkyrja\Http\Constants\StatusCode;
19
use Valkyrja\Http\JsonResponse;
20
21
/**
22
 * Abstract Class ApiController.
23
 *
24
 * @author Melech Mizrachi
25
 */
26
abstract class ApiController extends Controller
27
{
28
    /**
29
     * The Api service.
30
     *
31
     * @var Api
32
     */
33
    private static Api $api;
34
35
    /**
36
     * Get the Api service.
37
     *
38
     * @return Api
39
     */
40
    protected static function getApi(): Api
41
    {
42
        return self::$api ?? self::$api = self::$container->getSingleton(Api::class);
43
    }
44
45
    /**
46
     * Create an Api JsonResponse.
47
     *
48
     * @param array       $data       The json data
49
     * @param string|null $message    [optional] The message
50
     * @param string|null $status     [optional] The json status
51
     * @param int|null    $statusCode [optional] The status code
52
     *
53
     * @return JsonResponse
54
     */
55
    protected static function createApiJsonResponse(
56
        array $data,
57
        string $message = null,
58
        string $status = null,
59
        int $statusCode = null
60
    ): JsonResponse {
61
        $json = self::getApi()->jsonFromArray($data);
62
63
        $json->setMessage($message);
64
        $json->setStatus($status ?? Status::SUCCESS);
65
        $json->setStatusCode($statusCode ?? StatusCode::OK);
66
67
        return self::$responseFactory->createJsonResponse($json->__toArray(), $statusCode);
68
    }
69
}
70