Completed
Push — master ( 0e6afd...eefa71 )
by Christian
05:42 queued 04:09
created

ViewHandler::getStatusCode()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 4
nop 2
crap 6
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.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
namespace FOS\RestBundle\View;
13
14
use FOS\RestBundle\Context\Context;
15
use FOS\RestBundle\Serializer\Serializer;
16
use Symfony\Component\Form\FormInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\RequestStack;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
21
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
22
23
/**
24
 * View may be used in controllers to build up a response in a format agnostic way
25
 * The View class takes care of encoding your data in json, xml via the Serializer
26
 * component.
27
 *
28
 * @author Jordi Boggiano <[email protected]>
29
 * @author Lukas K. Smith <[email protected]>
30
 */
31
final class ViewHandler implements ConfigurableViewHandlerInterface
32
{
33
    /**
34
     * Key format, value a callable that returns a Response instance.
35
     *
36
     * @var array
37
     */
38
    private $customHandlers = [];
39
40
    /**
41
     * The supported formats as keys.
42
     *
43
     * @var array
44
     */
45
    private $formats;
46
    private $failedValidationCode;
47
    private $emptyContentCode;
48
    private $serializeNull;
49
    private $exclusionStrategyGroups = [];
50
    private $exclusionStrategyVersion;
51
    private $serializeNullStrategy;
52
    private $urlGenerator;
53
    private $serializer;
54
    private $requestStack;
55
    private $options;
56
57 54
    private function __construct(
58
        UrlGeneratorInterface $urlGenerator,
59
        Serializer $serializer,
60
        RequestStack $requestStack,
61
        array $formats = null,
62
        int $failedValidationCode = Response::HTTP_BAD_REQUEST,
63
        int $emptyContentCode = Response::HTTP_NO_CONTENT,
64
        bool $serializeNull = false,
65
        array $options = []
66
    ) {
67 54
        $this->urlGenerator = $urlGenerator;
68 54
        $this->serializer = $serializer;
69 54
        $this->requestStack = $requestStack;
70 54
        $this->formats = (array) $formats;
71 54
        $this->failedValidationCode = $failedValidationCode;
72 54
        $this->emptyContentCode = $emptyContentCode;
73 54
        $this->serializeNull = $serializeNull;
74 54
        $this->options = $options + [
75 54
            'exclusionStrategyGroups' => [],
76
            'exclusionStrategyVersion' => null,
77
            'serializeNullStrategy' => null,
78
            ];
79 54
        $this->reset();
80 54
    }
81
82 54
    public static function create(
83
        UrlGeneratorInterface $urlGenerator,
84
        Serializer $serializer,
85
        RequestStack $requestStack,
86
        array $formats = null,
87
        int $failedValidationCode = Response::HTTP_BAD_REQUEST,
88
        int $emptyContentCode = Response::HTTP_NO_CONTENT,
89
        bool $serializeNull = false,
90
        array $options = []
91
    ): self
92
    {
93 54
        return new self($urlGenerator, $serializer, $requestStack, $formats, $failedValidationCode, $emptyContentCode, $serializeNull, $options, false);
0 ignored issues
show
Unused Code introduced by
The call to ViewHandler::__construct() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
94
    }
95
96
    /**
97
     * @param string[]|string $groups
98
     */
99 1
    public function setExclusionStrategyGroups($groups): void
100
    {
101 1
        $this->exclusionStrategyGroups = (array) $groups;
102 1
    }
103
104 8
    public function setExclusionStrategyVersion(string $version): void
105
    {
106 8
        $this->exclusionStrategyVersion = $version;
107 8
    }
108
109 3
    public function setSerializeNullStrategy(bool $isEnabled): void
110
    {
111 3
        $this->serializeNullStrategy = $isEnabled;
112 3
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117 32
    public function supports(string $format): bool
118
    {
119 32
        return isset($this->customHandlers[$format]) || isset($this->formats[$format]);
120
    }
121
122
    /**
123
     * Registers a custom handler.
124
     *
125
     * The handler must have the following signature: handler(ViewHandler $viewHandler, View $view, Request $request, $format)
126
     * It can use the public methods of this class to retrieve the needed data and return a
127
     * Response object ready to be sent.
128
     */
129 15
    public function registerHandler(string $format, callable $callable): void
130
    {
131 15
        $this->customHandlers[$format] = $callable;
132 15
    }
133
134
    /**
135
     * Handles a request with the proper handler.
136
     *
137
     * Decides on which handler to use based on the request format.
138
     *
139
     * @throws UnsupportedMediaTypeHttpException
140
     */
141 28
    public function handle(View $view, Request $request = null): Response
142
    {
143 28
        if (null === $request) {
144 2
            $request = $this->requestStack->getCurrentRequest();
145
        }
146
147 28
        $format = $view->getFormat() ?: $request->getRequestFormat();
0 ignored issues
show
Bug introduced by
It seems like $request is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
148
149 28
        if (!$this->supports($format)) {
150 1
            $msg = "Format '$format' not supported, handler must be implemented";
151
152 1
            throw new UnsupportedMediaTypeHttpException($msg);
153
        }
154
155 27
        if (isset($this->customHandlers[$format])) {
156 10
            return call_user_func($this->customHandlers[$format], $this, $view, $request, $format);
157
        }
158
159 17
        return $this->createResponse($view, $request, $format);
0 ignored issues
show
Bug introduced by
It seems like $request can be null; however, createResponse() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
160
    }
161
162 4
    public function createRedirectResponse(View $view, string $location, string $format): Response
163
    {
164 4
        $content = null;
165 4
        if ((Response::HTTP_CREATED === $view->getStatusCode() || Response::HTTP_ACCEPTED === $view->getStatusCode()) && null !== $view->getData()) {
166 1
            $response = $this->initResponse($view, $format);
167
        } else {
168 3
            $response = $view->getResponse();
169
        }
170
171 4
        $code = $this->getStatusCode($view, $content);
172
173 4
        $response->setStatusCode($code);
174 4
        $response->headers->set('Location', $location);
175
176 4
        return $response;
177
    }
178
179 33
    public function createResponse(View $view, Request $request, string $format): Response
180
    {
181 33
        $route = $view->getRoute();
182
183 33
        $location = $route
184 2
            ? $this->urlGenerator->generate($route, (array) $view->getRouteParameters(), UrlGeneratorInterface::ABSOLUTE_URL)
185 33
            : $view->getLocation();
186
187 33
        if ($location) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $location of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
188 4
            return $this->createRedirectResponse($view, $location, $format);
189
        }
190
191 29
        $response = $this->initResponse($view, $format);
192
193 29
        if (!$response->headers->has('Content-Type')) {
194 29
            $mimeType = $request->attributes->get('media_type');
195 29
            if (null === $mimeType) {
196 22
                $mimeType = $request->getMimeType($format);
197
            }
198
199 29
            $response->headers->set('Content-Type', $mimeType);
200
        }
201
202 29
        return $response;
203
    }
204
205
    /**
206
     * Gets a response HTTP status code from a View instance.
207
     *
208
     * By default it will return 200. However if there is a FormInterface stored for
209
     * the key 'form' in the View's data it will return the failed_validation
210
     * configuration if the form instance has errors.
211
     *
212
     * @param string|false|null
213
     */
214 40
    private function getStatusCode(View $view, $content = null): int
215
    {
216 40
        $form = $this->getFormFromView($view);
217
218 40
        if (null !== $form && $form->isSubmitted() && !$form->isValid()) {
219 7
            return $this->failedValidationCode;
220
        }
221
222 33
        $statusCode = $view->getStatusCode();
223 33
        if (null !== $statusCode) {
224 7
            return $statusCode;
225
        }
226
227 26
        return null !== $content ? Response::HTTP_OK : $this->emptyContentCode;
228
    }
229
230 30
    private function getSerializationContext(View $view): Context
231
    {
232 30
        $context = $view->getContext();
233
234 30
        $groups = $context->getGroups();
235 30
        if (empty($groups) && $this->exclusionStrategyGroups) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->exclusionStrategyGroups 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...
236 1
            $context->setGroups($this->exclusionStrategyGroups);
237
        }
238
239 30
        if (null === $context->getVersion() && $this->exclusionStrategyVersion) {
240 8
            $context->setVersion($this->exclusionStrategyVersion);
241
        }
242
243 30
        if (null === $context->getSerializeNull() && null !== $this->serializeNullStrategy) {
244 14
            $context->setSerializeNull($this->serializeNullStrategy);
245
        }
246
247 30
        if (null !== $view->getStatusCode()) {
248 4
            $context->setAttribute('status_code', $view->getStatusCode());
249
        }
250
251 30
        return $context;
252
    }
