JsonFormatter::format()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 2
b 0
f 0
nc 2
nop 2
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 2
rs 10
1
<?php
2
/**
3
 * Copyright (c) 2020.
4
 * @author Paweł Antosiak <[email protected]>
5
 */
6
7
declare(strict_types=1);
8
9
namespace Gorynych\Http\Formatter;
10
11
use Symfony\Component\HttpFoundation\JsonResponse;
12
use Symfony\Component\HttpFoundation\Response;
13
14
/**
15
 * JSON response formatter according to JSON:API Latest Specification (v1.0)
16
 *
17
 * @see https://jsonapi.org/format/#document-top-level
18
 */
19
class JsonFormatter implements FormatterInterface
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24 3
    public function format($content, int $statusCode): Response
25
    {
26 3
        $response = new JsonResponse(null, $statusCode);
27
28 3
        if (true === in_array($statusCode, range(400, 599), true)) {
29 2
            $response->headers->set('Content-Type', 'application/problem+json');
30 2
            $response->setData(['errors' => [$content]]);
31
        } else {
32 1
            $response->setData(['data' => $content]);
33
        }
34
35 3
        return $response;
36
    }
37
}
38