Completed
Push — master ( b1054d...eba5f2 )
by Christian
07:28 queued 11s
created

RequestBodyParamConverter::__construct()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 10
cts 11
cp 0.9091
rs 9.2248
c 0
b 0
f 0
cc 5
nc 8
nop 5
crap 5.0187
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
38
    /**
39
     * The name of the argument on which the ConstraintViolationList will be set.
40
     *
41
     * @var null|string
42
     */
43
    private $validationErrorsArgument;
44
45
    /**
46
     * @param Serializer         $serializer
47
     * @param array|null         $groups                   An array of groups to be used in the serialization context
48
     * @param string|null        $version                  A version string to be used in the serialization context
49
     * @param ValidatorInterface $validator
50
     * @param string|null        $validationErrorsArgument
51
     *
52
     * @throws \InvalidArgumentException
53
     */
54 15
    public function __construct(
55
        Serializer $serializer,
56
        $groups = null,
57
        $version = null,
58
        ValidatorInterface $validator = null,
59
        $validationErrorsArgument = null
60
    ) {
61 15
        $this->serializer = $serializer;
62
63 15
        if (!empty($groups)) {
64 1
            $this->context['groups'] = (array) $groups;
65
        }
66
67 15
        if (!empty($version)) {
68 1
            $this->context['version'] = $version;
69
        }
70
71 15
        if (null !== $validator && null === $validationErrorsArgument) {
72
            throw new \InvalidArgumentException('"$validationErrorsArgument" cannot be null when using the validator');
73
        }
74
75 15
        $this->validator = $validator;
76 15
        $this->validationErrorsArgument = $validationErrorsArgument;
77 15
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82 9
    public function apply(Request $request, ParamConverter $configuration)
83
    {
84 9
        $options = (array) $configuration->getOptions();
85
86 9
        if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) {
87 1
            $arrayContext = array_merge($this->context, $options['deserializationContext']);
88
        } else {
89 8
            $arrayContext = $this->context;
90
        }
91 9
        $this->configureContext($context = new Context(), $arrayContext);
92
93
        try {
94 9
            $object = $this->serializer->deserialize(
95 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...
96 9
                $configuration->getClass(),
97 9
                $request->getContentType(),
98
                $context
99
            );
100 3
        } catch (UnsupportedFormatException $e) {
101
            return $this->throwException(new UnsupportedMediaTypeHttpException($e->getMessage(), $e), $configuration);
102 3
        } catch (JMSSerializerException $e) {
103 1
            return $this->throwException(new BadRequestHttpException($e->getMessage(), $e), $configuration);
104 2
        } catch (SymfonySerializerException $e) {
105 1
            return $this->throwException(new BadRequestHttpException($e->getMessage(), $e), $configuration);
106
        }
107
108 6
        $request->attributes->set($configuration->getName(), $object);
109
110 6
        if (null !== $this->validator && (!isset($options['validate']) || $options['validate'])) {
111 1
            $validatorOptions = $this->getValidatorOptions($options);
112
113 1
            $errors = $this->validator->validate($object, null, $validatorOptions['groups']);
114
115 1
            $request->attributes->set(
116 1
                $this->validationErrorsArgument,
117
                $errors
118
            );
119
        }
120
121 6
        return true;
122
    }
123
124
    /**
125
     * {@inheritdoc}
126
     */
127 4
    public function supports(ParamConverter $configuration)
128
    {
129 4
        return null !== $configuration->getClass() && 'fos_rest.request_body' === $configuration->getConverter();
130
    }
131
132
    /**
133
     * @param Context $context
134
     * @param array   $options
135
     */
136 9
    protected function configureContext(Context $context, array $options)
137
    {
138 9
        foreach ($options as $key => $value) {
139 1
            if ('groups' === $key) {
140 1
                $context->addGroups($options['groups']);
141 1
            } elseif ('version' === $key) {
142 1
                $context->setVersion($options['version']);
143 1
            } elseif ('enableMaxDepth' === $key) {
144 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...
145 1
            } elseif ('serializeNull' === $key) {
146 1
                $context->setSerializeNull($options['serializeNull']);
147
            } else {
148 1
                $context->setAttribute($key, $value);
149
            }
150
        }
151 9
    }
152
153
    /**
154
     * Throws an exception or return false if a ParamConverter is optional.
155
     */
156 2
    private function throwException(\Exception $exception, ParamConverter $configuration)
157
    {
158 2
        if ($configuration->isOptional()) {
159
            return false;
160
        }
161
162 2
        throw $exception;
163
    }
164
165
    /**
166
     * @param array $options
167
     *
168
     * @return array
169
     */
170 2
    private function getValidatorOptions(array $options)
171
    {
172 2
        $resolver = new OptionsResolver();
173 2
        $resolver->setDefaults([
174 2
            'groups' => null,
175
            'traverse' => false,
176
            'deep' => false,
177
        ]);
178
179 2
        return $resolver->resolve(isset($options['validator']) ? $options['validator'] : []);
180
    }
181
}
182