Completed
Pull Request — develop (#430)
by Narcotic
294:39 queued 229:38
created

Form::checkJsonRequest()   C

Complexity

Conditions 11
Paths 18

Size

Total Lines 47
Code Lines 29

Duplication

Lines 12
Ratio 25.53 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 12
loc 47
ccs 0
cts 33
cp 0
rs 5.2653
cc 11
eloc 29
nc 18
nop 3
crap 132

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * base form validator
4
 */
5
6
namespace Graviton\RestBundle\Validator;
7
8
use Graviton\DocumentBundle\Service\FormDataMapperInterface;
9
use Graviton\ExceptionBundle\Exception\InvalidJsonPatchException;
10
use Graviton\ExceptionBundle\Exception\MalformedInputException;
11
use Graviton\ExceptionBundle\Exception\NoInputException;
12
use Graviton\ExceptionBundle\Exception\ValidationException;
13
use Graviton\RestBundle\Model\DocumentModel;
14
use Symfony\Component\Form\FormFactory;
15
use Symfony\Component\Form\FormInterface;
16
use Graviton\DocumentBundle\Form\Type\DocumentType;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\Validator\Validator\ValidatorInterface;
20
21
/**
22
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
23
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
24
 * @link     http://swisscom.ch
25
 */
26
class Form
27
{
28
    /**
29
     * @var FormFactory
30
     */
31
    private $formFactory;
32
33
    /**
34
     * @var DocumentType
35
     */
36
    private $formType;
37
38
    /**
39
     * @var ValidatorInterface
40
     */
41
    private $validator;
42
43
    /**
44
     * @param FormFactory        $formFactory Factory, providing different file document instances.
45
     * @param DocumentType       $formType    Type of form to be set
46
     * @param ValidatorInterface $validator   Validator to verify correctness of the provided data
47
     */
48
    public function __construct(
49
        FormFactory $formFactory,
50
        DocumentType $formType,
51
        ValidatorInterface $validator
52
    ) {
53
        $this->formFactory = $formFactory;
54
        $this->formType = $formType;
55
        $this->validator = $validator;
56
    }
57
58
    /**
59
     * @param Request       $request request
60
     * @param DocumentModel $model   model
61
     *
62
     * @return \Symfony\Component\Form\Form
63
     */
64
    public function getForm(Request $request, DocumentModel $model)
65
    {
66
        $this->formType->initialize($model->getEntityClass());
67
        return $this->formFactory->create($this->formType, null, ['method' => $request->getMethod()]);
0 ignored issues
show
Documentation introduced by
$this->formType is of type object<Graviton\Document...Form\Type\DocumentType>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
68
    }
69
70
    /**
71
     * Validates the provided information against a form.
72
     *
73
     * @param FormInterface           $form           form to check
74
     * @param DocumentModel           $model          Model to determine entity to be used
75
     * @param FormDataMapperInterface $formDataMapper Mapps the entity to form fields
76
     * @param string                  $jsonContent    json data
77
     *
78
     * @throws ValidationException
79
     * @return mixed
80
     */
81
    public function checkForm(
82
        FormInterface $form,
83
        DocumentModel $model,
84
        FormDataMapperInterface $formDataMapper,
85
        $jsonContent
86
    ) {
87
        $document = $formDataMapper->convertToFormData(
88
            $jsonContent,
89
            $model->getEntityClass()
90
        );
91
        $form->submit($document, true);
92
93
        if (!$form->isValid()) {
94
            throw new ValidationException($form->getErrors(true));
95
        } else {
96
            $record = $form->getData();
97
        }
98
99
        return $record;
100
    }
101
102
    /**
103
     * validate raw json input
104
     *
105
     * @param Request  $request  request
106
     * @param Response $response response
107
     * @param string   $content  Alternative request content.
108
     *
109
     * @return void
110
     */
111
    public function checkJsonRequest(Request $request, Response $response, $content = '')
112
    {
113
        if (empty($content)) {
114
            $content = $request->getContent();
115
        }
116
117
        if (is_resource($content)) {
118
            throw new BadRequestHttpException('unexpected resource in validation');
119
        }
120
121
        // is request body empty
122
        if ($content === '') {
123
            $e = new NoInputException();
124
            $e->setResponse($response);
125
            throw $e;
126
        }
127
128
        $input = json_decode($content, true);
129
        if (JSON_ERROR_NONE !== json_last_error()) {
130
            $e = new MalformedInputException($this->getLastJsonErrorMessage());
131
            $e->setErrorType(json_last_error());
132
            $e->setResponse($response);
133
            throw $e;
134
        }
135
        if (!is_array($input)) {
136
            $e = new MalformedInputException('JSON request body must be an object');
137
            $e->setResponse($response);
138
            throw $e;
139
        }
140
141
        if ($request->getMethod() == 'PUT' && array_key_exists('id', $input)) {
142
            // we need to check for id mismatches....
143 View Code Duplication
            if ($request->attributes->get('id') != $input['id']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
144
                $e = new MalformedInputException('Record ID in your payload must be the same');
145
                $e->setResponse($response);
146
                throw $e;
147
            }
148
        }
149
150 View Code Duplication
        if ($request->getMethod() == 'POST' && array_key_exists('id', $input)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
151
            $e = new MalformedInputException(
152
                '"id" can not be given on a POST request. Do a PUT request instead to update an existing record.'
153
            );
154
            $e->setResponse($response);
155
            throw $e;
156
        }
157
    }
158
159
    /**
160
     * Validate JSON patch for any object
161
     *
162
     * @param array $jsonPatch json patch as array
163
     *
164
     * @throws InvalidJsonPatchException
165
     * @return void
166
     */
167
    public function checkJsonPatchRequest(array $jsonPatch)
168
    {
169
        foreach ($jsonPatch as $operation) {
170
            if (!is_array($operation)) {
171
                throw new InvalidJsonPatchException('Patch request should be an array of operations.');
172
            }
173
            if (array_key_exists('path', $operation) && trim($operation['path']) == '/id') {
174
                throw new InvalidJsonPatchException('Change/remove of ID not allowed');
175
            }
176
        }
177
    }
178
    /**
179
     * Used for backwards compatibility to PHP 5.4
180
     *
181
     * @return string
182
     */
183
    private function getLastJsonErrorMessage()
184
    {
185
        $message = 'Unable to decode JSON string';
186
187
        if (function_exists('json_last_error_msg')) {
188
            $message = json_last_error_msg();
189
        }
190
191
        return $message;
192
    }
193
}
194