Completed
Push — master ( d0bde7...345612 )
by Antoine
26s queued 11s
created

SerializeListener::onKernelView()   C

Complexity

Conditions 14
Paths 9

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 30
nc 9
nop 1
dl 0
loc 53
rs 6.2666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\EventListener;
15
16
use ApiPlatform\Core\Exception\RuntimeException;
17
use ApiPlatform\Core\Serializer\ResourceList;
18
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
19
use ApiPlatform\Core\Util\RequestAttributesExtractor;
20
use Fig\Link\GenericLinkProvider;
21
use Fig\Link\Link;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
25
use Symfony\Component\Serializer\Encoder\EncoderInterface;
26
use Symfony\Component\Serializer\SerializerInterface;
27
28
/**
29
 * Serializes data.
30
 *
31
 * @author Kévin Dunglas <[email protected]>
32
 */
33
final class SerializeListener
34
{
35
    private $serializer;
36
    private $serializerContextBuilder;
37
38
    public function __construct(SerializerInterface $serializer, SerializerContextBuilderInterface $serializerContextBuilder)
39
    {
40
        $this->serializer = $serializer;
41
        $this->serializerContextBuilder = $serializerContextBuilder;
42
    }
43
44
    /**
45
     * Serializes the data to the requested format.
46
     */
47
    public function onKernelView(GetResponseForControllerResultEvent $event): void
48
    {
49
        $controllerResult = $event->getControllerResult();
50
        $request = $event->getRequest();
51
52
        if ($controllerResult instanceof Response || !(($attributes = RequestAttributesExtractor::extractAttributes($request))['respond'] ?? $request->attributes->getBoolean('_api_respond', false))) {
53
            return;
54
        }
55
56
        if (!$attributes) {
0 ignored issues
show
introduced by
$attributes is an empty array, thus ! $attributes is always true.
Loading history...
Bug Best Practice introduced by
The expression $attributes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
57
            $this->serializeRawData($event, $request, $controllerResult);
58
59
            return;
60
        }
61
62
        $context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
63
64
        if (
65
            (isset($context['output']) && \array_key_exists('class', $context['output']) && null === $context['output']['class'])
66
            ||
67
            (
68
                null === $controllerResult && isset($context['input']) && \array_key_exists('class', $context['input']) &&
69
                null === $context['input']['class']
70
            )
71
        ) {
72
            $event->setControllerResult('');
73
74
            return;
75
        }
76
77
        if ($included = $request->attributes->get('_api_included')) {
78
            $context['api_included'] = $included;
79
        }
80
        $resources = new ResourceList();
81
        $context['resources'] = &$resources;
82
83
        $resourcesToPush = new ResourceList();
84
        $context['resources_to_push'] = &$resourcesToPush;
85
86
        $request->attributes->set('_api_normalization_context', $context);
87
88
        $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));
89
90
        $request->attributes->set('_resources', $request->attributes->get('_resources', []) + (array) $resources);
91
        if (!\count($resourcesToPush)) {
92
            return;
93
        }
94
95
        $linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
96
        foreach ($resourcesToPush as $resourceToPush) {
97
            $linkProvider = $linkProvider->withLink(new Link('preload', $resourceToPush));
98
        }
99
        $request->attributes->set('_links', $linkProvider);
100
    }
101
102
    /**
103
     * Tries to serialize data that are not API resources (e.g. the entrypoint or data returned by a custom controller).
104
     *
105
     * @param object $controllerResult
106
     *
107
     * @throws RuntimeException
108
     */
109
    private function serializeRawData(GetResponseForControllerResultEvent $event, Request $request, $controllerResult): void
110
    {
111
        if (\is_object($controllerResult)) {
112
            $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $request->attributes->get('_api_normalization_context', [])));
113
114
            return;
115
        }
116
117
        if (!$this->serializer instanceof EncoderInterface) {
118
            throw new RuntimeException(sprintf('The serializer instance must implements the "%s" interface.', EncoderInterface::class));
119
        }
120
121
        $event->setControllerResult($this->serializer->encode($controllerResult, $request->getRequestFormat()));
122
    }
123
}
124