253
254 30
    private function initResponse(View $view, string $format): Response
255
    {
256 30
        $content = null;
257 30
        if ($this->serializeNull || null !== $view->getData()) {
258 27
            $data = $this->getDataFromView($view);
259
260 27
            if ($data instanceof FormInterface && $data->isSubmitted() && !$data->isValid()) {
261 6
                $view->getContext()->setAttribute('status_code', $this->failedValidationCode);
262
            }
263
264 27
            $context = $this->getSerializationContext($view);
265
266 27
            $content = $this->serializer->serialize($data, $format, $context);
267
        }
268
269 30
        $response = $view->getResponse();
270 30
        $response->setStatusCode($this->getStatusCode($view, $content));
271
272 30
        if (null !== $content) {
273 22
            $response->setContent($content);
274
        }
275
276 30
        return $response;
277
    }
278
279 40
    private function getFormFromView(View $view): ?FormInterface
280
    {
281 40
        $data = $view->getData();
282
283 40
        if ($data instanceof FormInterface) {
284 6
            return $data;
285
        }
286
287 34
        if (is_array($data) && isset($data['form']) && $data['form'] instanceof FormInterface) {
288 4
            return $data['form'];
289
        }
290
291 30
        return null;
292
    }
293
294 27
    private function getDataFromView(View $view)
295
    {
296 27
        $form = $this->getFormFromView($view);
297
298 27
        if (null === $form) {
299 21
            return $view->getData();
300
        }
301
302 6
        return $form;
303
    }
304
305 54
    public function reset(): void
306
    {
307 54
        $this->exclusionStrategyGroups = $this->options['exclusionStrategyGroups'];
308 54
        $this->exclusionStrategyVersion = $this->options['exclusionStrategyVersion'];
309 54
        $this->serializeNullStrategy = $this->options['serializeNullStrategy'];
310 54
    }
311
}
312