AbstractRestController   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B renderJsonApi() 0 38 5
1
<?php
2
3
/*
4
 * This file is part of JsonApiBundle the package.
5
 *
6
 * (c) Alexey Astafev <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace RonteLtd\JsonApiBundle\Controller;
13
14
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
15
use Symfony\Component\HttpFoundation\Response;
16
use RonteLtd\JsonApiBundle\Annotation\Links;
17
use RonteLtd\JsonApiBundle\Annotation\Meta;
18
use RonteLtd\JsonApiBundle\Serializer\Normalizer\Collection;
19
20
/**
21
 * AbstractRestController
22
 *
23
 * @author Alexey Astafev <[email protected]>
24
 */
25
abstract class AbstractRestController extends Controller
26
{
27
    /**
28
     * Render jsonapi from array or object
29
     * 
30
     * @param mixed $data
31
     * @return Response
32
     */
33
    protected function renderJsonApi($data)
34
    {
35
        if (!$data instanceof Collection) {
36
            $collection = new Collection($data);
37
38
            $refectionMethod = new \ReflectionMethod(static::class, debug_backtrace()[1]['function']);
39
40
            // Get links and meta
41
            $reader = $this->get('annotation_reader');
42
            $linksAnnotation = $reader->getMethodAnnotation($refectionMethod, "RonteLtd\JsonApiBundle\Annotation\Links");
43
            $metaAnnotation = $reader->getMethodAnnotation($refectionMethod, "RonteLtd\JsonApiBundle\Annotation\Meta");
44
45
            // Get JsonApi version
46
            $jsonapi = $this->container->getParameter('ronte_ltd_json_api.jsonapi');
47
            if (null !== $jsonapi) {
48
                $collection->setJsonapi($jsonapi);
49
            }
50
51
            // Get and set links
52
            $links = ($linksAnnotation instanceof Links) ? $linksAnnotation->getLinks() : [];
53
            $links['self'] = $this->get('request_stack')->getCurrentRequest()->getUri();
54
            $collection->setLinks($links);
55
56
            // Get and set JsonApi meta
57
            if ($metaAnnotation instanceof Meta) {
58
                $collection->setMeta($metaAnnotation->getMeta());
59
            }
60
        } else {
61
            $collection = &$data;
62
        }
63
64
        $jsonApi = $this->get('serializer')->serialize($collection, 'json');
65
66
        $response = new Response($jsonApi);
67
        $response->headers->set('Content-Type', 'application/vnd.api+json');
68
69
        return $response;
70
    }
71
}