Passed
Push — master ( 8bd912...d93388 )
by Alan
06:58 queued 02:20
created

src/EventListener/SerializeListener.php (3 issues)

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\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
18
use ApiPlatform\Core\Metadata\Resource\ToggleableOperationAttributeTrait;
19
use ApiPlatform\Core\Serializer\ResourceList;
20
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
21
use ApiPlatform\Core\Util\RequestAttributesExtractor;
22
use Fig\Link\GenericLinkProvider;
23
use Fig\Link\Link;
24
use Symfony\Component\HttpFoundation\Request;
25
use Symfony\Component\HttpFoundation\Response;
26
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
27
use Symfony\Component\Serializer\Encoder\EncoderInterface;
28
use Symfony\Component\Serializer\SerializerInterface;
29
30
/**
31
 * Serializes data.
32
 *
33
 * @author Kévin Dunglas <[email protected]>
34
 */
35
final class SerializeListener
36
{
37
    use ToggleableOperationAttributeTrait;
38
39
    public const OPERATION_ATTRIBUTE_KEY = 'serialize';
40
41
    private $serializer;
42
    private $serializerContextBuilder;
43
44
    public function __construct(SerializerInterface $serializer, SerializerContextBuilderInterface $serializerContextBuilder, ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
45
    {
46
        $this->serializer = $serializer;
47
        $this->serializerContextBuilder = $serializerContextBuilder;
48
        $this->resourceMetadataFactory = $resourceMetadataFactory;
49
    }
50
51
    /**
52
     * Serializes the data to the requested format.
53
     */
54
    public function onKernelView(GetResponseForControllerResultEvent $event): void
55
    {
56
        $controllerResult = $event->getControllerResult();
57
        $request = $event->getRequest();
58
59
        if (
60
            $controllerResult instanceof Response
61
            || !(($attributes = RequestAttributesExtractor::extractAttributes($request))['respond'] ?? $request->attributes->getBoolean('_api_respond', false))
62
            || $attributes && $this->isOperationAttributeDisabled($attributes, self::OPERATION_ATTRIBUTE_KEY)
0 ignored issues
show
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...
63
        ) {
64
            return;
65
        }
66
67
        if (!$attributes) {
0 ignored issues
show
$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...
68
            $this->serializeRawData($event, $request, $controllerResult);
69
70
            return;
71
        }
72
73
        $context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
74
75
        if (isset($context['output']) && \array_key_exists('class', $context['output']) && null === $context['output']['class']) {
76
            $event->setControllerResult(null);
77
78
            return;
79
        }
80
81
        if ($included = $request->attributes->get('_api_included')) {
82
            $context['api_included'] = $included;
83
        }
84
        $resources = new ResourceList();
85
        $context['resources'] = &$resources;
86
87
        $resourcesToPush = new ResourceList();
88
        $context['resources_to_push'] = &$resourcesToPush;
89
90
        $request->attributes->set('_api_normalization_context', $context);
91
92
        $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));
93
94
        $request->attributes->set('_resources', $request->attributes->get('_resources', []) + (array) $resources);
95
        if (!\count($resourcesToPush)) {
96
            return;
97
        }
98
99
        $linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
100
        foreach ($resourcesToPush as $resourceToPush) {
101
            $linkProvider = $linkProvider->withLink(new Link('preload', $resourceToPush));
102
        }
103
        $request->attributes->set('_links', $linkProvider);
104
    }
105
106
    /**
107
     * Tries to serialize data that are not API resources (e.g. the entrypoint or data returned by a custom controller).
108
     *
109
     * @param object $controllerResult
110
     *
111
     * @throws RuntimeException
112
     */
113
    private function serializeRawData(GetResponseForControllerResultEvent $event, Request $request, $controllerResult): void
114
    {
115
        if (\is_object($controllerResult)) {
116
            $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $request->attributes->get('_api_normalization_context', [])));
117
118
            return;
119
        }
120
121
        if (!$this->serializer instanceof EncoderInterface) {
122
            throw new RuntimeException(sprintf('The serializer must implement the "%s" interface.', EncoderInterface::class));
123
        }
124
125
        $event->setControllerResult($this->serializer->encode($controllerResult, $request->getRequestFormat()));
126
    }
127
}
128