Passed
Push — master ( e85a2d...ea8174 )
by Rafael
07:43
created

AbstractMutationResolver::createDefinitionForm()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.2269

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 32
ccs 15
cts 18
cp 0.8333
rs 6.7272
cc 7
eloc 18
nc 6
nop 2
crap 7.2269
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\Form\DataTransformer\DataWithIdToNodeTransformer;
20
use Ynlo\GraphQLBundle\Model\ConstraintViolation;
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($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 mixed $data
165
     * @param bool  $disableValidation
166
     *
167
     * @return FormBuilderInterface|null
168
     */
169 8
    public function createDefinitionForm($data, $disableValidation = false): ?FormBuilderInterface
170
    {
171 8
        if (!$this->context->getDefinition()->hasMeta('form')) {
172
            return null;
173
        }
174
175 8
        $formConfig = $this->context->getDefinition()->getMeta('form') ?? [];
176 8
        $formType = $formConfig['type'] ?? null;
177 8
        if (!$formConfig || !$formType) {
178
            throw new \RuntimeException(sprintf('Can`t find a valid form for %s', $this->context->getDefinition()->getName()));
179
        }
180
181
        $options = [
182 8
            'allow_extra_fields' => true,
183
        ];
184
185 8
        if ($this->container->hasParameter('form.type_extension.csrf.enabled')
186 8
            && $this->container->getParameter('form.type_extension.csrf.enabled')) {
187 8
            $options['csrf_protection'] = false;
188
        }
189
190 8
        $options = array_merge($options, $formConfig['options'] ?? []);
191
192 8
        if ($disableValidation) {
193
            $options['validation_groups'] = false;
194
        }
195
196 8
        $form = $this->createFormBuilder($formType, $data, $options);
197 8
        $viewTransformer = new DataWithIdToNodeTransformer($this->getManager(), $this->context->getEndpoint());
198 8
        $form->addViewTransformer($viewTransformer);
199
200 8
        return $form;
201
    }
202
203
    /**
204
     * @param FormInterface           $form
205
     * @param ConstraintViolationList $violations
206
     * @param null|string             $parentName
207
     */
208 8
    public function extractFormErrors(FormInterface $form, ConstraintViolationList $violations, ?string $parentName = null)
209
    {
210 8
        $errors = $form->getErrors();
211 8
        foreach ($errors as $error) {
212 1
            $violation = new ConstraintViolation();
213
214 1
            $path = null;
215 1
            if ($form->getParent()) {
216 1
                $path = $form->getName();
217
            }
218 1
            if ($parentName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parentName of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
219 1
                $path = $parentName.'.'.$form->getName();
220
            }
221
222 1
            $violation->setPropertyPath($path);
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
236 1
            $violations->addViolation($violation);
237
        }
238 8
        if ($form->all()) {
239 8
            foreach ($form->all() as $child) {
240 8
                $parentName = $form->getName();
241
242
                //avoid set the name of the form
243 8
                if ($form->getName() === $parentName && !$form->getParent()) {
244 8
                    $parentName = null;
245
                }
246
247 8
                $this->extractFormErrors($child, $violations, $parentName);
248
            }
249
        }
250 8
    }
251
}
252