• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 7142557150

08 Dec 2023 02:28PM UTC coverage: 36.003% (-1.4%) from 37.36%
7142557150

push

github

web-flow
fix(jsonld): remove link to ApiDocumentation when doc is disabled (#6029)

0 of 1 new or added line in 1 file covered. (0.0%)

2297 existing lines in 182 files now uncovered.

9992 of 27753 relevant lines covered (36.0%)

147.09 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

54.72
/src/Symfony/EventListener/SerializeListener.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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\Symfony\EventListener;
15

16
use ApiPlatform\Doctrine\Odm\State\Options as ODMOptions;
17
use ApiPlatform\Doctrine\Orm\State\Options;
18
use ApiPlatform\Exception\RuntimeException;
19
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
20
use ApiPlatform\Serializer\ResourceList;
21
use ApiPlatform\Serializer\SerializerContextBuilderInterface;
22
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
23
use ApiPlatform\Symfony\Util\RequestAttributesExtractor;
24
use ApiPlatform\Util\ErrorFormatGuesser;
25
use ApiPlatform\Validator\Exception\ValidationException;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpFoundation\Response;
28
use Symfony\Component\HttpKernel\Event\ViewEvent;
29
use Symfony\Component\Serializer\Encoder\EncoderInterface;
30
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
31
use Symfony\Component\Serializer\SerializerInterface;
32
use Symfony\Component\WebLink\GenericLinkProvider;
33
use Symfony\Component\WebLink\Link;
34

35
/**
36
 * Serializes data.
37
 *
38
 * @author Kévin Dunglas <dunglas@gmail.com>
39
 */
40
final class SerializeListener
41
{
42
    use OperationRequestInitiatorTrait;
43

44
    public const OPERATION_ATTRIBUTE_KEY = 'serialize';
45

46
    public function __construct(
47
        private readonly SerializerInterface $serializer,
48
        private readonly SerializerContextBuilderInterface $serializerContextBuilder,
49
        ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null,
50
        private readonly array $errorFormats = [],
51
        // @phpstan-ignore-next-line we don't need this anymore
52
        private readonly bool $debug = false,
53
    ) {
54
        $this->resourceMetadataCollectionFactory = $resourceMetadataFactory;
18✔
55
    }
56

57
    /**
58
     * Serializes the data to the requested format.
59
     */
60
    public function onKernelView(ViewEvent $event): void
61
    {
62
        $controllerResult = $event->getControllerResult();
18✔
63
        $request = $event->getRequest();
18✔
64

65
        if ($controllerResult instanceof Response) {
18✔
66
            return;
×
67
        }
68

69
        $attributes = RequestAttributesExtractor::extractAttributes($request);
18✔
70

71
        if (!($attributes['respond'] ?? $request->attributes->getBoolean('_api_respond', false))) {
18✔
72
            return;
3✔
73
        }
74

75
        $operation = $this->initializeOperation($request);
15✔
76

77
        if ('api_platform.symfony.main_controller' === $operation?->getController() || $request->attributes->get('_api_platform_disable_listeners')) {
15✔
78
            return;
×
79
        }
80

81
        if (!($operation?->canSerialize() ?? true)) {
15✔
UNCOV
82
            return;
×
83
        }
84

85
        if (!$attributes) {
15✔
UNCOV
86
            $this->serializeRawData($event, $request, $controllerResult);
×
87

UNCOV
88
            return;
×
89
        }
90

91
        $context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
15✔
92
        if (isset($context['output']) && \array_key_exists('class', $context['output']) && null === $context['output']['class']) {
15✔
UNCOV
93
            $event->setControllerResult(null);
×
94

UNCOV
95
            return;
×
96
        }
97

98
        if ($controllerResult instanceof ValidationException) {
15✔
99
            $format = ErrorFormatGuesser::guessErrorFormat($request, $this->errorFormats);
×
100
            $previousOperation = $request->attributes->get('_api_previous_operation');
×
101
            if (!($previousOperation?->getExtraProperties()['rfc_7807_compliant_errors'] ?? false)) {
×
102
                $context['groups'] = ['legacy_'.$format['key']];
×
103
                $context['force_iri_generation'] = false;
×
104
            }
105
        }
106

107
        if ($included = $request->attributes->get('_api_included')) {
15✔
108
            $context['api_included'] = $included;
×
109
        }
110
        $resources = new ResourceList();
15✔
111
        $context['resources'] = &$resources;
15✔
112
        $context[AbstractObjectNormalizer::EXCLUDE_FROM_CACHE_KEY][] = 'resources';
15✔
113

114
        $resourcesToPush = new ResourceList();
15✔
115
        $context['resources_to_push'] = &$resourcesToPush;
15✔
116
        $context[AbstractObjectNormalizer::EXCLUDE_FROM_CACHE_KEY][] = 'resources_to_push';
15✔
117
        if (($options = $operation?->getStateOptions()) && (
15✔
118
            ($options instanceof Options && $options->getEntityClass())
15✔
119
            || ($options instanceof ODMOptions && $options->getDocumentClass())
15✔
120
        )) {
121
            $context['force_resource_class'] = $operation->getClass();
×
122
        }
123

124
        $request->attributes->set('_api_normalization_context', $context);
15✔
125
        $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));
15✔
126

127
        $request->attributes->set('_resources', $request->attributes->get('_resources', []) + (array) $resources);
15✔
128
        if (!\count($resourcesToPush)) {
15✔
129
            return;
15✔
130
        }
131

132
        $linkProvider = $request->attributes->get('_api_platform_links', new GenericLinkProvider());
×
133
        foreach ($resourcesToPush as $resourceToPush) {
×
134
            $linkProvider = $linkProvider->withLink((new Link('preload', $resourceToPush))->withAttribute('as', 'fetch'));
×
135
        }
136
        $request->attributes->set('_api_platform_links', $linkProvider);
×
137
    }
138

139
    /**
140
     * Tries to serialize data that are not API resources (e.g. the entrypoint or data returned by a custom controller).
141
     *
142
     * @throws RuntimeException
143
     */
144
    private function serializeRawData(ViewEvent $event, Request $request, $controllerResult): void
145
    {
UNCOV
146
        if (\is_object($controllerResult)) {
×
147
            $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $request->attributes->get('_api_normalization_context', [])));
×
148

149
            return;
×
150
        }
151

UNCOV
152
        if (!$this->serializer instanceof EncoderInterface) {
×
153
            throw new RuntimeException(sprintf('The serializer must implement the "%s" interface.', EncoderInterface::class));
×
154
        }
155

UNCOV
156
        $event->setControllerResult($this->serializer->encode($controllerResult, $request->getRequestFormat()));
×
157
    }
158
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc