Completed
Pull Request — 2.x (#2288)
by Guilhem
17:20
created

RequestBodyParamConverter::configureContext()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 12
cts 12
cp 1
rs 9.1111
c 0
b 0
f 0
cc 6
nc 6
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\Request;
13
14
use FOS\RestBundle\Context\Context;
15
use FOS\RestBundle\Serializer\Serializer;
16
use JMS\Serializer\Exception\Exception as JMSSerializerException;
17
use JMS\Serializer\Exception\UnsupportedFormatException;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
19
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
22
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
23
use Symfony\Component\OptionsResolver\OptionsResolver;
24
use Symfony\Component\Serializer\Exception\ExceptionInterface as SymfonySerializerException;
25
use Symfony\Component\Validator\Validator\ValidatorInterface;
26
27
/**
28
 * @author Tyler Stroud <[email protected]>
29
 */
30
final class RequestBodyParamConverter implements ParamConverterInterface
31
{
32
    private $serializer;
33
    private $context = [];
34
    private $validator;
35
    private $validationErrorsArgument;
36
37
    /**
38
     * @param string[]|null $groups
39
     */
40 16
    public function __construct(
41
        Serializer $serializer,
42
        ?array $groups = null,
43
        ?string $version = null,
44
        ValidatorInterface $validator = null,
45
        ?string $validationErrorsArgument = null
46
    ) {
47 16
        $this->serializer = $serializer;
48
49 16
        if (!empty($groups)) {
50 1
            $this->context['groups'] = (array) $groups;
51
        }
52
53 16
        if (!empty($version)) {
54 1
            $this->context['version'] = $version;
55
        }
56
57 16
        if (null !== $validator && null === $validationErrorsArgument) {
58
            throw new \InvalidArgumentException('"$validationErrorsArgument" cannot be null when using the validator');
59
        }
60
61 16
        $this->validator = $validator;
62 16
        $this->validationErrorsArgument = $validationErrorsArgument;
63 16
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 10
    public function apply(Request $request, ParamConverter $configuration): bool
69
    {
70 10
        $options = (array) $configuration->getOptions();
71
72 10
        if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) {
73 1
            $arrayContext = array_merge($this->context, $options['deserializationContext']);
74
        } else {
75 9
            $arrayContext = $this->context;
76
        }
77 10
        $this->configureContext($context = new Context(), $arrayContext);
78
79 10
        $format = $request->getContentType();
80 10
        if (null === $format) {
81 1
            return $this->throwException(new UnsupportedMediaTypeHttpException(), $configuration);
82
        }
83
84
        try {
85 9
            $object = $this->serializer->deserialize(
86 9
                $request->getContent(),
0 ignored issues
show
Bug introduced by
It seems like $request->getContent() targeting Symfony\Component\HttpFo...n\Request::getContent() can also be of type resource; however, FOS\RestBundle\Serialize...rializer::deserialize() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
87 9
                $configuration->getClass(),
88
                $format,
89
                $context
90
            );
91 3
        } catch (UnsupportedFormatException $e) {
92
            return $this->throwException(new UnsupportedMediaTypeHttpException($e->getMessage(), $e), $configuration);
93 3
        } catch (JMSSerializerException $e) {
94 1
            return $this->throwException(new BadRequestHttpException($e->getMessage(), $e), $configuration);
95 2
        } catch (SymfonySerializerException $e) {
96 1
            return $this->throwException(new BadRequestHttpException($e->getMessage(), $e), $configuration);
97
        }
98
99 6
        $request->attributes->set($configuration->getName(), $object);
100
101 6
        if (null !== $this->validator && (!isset($options['validate']) || $options['validate'])) {
102 1
            $validatorOptions = $this->getValidatorOptions($options);
103
104 1
            $errors = $this->validator->validate($object, null, $validatorOptions['groups']);
105
106 1
            $request->attributes->set(
107 1
                $this->validationErrorsArgument,
108
                $errors
109
            );
110
        }
111
112 6
        return true;
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118 4
    public function supports(ParamConverter $configuration): bool
119
    {
120 4
        return null !== $configuration->getClass() && 'fos_rest.request_body' === $configuration->getConverter();
121
    }
122
123 11
    private function configureContext(Context $context, array $options): void
124
    {
125 11
        foreach ($options as $key => $value) {
126 2
            if ('groups' === $key) {
127 2
                $context->addGroups($options['groups']);
128 2
            } elseif ('version' === $key) {
129 2
                $context->setVersion($options['version']);
130 2
            } elseif ('enableMaxDepth' === $key) {
131 1
                $context->enableMaxDepth($options['enableMaxDepth']);
0 ignored issues
show
Unused Code introduced by
The call to Context::enableMaxDepth() has too many arguments starting with $options['enableMaxDepth'].

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...
132 2
            } elseif ('serializeNull' === $key) {
133 1
                $context->setSerializeNull($options['serializeNull']);
134
            } else {
135 2
                $context->setAttribute($key, $value);
136
            }
137
        }
138 11
    }
139
140 3
    private function throwException(\Exception $exception, ParamConverter $configuration): bool
141
    {
142 3
        if ($configuration->isOptional()) {
143
            return false;
144
        }
145
146 3
        throw $exception;
147
    }
148
149 2
    private function getValidatorOptions(array $options): array
150
    {
151 2
        $resolver = new OptionsResolver();
152 2
        $resolver->setDefaults([
153 2
            'groups' => null,
154
            'traverse' => false,
155
            'deep' => false,
156
        ]);
157
158 2
        return $resolver->resolve(isset($options['validator']) ? $options['validator'] : []);
159
    }
160
}
161