Completed
Push — master ( 003c1a...870291 )
by Tomáš
06:24
created

ControllerSerializerTrait::json()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 6
nc 2
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Symplify
7
 * Copyright (c) 2016 Tomas Votruba (http://tomasvotruba.cz).
8
 */
9
10
namespace Symplify\ControllerAutowire\Controller\Serializer;
11
12
use Symfony\Component\HttpFoundation\JsonResponse;
13
use Symfony\Component\Serializer\SerializerInterface;
14
15
trait ControllerSerializerTrait
16
{
17
    /**
18
     * @var SerializerInterface
19
     */
20
    private $serializer;
21
22
    public function setSerializer(SerializerInterface $serializer)
23
    {
24
        $this->serializer = $serializer;
25
    }
26
27
    /**
28
     * @param mixed $data
29
     * @param int   $status
30
     * @param array $headers
31
     * @param array $context
32
     */
33
    protected function json($data, int $status = 200, array $headers = [], array $context = []) : JsonResponse
34
    {
35
        if ($this->serializer) {
36
            $data = $this->serializer->serialize($data, 'json', array_merge([
37
                'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
38
            ], $context));
39
        }
40
41
        return new JsonResponse($data, $status, $headers, true);
42
    }
43
}
44