Completed
Pull Request — 2.x (#2227)
by
unknown
08:36
created

ViewHandler   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 281
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 98.59%

Importance

Changes 0
Metric Value
wmc 51
lcom 1
cbo 11
dl 0
loc 281
ccs 70
cts 71
cp 0.9859
rs 7.92
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 24 1
A create() 0 13 1
A setExclusionStrategyGroups() 0 4 1
A setExclusionStrategyVersion() 0 4 1
A setSerializeNullStrategy() 0 4 1
A supports() 0 4 2
A registerHandler() 0 4 1
A handle() 0 20 5
A createRedirectResponse() 0 16 4
A createResponse() 0 25 5
A getStatusCode() 0 15 6
B getSerializationContext() 0 23 8
B initResponse() 0 24 7
A getFormFromView() 0 14 5
A getDataFromView() 0 10 2
A reset() 0 6 1

How to fix   Complexity   

Complex Class

Complex classes like ViewHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ViewHandler, and based on these observations, apply Extract Interface, too.

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
    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
        $this->urlGenerator = $urlGenerator;
68
        $this->serializer = $serializer;
69
        $this->requestStack = $requestStack;
70
        $this->formats = (array) $formats;
71
        $this->failedValidationCode = $failedValidationCode;
72
        $this->emptyContentCode = $emptyContentCode;
73
        $this->serializeNull = $serializeNull;
74
        $this->options = $options + [
75
            'exclusionStrategyGroups' => [],
76
            'exclusionStrategyVersion' => null,
77
            'serializeNullStrategy' => null,
78
            ];
79
        $this->reset();
80
    }
81
82
    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
        return new self($urlGenerator, $serializer, $requestStack, $formats, $failedValidationCode, $emptyContentCode, $serializeNull, $options);
94
    }
95
96
    /**
97
     * @param string[]|string $groups
98
     */
99
    public function setExclusionStrategyGroups($groups): void
100
    {
101
        $this->exclusionStrategyGroups = (array) $groups;
102
    }
103
104
    public function setExclusionStrategyVersion(string $version): void
105
    {
106
        $this->exclusionStrategyVersion = $version;
107 87
    }
108
109
    public function setSerializeNullStrategy(bool $isEnabled): void
