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

ControllerSerializerTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 1
dl 0
loc 29
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setSerializer() 0 4 1
A json() 0 10 2
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