Completed
Push — master ( d2c88c...854f25 )
by Rafael
03:52
created

AbstractMutationResolver::extractFormErrors()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 17
cts 17
cp 1
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 16
nc 7
nop 3
crap 5
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Mutation;
12
13
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
14
use Symfony\Component\Form\FormBuilderInterface;
15
use Symfony\Component\Form\FormEvent;
16
use Symfony\Component\Form\FormEvents;
17
use Symfony\Component\Form\FormInterface;
18
use Symfony\Component\Validator\ConstraintViolation as SymfonyConstraintViolation;
19
use Ynlo\GraphQLBundle\Model\ConstraintViolation;
20
use Ynlo\GraphQLBundle\Model\ID;
21
use Ynlo\GraphQLBundle\Resolver\AbstractResolver;
22
use Ynlo\GraphQLBundle\Validator\ConstraintViolationList;
23
24
/**
25
 * Base class for mutations
26
 * Implement the method "process()" and "returnPayload()" is enough in many scenarios
27
 */
28
abstract class AbstractMutationResolver extends AbstractResolver implements EventSubscriberInterface
29
{
30
    /**
31
     * @param array $input
32
     *
33
     * @return mixed
34
     */
35 8
    public function __invoke($input)
36
    {
37 8
        $formBuilder = $this->createDefinitionForm($this->initialFormData($input));
38
39 8
        $form = null;
40 8
        if ($formBuilder) {
41 8
            $formBuilder->addEventSubscriber($this);
42
43
            $extensionExecutor = function ($method) {
44 8
                return function (FormEvent $event) use ($method) {
45 8
                    foreach ($this->extensions as $extension) {
46 4
                        return call_user_func_array([$extension, $method], [$event]);
47
                    }
48 8
                };
49 8
            };
50
51 8
            foreach (self::getSubscribedEvents() as $event => $method) {
52 8
                $formBuilder->addEventListener($event, $extensionExecutor($method));
53
            }
54
55 8
            $form = $formBuilder->getForm();
56
        }
57
58 8
        if ($form) {
59 8
            $form->submit($input, false);
60 8
            $data = $form->getData();
61
        } else {
62
            $data = $input;
63
        }
64
65 8
        $violations = new ConstraintViolationList();
66 8
        if ($form) {
67 8
            $this->extractFormErrors($form, $violations);
68
        }
69
70 8
        $dryRun = $input['dryRun'] ?? false;
71
72 8
        if ($dryRun) {
73
            $data = null;
74
        } else {
75 8
            if ((!$form && !$violations->count())
76 8
                || ($form->isSubmitted() && $form->isValid() && !$violations->count())
77
            ) {
78 7
                $this->process($data);
79
            }
80
        }
81
82 8
        return $this->returnPayload($data, $violations, $input);
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 8
    public static function getSubscribedEvents()
89
    {
90
        return [
91 8
            FormEvents::PRE_SET_DATA => 'preSetData',
92 8
            FormEvents::POST_SET_DATA => 'postSetData',
93 8
            FormEvents::PRE_SUBMIT => 'preSubmit',
94 8
            FormEvents::SUBMIT => 'onSubmit',
95 8
            FormEvents::POST_SUBMIT => 'postSubmit',
96
        ];
97
    }
98
99
    /**
100
     * @see http://api.symfony.com/4.0/Symfony/Component/Form/FormEvents.html
101
     *
102
     * @param FormEvent $event
103
     */
104 8
    public function preSetData(FormEvent $event)
105
    {
106 8
    }
107
108
    /**
109
     * @see http://api.symfony.com/4.0/Symfony/Component/Form/FormEvents.html
110
     *
111
     * @param FormEvent $event
112
     */
113 8
    public function postSetData(FormEvent $event)
114
    {
115 8
    }
116
117
    /**
118
     * @see http://api.symfony.com/4.0/Symfony/Component/Form/FormEvents.html
119
     *
120
     * @param FormEvent $event
121
     */
122 8
    public function preSubmit(FormEvent $event)
123
    {
124 8
    }
125
126
    /**
127
     * @see http://api.symfony.com/4.0/Symfony/Component/Form/FormEvents.html
128
     *
129
     * @param FormEvent $event
130
     */
131 4
    public function onSubmit(FormEvent $event)
132
    {
133 4
    }
134
135
    /**
136
     * @see http://api.symfony.com/4.0/Symfony/Component/Form/FormEvents.html
137
     *
138
     * @param FormEvent $event
139
     */
140 8
    public function postSubmit(FormEvent $event)
141
    {
142 8
    }
143
144
    /**
145
     * Actions to process
146
     * the result processed data is given to payload
147
     *
148
     * @param mixed $data
149
     */
150
    abstract public function process(&$data);
151
152
    /**
153
     * The payload object or array matching the GraphQL definition
154
     *
155
     * @param mixed                   $data        normalized data, its the input data processed by the form
156
     * @param ConstraintViolationList $violations  violations returned by the form validation process
157
     * @param array                   $inputSource the original submitted data in array
158
     *
159
     * @return mixed
160
     */
161
    abstract public function returnPayload($data, ConstraintViolationList $violations, $inputSource);
162
163
    /**
164
     * @param array $input
165
     *
166
     * @return mixed
167
     */
168 8
    public function initialFormData($input)
169
    {
170 8
        if (is_array($input) && isset($input['id'])) {
171 3
            $id = ID::createFromString($input['id']);
172 3
            if ($this->context->getEndpoint()->hasType($id->getNodeType())) {
173 3
                $class = $this->context->getEndpoint()->getClassForType($id->getNodeType());
174 3
                if ($class) {
175 3
                    return $this->getManager()->getRepository($class)->find($id->getDatabaseId());
176
                }
177
            }
178
        }
179
180 6
        return null;
181
    }
182
    /**
183
     * @param mixed|null $data
184
     *
185
     * @return FormBuilderInterface|null
186
     */
187 8
    public function createDefinitionForm($data): ?FormBuilderInterface
188
    {
189 8
        if (!$this->context->getDefinition()->hasMeta('form')) {
190
            return null;
191
        }
192
193 8
        $formConfig = $this->context->getDefinition()->getMeta('form') ?? [];
194 8
        $formType = $formConfig['type'] ?? null;
195 8
        if (!$formConfig || !$formType) {
196
            throw new \RuntimeException(sprintf('Can`t find a valid form for %s', $this->context->getDefinition()->getName()));
197
        }
198
199
        $options = [
200 8
            'allow_extra_fields' => true,
201
        ];
202
203 8
        if ($this->container->hasParameter('form.type_extension.csrf.enabled')
204 8
            && $this->container->getParameter('form.type_extension.csrf.enabled')) {
205 8
            $options['csrf_protection'] = false;
206
        }
207
208 8
        $options = array_merge($options, $formConfig['options'] ?? []);
209
210 8
        return $this->createFormBuilder($formType, $data, $options);
211
    }
212
213
    /**
214
     * @param FormInterface           $form
215
     * @param ConstraintViolationList $violations
216
     * @param null|string             $parentName
217
     */
218 8
    public function extractFormErrors(FormInterface $form, ConstraintViolationList $violations, ?string $parentName = null)
219
    {
220 8
        $errors = $form->getErrors(true);
221 8
        foreach ($errors as $error) {
222 1
            $violation = new ConstraintViolation();
223 1
            $violation->setMessage($error->getMessage());
0 ignored issues
show
Bug introduced by
The method getMessage() does not exist on Symfony\Component\Form\FormErrorIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

223
            $violation->setMessage($error->/** @scrutinizer ignore-call */ getMessage());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
224 1
            $violation->setMessageTemplate($error->getMessageTemplate());
0 ignored issues
show
Bug introduced by
The method getMessageTemplate() does not exist on Symfony\Component\Form\FormErrorIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

224
            $violation->setMessageTemplate($error->/** @scrutinizer ignore-call */ getMessageTemplate());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
225 1
            foreach ($error->getMessageParameters() as $key => $value) {
0 ignored issues
show
Bug introduced by
The method getMessageParameters() does not exist on Symfony\Component\Form\FormErrorIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

225
            foreach ($error->/** @scrutinizer ignore-call */ getMessageParameters() as $key => $value) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
226 1
                $violation->addParameter($key, $value);
227
            }
228
229 1
            $cause = $error->getCause();
0 ignored issues
show
Bug introduced by
The method getCause() does not exist on Symfony\Component\Form\FormErrorIterator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

229
            /** @scrutinizer ignore-call */ 
230
            $cause = $error->getCause();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
230 1
            if ($cause instanceof SymfonyConstraintViolation) {
231 1
                $violation->setCode($cause->getCode());
232 1
                $violation->setInvalidValue($cause->getInvalidValue());
233 1
                $violation->setPlural($cause->getPlural());
234
235 1
                $path = $this->publicPropertyPath($form, $cause->getPropertyPath());
236 1
                if ($path) {
237 1
                    $violation->setPropertyPath($path);
238
                }
239
            }
240
241 1
            $violations->addViolation($violation);
242
        }
243 8
    }
244
245
    /**
246
     * Convert internal validation property path to the public one,
247
     * required when use `property_path` in the form
248
     *
249
     * @param FormInterface $form
250
     * @param string        $path
251
     *
252
     * @return string
253
     */
254 1
    private function publicPropertyPath(FormInterface $form, $path)
255
    {
256 1
        if (strpos($path, '.') !== false) {
257 1
            $pathArray = explode('.', $path);
258
        } else {
259
            $pathArray = [$path];
260
        }
261 1
        if ($pathArray[0] === 'data') {
262 1
            array_shift($pathArray);
263
        }
264
265 1
        $contextForm = $form;
266 1
        foreach ($pathArray as &$propName) {
267 1
            $index = null;
268 1
            if (preg_match('/(\w+)(\[\d+\])$/', $propName, $matches)) {
269
                list(, $propName, $index) = $matches;
270
            }
271 1
            if (!$contextForm->has($propName)) {
272 1
                foreach ($contextForm->all() as $child) {
273 1
                    if ($child->getConfig()->getOption('property_path') === $propName) {
274 1
                        $propName = $child->getName();
275
                    }
276
                }
277
            }
278 1
            if ($index) {
279 1
                $propName = sprintf('%s%s', $propName, $index);
0 ignored issues
show
Bug introduced by
$index of type void is incompatible with the type string expected by parameter $args of sprintf(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

279
                $propName = sprintf('%s%s', $propName, /** @scrutinizer ignore-type */ $index);
Loading history...
280
            }
281
        }
282 1
        unset($propName);
283
284 1
        return implode('.', $pathArray);
285
    }
286
}
287