Completed
Push — master ( 8e0f41...aafb5f )
by Christian
08:40 queued 10s
created

ViewHandler::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 3
cts 3
cp 1
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 8
crap 1

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\RedirectResponse;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\RequestStack;
20
use Symfony\Component\HttpFoundation\Response;
21
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
22
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
23
use Symfony\Component\Templating\EngineInterface;
24
use Symfony\Component\Templating\TemplateReferenceInterface;
25
use Twig\Environment;
26
27
/**
28
 * View may be used in controllers to build up a response in a format agnostic way
29
 * The View class takes care of encoding your data in json, xml, or renders a
30
 * template for html via the Serializer component.
31
 *
32
 * @author Jordi Boggiano <[email protected]>
33
 * @author Lukas K. Smith <[email protected]>
34
 */
35
class ViewHandler implements ConfigurableViewHandlerInterface
36
{
37
    /**
38
     * Key format, value a callable that returns a Response instance.
39
     *
40
     * @var array
41
     */
42
    protected $customHandlers = [];
43
44
    /**
45
     * The supported formats as keys and if the given formats
46
     * uses templating is denoted by a true value.
47
     *
48
     * @var array
49
     */
50
    protected $formats;
51
52
    /**
53
     *  HTTP response status code for a failed validation.
54
     *
55
     * @var int
56
     */
57
    protected $failedValidationCode;
58
59
    /**
60
     * HTTP response status code when the view data is null.
61
     *
62
     * @var int
63
     */
64
    protected $emptyContentCode;
65
66
    /**
67
     * Whether or not to serialize null view data.
68
     *
69
     * @var bool
70
     */
71
    protected $serializeNull;
72
73
    /**
74
     * If to force a redirect for the given key format,
75
     * with value being the status code to use.
76
     *
77
     * @var array
78
     */
79
    protected $forceRedirects;
80
81
    /**
82
     * @var string
83
     */
84
    protected $defaultEngine;
85
86
    /**
87
     * @var array
88
     */
89
    protected $exclusionStrategyGroups = [];
90
91
    /**
92
     * @var string
93
     */
94
    protected $exclusionStrategyVersion;
95
96
    /**
97
     * @var bool
98
     */
99
    protected $serializeNullStrategy;
100
101
    private $urlGenerator;
102
    private $serializer;
103
    private $templating;
104
    private $requestStack;
105
106
    private $options;
107
108
    /**
109
     * Constructor.
110
     *
111
     * @param UrlGeneratorInterface       $urlGenerator         The URL generator
112
     * @param Serializer                  $serializer
113
     * @param EngineInterface|Environment $templating           The configured templating engine
114
     * @param RequestStack                $requestStack         The request stack
115
     * @param array                       $formats              the supported formats as keys and if the given formats uses templating is denoted by a true value
116
     * @param int                         $failedValidationCode The HTTP response status code for a failed validation
117
     * @param int                         $emptyContentCode     HTTP response status code when the view data is null
118
     * @param bool                        $serializeNull        Whether or not to serialize null view data
119 81
     * @param array                       $forceRedirects       If to force a redirect for the given key format, with value being the status code to use
120
     * @param string                      $defaultEngine        default engine (twig, php ..)
121
     * @param array                       $options              config options
122
     */
123
    public function __construct(
124
        UrlGeneratorInterface $urlGenerator,
125
        Serializer $serializer,
126
        $templating,
127
        RequestStack $requestStack,
128
        array $formats = null,
129
        $failedValidationCode = Response::HTTP_BAD_REQUEST,
130
        $emptyContentCode = Response::HTTP_NO_CONTENT,
131 81
        $serializeNull = false,
132 81
        array $forceRedirects = null,
133 81
        $defaultEngine = 'twig',
134 81
        array $options = []
135 81
    ) {
136 81
        if (11 >= func_num_args() || func_get_arg(11)) {
137 81
            @trigger_error(sprintf('The constructor of the %s class is deprecated, use the static create() factory method instead.', __CLASS__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
138 81
        }
139 81
140 81
        if (null !== $templating && !$templating instanceof EngineInterface && !$templating instanceof Environment) {
141 81
            throw new \TypeError(sprintf('If provided, the templating engine must be an instance of %s or %s, but %s was given.', EngineInterface::class, Environment::class, get_class($templating)));
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('If provided, th...get_class($templating)).

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...
142
        }
143
144
        $this->urlGenerator = $urlGenerator;
145
        $this->serializer = $serializer;
146
        $this->templating = $templating;
147
        $this->requestStack = $requestStack;
148 1
        $this->formats = (array) $formats;
149
        $this->failedValidationCode = $failedValidationCode;
150 1
        $this->emptyContentCode = $emptyContentCode;
151 1
        $this->serializeNull = $serializeNull;
152
        $this->forceRedirects = (array) $forceRedirects;
153
        $this->defaultEngine = $defaultEngine;
154
        $this->options = $options + [
155
            'exclusionStrategyGroups' => [],
156
            'exclusionStrategyVersion' => null,
157
            'serializeNullStrategy' => null,
158 7
            ];
159
        $this->reset();
160 7
    }
161 7
162
    public static function create(
163
        UrlGeneratorInterface $urlGenerator,
164
        Serializer $serializer,
165
        RequestStack $requestStack,
166
        array $formats = null,
167
        int $failedValidationCode = Response::HTTP_BAD_REQUEST,
168 25
        int $emptyContentCode = Response::HTTP_NO_CONTENT,
169
        bool $serializeNull = false,
170 25
        array $options = []
171 25
    ): self
172
    {
173
        return new self($urlGenerator, $serializer, null, $requestStack, $formats, $failedValidationCode, $emptyContentCode, $serializeNull, [], 'twig', $options, false);
174
    }
175
176 44
    /**
177
     * Sets the default serialization groups.
178 44
     *
179
     * @param array|string $groups
180
     */
181
    public function setExclusionStrategyGroups($groups)
182
    {
183
        $this->exclusionStrategyGroups = (array) $groups;
184
    }
185
186
    /**
187
     * Sets the default serialization version.
188
     *
189
     * @param string $version
190
     */
191
    public function setExclusionStrategyVersion($version)
192
    {
193 16
        $this->exclusionStrategyVersion = $version;
194
    }
195 16
196 1
    /**
197
     * If nulls should be serialized.
198
     *
199 15
     * @param bool $isEnabled
200 15
     */
201
    public function setSerializeNullStrategy($isEnabled)
202
    {
203
        $this->serializeNullStrategy = $isEnabled;
204
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209
    public function supports($format)
210
    {
211
        return isset($this->customHandlers[$format]) || isset($this->formats[$format]);
212
    }
213
214 55
    /**
215
     * Registers a custom handler.
216 55
     *
217
     * The handler must have the following signature: handler(ViewHandler $viewHandler, View $view, Request $request, $format)
218 55
     * It can use the public methods of this class to retrieve the needed data and return a
219 7
     * Response object ready to be sent.
220
     *
221
     * @param string   $format
222 48
     * @param callable $callable
223 48
     *
224 15
     * @throws \InvalidArgumentException
225
     */
226
    public function registerHandler($format, $callable)
227 33
    {
228
        if (!is_callable($callable)) {
229
            throw new \InvalidArgumentException('Registered view callback must be callable.');
230
        }
231
232
        $this->customHandlers[$format] = $callable;
233
    }
234
235
    /**
236
     * Gets a response HTTP status code from a View instance.
237 46
     *
238
     * By default it will return 200. However if there is a FormInterface stored for
239 46
     * the key 'form' in the View's data it will return the failed_validation
240
     * configuration if the form instance has errors.
241
     *
242
     * @param View  $view
243
     * @param mixed $content
244
     *
245
     * @return int HTTP status code
246
     */
247
    protected function getStatusCode(View $view, $content = null)
248
    {
249
        $form = $this->getFormFromView($view);
250 31
251
        if ($form && $form->isSubmitted() && !$form->isValid()) {
252 31
            return $this->failedValidationCode;
253
        }
254 31
255 31
        $statusCode = $view->getStatusCode();
256 1
        if (null !== $statusCode) {
257 1
            return $statusCode;
258
        }
259 31
260 5
        return null !== $content ? Response::HTTP_OK : $this->emptyContentCode;
261 5
    }
262
263 31
    /**
264 18
     * If the given format uses the templating system for rendering.
265 18
     *
266
     * @deprecated since 2.8
267 31
     *
268
     * @param string $format
269
     *
270
     * @return bool
271
     */
272 View Code Duplication
    public function isFormatTemplating($format)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
273
    {
274
        if (1 === func_num_args() || func_get_arg(1)) {
275
            @trigger_error(sprintf('The %s() method is deprecated since FOSRestBundle 2.8.', __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
276
        }
277
278
        return !empty($this->formats[$format]);
279
    }
280
281
    /**
282 40
     * Gets or creates a JMS\Serializer\SerializationContext and initializes it with
283
     * the view exclusion strategies, groups & versions if a new context is created.
284 40
     *
285 12
     * @param View $view
286 12
     *
287
     * @return Context
288 40
     */
289
    protected function getSerializationContext(View $view)
290 40
    {
291 1
        $context = $view->getContext();
292 1
293
        $groups = $context->getGroups();
294
        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...
295 39
            $context->setGroups($this->exclusionStrategyGroups);
296 10
        }
297
298
        if (null === $context->getVersion() && $this->exclusionStrategyVersion) {
299 29
            $context->setVersion($this->exclusionStrategyVersion);
300
        }
301
302
        if (null === $context->getSerializeNull() && null !== $this->serializeNullStrategy) {
303
            $context->setSerializeNull($this->serializeNullStrategy);
304
        }
305
306
        if (null !== $view->getStatusCode()) {
307
            $context->setAttribute('status_code', $view->getStatusCode());
308
        }
309
310
        return $context;
311 8
    }
312
313 8
    /**
314 8
     * Handles a request with the proper handler.
315 1
     *
316 1
     * Decides on which handler to use based on the request format.
317 7
     *
318 7
     * @param View    $view
319 2
     * @param Request $request
320 2
     *
321 2
     * @throws UnsupportedMediaTypeHttpException
322 2
     *
323
     * @return Response
324
     */
325 8
    public function handle(View $view, Request $request = null)
326 8
    {
327
        if (null === $request) {
328 8
            $request = $this->requestStack->getCurrentRequest();
329 8
        }
330
331 8
        $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...
332
333
        if (!$this->supports($format)) {
334
            $msg = "Format '$format' not supported, handler must be implemented";
335
336
            throw new UnsupportedMediaTypeHttpException($msg);
337
        }
338
339
        if (isset($this->customHandlers[$format])) {
340
            return call_user_func($this->customHandlers[$format], $this, $view, $request, $format);
341
        }
342 15
343
        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...
344 15
    }
345
346 15
    /**
347 15
     * Creates the Response from the view.
348 2
     *
349
     * @param View   $view
350
     * @param string $location
351
     * @param string $format
352 2
     *
353
     * @return Response
354
     */
355
    public function createRedirectResponse(View $view, $location, $format)
356 2
    {
357
        $content = null;
358 15
        if ((Response::HTTP_CREATED === $view->getStatusCode() || Response::HTTP_ACCEPTED === $view->getStatusCode()) && null !== $view->getData()) {
359
            $response = $this->initResponse($view, $format);
360
        } else {
361
            $response = $view->getResponse();
362
            if ('html' === $format && isset($this->forceRedirects[$format])) {
363
                $redirect = new RedirectResponse($location);
364
                $content = $redirect->getContent();
365
                $response->setContent($content);
366
            }
367
        }
368 22
369
        $code = isset($this->forceRedirects[$format])
370 22
            ? $this->forceRedirects[$format] : $this->getStatusCode($view, $content);
371
372 22
        $response->setStatusCode($code);
373 2
        $response->headers->set('Location', $location);
374 22
375 12
        return $response;
376 12
    }
377
378 22
    /**
379 2
     * Renders the view data with the given template.
380 2
     *
381
     * @deprecated since 2.8
382 22
     *
383 22
     * @param View   $view
384 2
     * @param string $format
385 2
     *
386
     * @return string
387 22
     */
388
    public function renderTemplate(View $view, $format)
389
    {
390
        if (2 === func_num_args() || func_get_arg(2)) {
391
            @trigger_error(sprintf('The %s() method is deprecated since FOSRestBundle 2.8.', __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
392
        }
393
394
        if (null === $this->templating) {
395
            throw new \LogicException(sprintf('An instance of %s or %s must be injected in %s to render templates.', EngineInterface::class, Environment::class, __CLASS__));
396
        }
397
398
        $data = $this->prepareTemplateParameters($view, false);
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View...areTemplateParameters() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
399 51
400
        $template = $view->getTemplate(false);
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View::getTemplate() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
401 51
        if ($template instanceof TemplateReferenceInterface) {
402
            if (null === $template->get('format')) {
403
                $template->set('format', $format);
404 51
            }
405 51
406
            if (null === $template->get('engine')) {
407 51
                $engine = $view->getEngine() ?: $this->defaultEngine;
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View::getEngine() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
408 8
                $template->set('engine', $engine);
409
            }
410
        }
411 43
412
        return $this->templating->render($template, $data);
0 ignored issues
show
Bug introduced by
It seems like $template defined by $view->getTemplate(false) on line 400 can also be of type null; however, Symfony\Component\Templa...gineInterface::render() does only seem to accept string|object<Symfony\Co...lateReferenceInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $template defined by $view->getTemplate(false) on line 400 can also be of type null; however, Twig\Environment::render() does only seem to accept string|object<Twig\TemplateWrapper>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
413 43
    }
414 43
415 43
    /**
416
     * Prepares view data for use by templating engine.
417 43
     *
418
     * @deprecated since 2.8
419
     *
420
     * @param View $view
421
     *
422
     * @return array
423
     */
424
    public function prepareTemplateParameters(View $view)
425
    {
426
        if (1 === func_num_args() || func_get_arg(1)) {
427
            @trigger_error(sprintf('The %s() method is deprecated since FOSRestBundle 2.8.', __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
428 44
        }
429
430 44
        $data = $view->getData();
431 44
432 15
        if ($data instanceof FormInterface) {
433 44
            $data = [$view->getTemplateVar(false) => $data->getData(), 'form' => $data];
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View::getTemplateVar() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
434 28
        } elseif (empty($data) || !is_array($data) || is_numeric((key($data)))) {
435
            $data = [$view->getTemplateVar(false) => $data];
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View::getTemplateVar() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
436 28
        }
437 6
438 6
        if (isset($data['form']) && $data['form'] instanceof FormInterface) {
439
            $data['form'] = $data['form']->createView();
440 28
        }
441 28
442
        $templateData = $view->getTemplateData(false);
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View::getTemplateData() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
443 28
        if (is_callable($templateData)) {
444 28
            $templateData = call_user_func($templateData, $this, $view);
445
        }
446 44
447 44
        return array_merge($data, $templateData);
448
    }
449 44
450 39
    /**
451 39
     * Handles creation of a Response using either redirection or the templating/serializer service.
452
     *
453 44
     * @param View    $view
454
     * @param Request $request
455
     * @param string  $format
456
     *
457
     * @return Response
458
     */
459
    public function createResponse(View $view, Request $request, $format)
460
    {
461
        $route = $view->getRoute();
462
463 55
        $location = $route
464
            ? $this->urlGenerator->generate($route, (array) $view->getRouteParameters(), UrlGeneratorInterface::ABSOLUTE_URL)
465 55
            : $view->getLocation();
466
467 55
        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...
468 7
            return $this->createRedirectResponse($view, $location, $format);
469
        }
470
471 48
        $response = $this->initResponse($view, $format);
472 4
473
        if (!$response->headers->has('Content-Type')) {
474
            $mimeType = $request->attributes->get('media_type');
475 44
            if (null === $mimeType) {
476
                $mimeType = $request->getMimeType($format);
477
            }
478
479
            $response->headers->set('Content-Type', $mimeType);
480
        }
481
482
        return $response;
483
    }
484
485 28
    /**
486
     * Initializes a response object that represents the view and holds the view's status code.
487 28
     *
488
     * @param View   $view
489 28
     * @param string $format
490 22
     *
491
     * @return Response
492
     */
493 6
    private function initResponse(View $view, $format)
494
    {
495
        $content = null;
496
        if ($this->isFormatTemplating($format, false)) {
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View...r::isFormatTemplating() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
497
            $content = $this->renderTemplate($view, $format, false);
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\ViewHandler::renderTemplate() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
498
        } elseif ($this->serializeNull || null !== $view->getData()) {
499
            $data = $this->getDataFromView($view);
500
501
            if ($data instanceof FormInterface && $data->isSubmitted() && !$data->isValid()) {
502
                $view->getContext()->setAttribute('status_code', $this->failedValidationCode);
503
            }
504
505
            $context = $this->getSerializationContext($view);
506
            $context->setAttribute('template_data', $view->getTemplateData(false));
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\View\View::getTemplateData() has been deprecated with message: since 2.8

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
507
508
            $content = $this->serializer->serialize($data, $format, $context);
509
        }
510
511
        $response = $view->getResponse();
512
        $response->setStatusCode($this->getStatusCode($view, $content));
513
514
        if (null !== $content) {
515
            $response->setContent($content);
516
        }
517
518
        return $response;
519
    }
520
521
    /**
522
     * Returns the form from the given view if present, false otherwise.
523
     *
524
     * @param View $view
525
     *
526
     * @return bool|FormInterface
527
     */
528
    protected function getFormFromView(View $view)
529
    {
530
        $data = $view->getData();
531
532
        if ($data instanceof FormInterface) {
533
            return $data;
534
        }
535
536
        if (is_array($data) && isset($data['form']) && $data['form'] instanceof FormInterface) {
537
            return $data['form'];
538
        }
539
540
        return false;
541
    }
542
543
    /**
544
     * Returns the data from a view.
545
     *
546
     * @param View $view
547
     *
548
     * @return mixed|null
549
     */
550
    private function getDataFromView(View $view)
551
    {
552
        $form = $this->getFormFromView($view);
553
554
        if (false === $form) {
555
            return $view->getData();
556
        }
557
558
        return $form;
559
    }
560
561
    /**
562
     * Resets internal object state at the end of the request.
563
     */
564
    public function reset()
565
    {
566
        $this->exclusionStrategyGroups = $this->options['exclusionStrategyGroups'];
567
        $this->exclusionStrategyVersion = $this->options['exclusionStrategyVersion'];
568
        $this->serializeNullStrategy = $this->options['serializeNullStrategy'];
569
    }
570
}
571