110
    {
111
        $this->serializeNullStrategy = $isEnabled;
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117
    public function supports(string $format): bool
118
    {
119
        return isset($this->customHandlers[$format]) || isset($this->formats[$format]);
120 87
    }
121 14
122
    /**
123
     * Registers a custom handler.
124 87
     *
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 87
     */
129 87
    public function registerHandler(string $format, callable $callable): void
130 87
    {
131 87
        $this->customHandlers[$format] = $callable;
132 87
    }
133 87
134 87
    /**
135 87
     * Handles a request with the proper handler.
136 87
     *
137 87
     * Decides on which handler to use based on the request format.
138 87
     *
139 87
     * @throws UnsupportedMediaTypeHttpException
140
     */
141
    public function handle(View $view, Request $request = null): Response
142
    {
143 87
        if (null === $request) {
144 87
            $request = $this->requestStack->getCurrentRequest();
145
        }
146 51
147
        $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
        if (!$this->supports($format)) {
150
            $msg = "Format '$format' not supported, handler must be implemented";
151
152
            throw new UnsupportedMediaTypeHttpException($msg);
153
        }
154
155
        if (isset($this->customHandlers[$format])) {
156
            return call_user_func($this->customHandlers[$format], $this, $view, $request, $format);
157 51
        }
158
159
        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
    public function createRedirectResponse(View $view, string $location, string $format): Response
163 1
    {
164
        $content = null;
165 1
        if ((Response::HTTP_CREATED === $view->getStatusCode() || Response::HTTP_ACCEPTED === $view->getStatusCode()) && null !== $view->getData()) {
166 1
            $response = $this->initResponse($view, $format);
167
        } else {
168
            $response = $view->getResponse();
169
        }
170
171 8
        $code = $this->getStatusCode($view, $content);
172
173 8
        $response->setStatusCode($code);
174 8
        $response->headers->set('Location', $location);
175
176
        return $response;
177
    }
178
179 3
    public function createResponse(View $view, Request $request, string $format): Response
180
    {
181 3
        $route = $view->getRoute();
182 3
183
        $location = $route
184
            ? $this->urlGenerator->generate($route, (array) $view->getRouteParameters(), UrlGeneratorInterface::ABSOLUTE_URL)
185
            : $view->getLocation();
186
187 49
        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
            return $this->createRedirectResponse($view, $location, $format);
189 49
        }
190
191
        $response = $this->initResponse($view, $format);
192
193
        if (!$response->headers->has('Content-Type')) {
194
            $mimeType = $request->attributes->get('media_type');
195
            if (null === $mimeType) {
196
                $mimeType = $request->getMimeType($format);
197
            }
198
199
            $response->headers->set('Content-Type', $mimeType);
200
        }
201
202
        return $response;
203
    }
204 16
205
    /**
206 16
     * Gets a response HTTP status code from a View instance.
207 1
     *
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 15
     * configuration if the form instance has errors.
211 15
     *
212
     * @param string|false|null
213
     */
214
    private function getStatusCode(View $view, $content = null): int
215
    {
216
        $form = $this->getFormFromView($view);
217
218
        if (null !== $form && $form->isSubmitted() && !$form->isValid()) {
219
            return $this->failedValidationCode;
220
        }
221
222
        $statusCode = $view->getStatusCode();
223
        if (null !== $statusCode) {
224 60
            return $statusCode;
225
        }
226 60
227
        return null !== $content ? Response::HTTP_OK : $this->emptyContentCode;
228 60
    }
229 7
230
    private function getSerializationContext(View $view): Context
231
    {
232 53
        $context = $view->getContext();
233 53
234 17
        $groups = $context->getGroups();
235
        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
            $context->setGroups($this->exclusionStrategyGroups);
237 36
        }
238
239
        if (null === $context->getVersion() && $this->exclusionStrategyVersion) {
240
            $context->setVersion($this->exclusionStrategyVersion);
241
        }
242
243
        if (null === $context->getSerializeNull() && null !== $this->serializeNullStrategy) {
244
            $context->setSerializeNull($this->serializeNullStrategy);
245
        }
246
247 51
        if (null !== $view->getStatusCode()) {
248
            $context->setAttribute('status_code', $view->getStatusCode());
249 51
        }
250 1
251
        return $context;
252
    }
253 51
254
    private function initResponse(View $view, string $format): Response
255
    {
256
        $content = null;
257
        if ($this->serializeNull || null !== $view->getData()) {
258
            $data = $this->getDataFromView($view);
259 37
260
            if ($data instanceof FormInterface && $data->isSubmitted() && !$data->isValid()) {
261 37
                $view->getContext()->setAttribute('status_code', $this->failedValidationCode);
262
            }
263 37
264 37
            $context = $this->getSerializationContext($view);
265 1
266
            $content = $this->serializer->serialize($data, $format, $context);
267
        }
268 37
269 8
        $response = $view->getResponse();
270
        $response->setStatusCode($this->getStatusCode($view, $content));
271
272 37
        if (null !== $content) {
273 21
            $response->setContent($content);
274
        }
275
276 37
        return $response;
277 11
    }
278
279
    private function getFormFromView(View $view): ?FormInterface
280 37
    {
281
        $data = $view->getData();
282
283
        if ($data instanceof FormInterface) {
284
            return $data;
285
        }
286
287
        if (is_array($data) && isset($data['form']) && $data['form'] instanceof FormInterface) {
288
            return $data['form'];
289
        }
290
291
        return null;
292 45
    }
293
294 45
    private function getDataFromView(View $view)
295 10
    {
296
        $form = $this->getFormFromView($view);
297
298 45
        if (null === $form) {
299
            return $view->getData();
300 45
        }
301 1
302
        return $form;
303 1
    }
304
305
    public function reset(): void
306 44
    {
307 10
        $this->exclusionStrategyGroups = $this->options['exclusionStrategyGroups'];
308
        $this->exclusionStrategyVersion = $this->options['exclusionStrategyVersion'];
309
        $this->serializeNullStrategy = $this->options['serializeNullStrategy'];
310 34
    }
311
}
312