Passed
Push — master ( 9013bb...125cf1 )
by Kirill
03:56
created

JsonTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A writeJson() 0 13 4
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Http\Traits;
13
14
use JsonSerializable;
15
use Psr\Http\Message\ResponseInterface;
16
17
/**
18
 * Provides ability to write json payloads into responses.
19
 */
20
trait JsonTrait
21
{
22
    /**
23
     * Generate JSON response.
24
     *
25
     * @param ResponseInterface $response
26
     * @param mixed             $payload
27
     * @param int               $code
28
     * @return ResponseInterface
29
     */
30
    private function writeJson(ResponseInterface $response, $payload, int $code = 200): ResponseInterface
31
    {
32
        if ($payload instanceof JsonSerializable) {
33
            $payload = $payload->jsonSerialize();
34
        }
35
36
        if (is_array($payload) && isset($payload['status'])) {
37
            $code = $payload['status'];
38
        }
39
40
        $response->getBody()->write(json_encode($payload));
41
42
        return $response->withStatus($code)->withHeader('Content-Type', 'application/json');
43
    }
44
}
45