Completed
Pull Request — 2.x (#2251)
by Christian
03:49
created

RequestBodyParamConverter   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 137
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 95.16%

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 12
dl 0
loc 137
ccs 59
cts 62
cp 0.9516
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 24 5
A supports() 0 4 2
B configureContext() 0 19 7
A throwException() 0 8 2
A getValidatorOptions() 0 11 2
B apply() 0 46 10
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 since 2.8
31
 */
32
class RequestBodyParamConverter implements ParamConverterInterface
33
{
34
    private $serializer;
35
    private $context = [];
36
    private $validator;
37
    private $validationErrorsArgument;
38
39
    /**
40
     * @param string[]|null $groups  An array of groups to be used in the serialization context
41
     * @param string|null   $version A version string to be used in the serialization context
42
     *
43
     * @throws \InvalidArgumentException
44
     */
45 19
    public function __construct(
46
        Serializer $serializer,
47
        ?array $groups = null,
48
        ?string $version = null,
49
        ValidatorInterface $validator = null,
50
        ?string $validationErrorsArgument = null
51
    ) {
52 19
        $this->serializer = $serializer;
53
54 19
        if (!empty($groups)) {
55 1
            $this->context['groups'] = (array) $groups;
56
        }
57
58 19
        if (!empty($version)) {
59 1
            $this->context['version'] = $version;
60
        }
61
62 19
        if (null !== $validator && null === $validationErrorsArgument) {
63
            throw new \InvalidArgumentException('"$validationErrorsArgument" cannot be null when using the validator');
64
        }
65
66 19
        $this->validator = $validator;
67 19
        $this->validationErrorsArgument = $validationErrorsArgument;
68 19
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73 10
    public function apply(Request $request, ParamConverter $configuration)
74
    {
75 10
        $options = (array) $configuration->getOptions();
76
77 10
        if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) {
78 1
            $arrayContext = array_merge($this->context, $options['deserializationContext']);
79
        } else {
80 9
            $arrayContext = $this->context;
81
        }
82 10
        $this->configureContext($context = new Context(), $arrayContext);
83
84 10
        $format = $request->getContentType();
85 10
        if (null === $format) {
86 1
            return $this->throwException(new UnsupportedMediaTypeHttpException(), $configuration);
87
        }
88
89
        try {
90 9
            $object = $this->serializer->deserialize(
91 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...
92 9
                $configuration->getClass(),
93
                $format,
94
                $context
95
            );
96 3
        } catch (UnsupportedFormatException $e) {
97
            return $this->throwException(new UnsupportedMediaTypeHttpException($e->getMessage(), $e), $configuration);
98 3
        } catch (JMSSerializerException $e) {
99 1
            return $this->throwException(new BadRequestHttpException($e->getMessage(), $e), $configuration);
100 2
        } catch (SymfonySerializerException $e) {
101 1
            return $this->throwException(new BadRequestHttpException($e->getMessage(), $e), $configuration);
102
        }
103
104 6
        $request->attributes->set($configuration->getName(), $object);
105
106 6
        if (null !== $this->validator && (!isset($options['validate']) || $options['validate'])) {
107 1
            $validatorOptions = $this->getValidatorOptions($options);
108
109 1
            $errors = $this->validator->validate($object, null, $validatorOptions['groups']);
110
111 1
            $request->attributes->set(
112 1
                $this->validationErrorsArgument,
113
                $errors
114
            );
115
        }
116
117 6
        return true;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 5
    public function supports(ParamConverter $configuration)
124
    {
125 5
        return null !== $configuration->getClass() && 'fos_rest.request_body' === $configuration->getConverter();
126
    }
127
128 12
    protected function configureContext(Context $context, array $options)
129
    {
130 12
        foreach ($options as $key => $value) {
131 3
            if ('groups' === $key) {
132 2
                $context->addGroups($options['groups']);
133 3
            } elseif ('version' === $key) {
134 2
                $context->setVersion($options['version']);
135 3
            } elseif ('maxDepth' === $key) {
136 1
                @trigger_error('Context attribute "maxDepth" is deprecated since version 2.1 and will be removed in 3.0. Use "enable_max_depth" instead.', 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...
137 1
                $context->setMaxDepth($options['maxDepth']);
0 ignored issues
show
Deprecated Code introduced by
The method FOS\RestBundle\Context\Context::setMaxDepth() has been deprecated with message: since 2.1, to be removed in 3.0. Use {@link self::enableMaxDepth()} and {@link self::disableMaxDepth()} instead

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