Completed
Push — master ( cbfed7...c39fb6 )
by Rafael
05:06
created

MutationAnnotationParser   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 199
Duplicated Lines 9.05 %

Test Coverage

Coverage 86.02%

Importance

Changes 0
Metric Value
dl 18
loc 199
ccs 80
cts 93
cp 0.8602
rs 10
c 0
b 0
f 0
wmc 23

6 Methods

Rating   Name   Duplication   Size   Complexity  
C getFormType() 0 25 7
C parse() 0 50 8
A __construct() 0 3 1
B createFormInputObject() 0 24 3
B createMutation() 18 43 3
A supports() 0 3 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Definition\Loader\Annotation;
12
13
use GraphQL\Type\Definition\Type;
14
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
15
use Symfony\Component\Form\Extension\Core\Type\EmailType;
16
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
17
use Symfony\Component\Form\Extension\Core\Type\TextType;
18
use Symfony\Component\Form\FormFactory;
19
use Symfony\Component\Form\FormInterface;
20
use Ynlo\GraphQLBundle\Annotation;
21
use Ynlo\GraphQLBundle\Definition\ArgumentDefinition;
22
use Ynlo\GraphQLBundle\Definition\FieldDefinition;
23
use Ynlo\GraphQLBundle\Definition\InputObjectDefinition;
24
use Ynlo\GraphQLBundle\Definition\MutationDefinition;
25
use Ynlo\GraphQLBundle\Definition\Registry\DefinitionManager;
26
use Ynlo\GraphQLBundle\Form\Type\IDType;
27
28
/**
29
 * Parse mutation annotation to fetch definitions
30
 */
31
class MutationAnnotationParser implements AnnotationParserInterface
32
{
33
    use AnnotationReaderAwareTrait;
34
    use AnnotationParserHelper;
35
36
    /**
37
     * @var FormFactory
38
     */
39
    protected $formFactory;
40
41
    /**
42
     * @var DefinitionManager
43
     */
44
    protected $definitionManager;
45
46
    /**
47
     * @param FormFactory $formFactory
48
     */
49 1
    public function __construct(FormFactory $formFactory)
50
    {
51 1
        $this->formFactory = $formFactory;
52 1
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 1
    public function supports($annotation): bool
58
    {
59 1
        return get_class($annotation) === Annotation\Mutation::class;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 1
    public function parse($annotation, \ReflectionClass $refClass, DefinitionManager $definitionManager)
66
    {
67
        /** @var Annotation\Mutation $annotation */
68
69 1
        if (!$annotation->name) {
70 1
            $annotation->name = $this->getDefaultName($refClass, $definitionManager);
71
        }
72
73
        //try find form using naming convention
74
        //the form should be placed in the same bundle with the same name of the mutation with "Input" suffix
75
        //e.g. AppBundle\Mutation\User\AddUser => AppBundle\Form\Input\User\AddUserInput
76 1
        if (!$annotation->form) {
77 1
            $definition = $this->getObjectDefinition($refClass, $definitionManager);
78 1
            if ($class = $definition->getClass()) {
79 1
                $bundleNamespace = preg_replace('~Bundle(?!.*Bundle)[\\\\\w+]+~', null, $class).'Bundle';
80 1
                $formClass = sprintf('%s\Form\Input\%s\%sInput', $bundleNamespace, $definition->getName(), ucfirst($annotation->name));
81 1
                if (class_exists($formClass)) {
82 1
                    $annotation->form = $formClass;
83
                } else {
84
                    $error = sprintf(
85
                        'Can`t find a valid input form type to use in "%s".
86
                         Create the form "%s" or specify a custom form in the annotation of "%s"',
87
                        $annotation->name,
88
                        $formClass,
89
                        $refClass->getName()
90
                    );
91
                    throw new \Exception($error);
92
                }
93
            }
94
        }
95
96
97 1
        $this->definitionManager = $definitionManager;
98 1
        $mutation = $this->createMutation($annotation);
99 1
        $this->definitionManager->addMutation($mutation);
100
101 1
        if (!$mutation->getType()) {
102 1
            $mutation->setType($annotation->payload);
103
        }
104
105 1
        if (!$mutation->getType()) {
106
            $error = sprintf(
107
                'The mutation "%s" does not have a valid payload, must define the payload in the annotation.',
108
                $annotation->name
109
            );
110
            throw new \Exception($error);
111
        }
112
113 1
        if (!$mutation->getResolver()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $mutation->getResolver() of type null|string is loosely compared to false; 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...
114 1
            $mutation->setResolver($refClass->getName());
115
        }
116 1
    }
117
118
    /**
119
     * @param Annotation\Mutation $annotation
120
     *
121
     * @return MutationDefinition
122
     */
123 1
    public function createMutation(Annotation\Mutation $annotation): MutationDefinition
124
    {
125 1
        $mutation = new MutationDefinition();
126 1
        $mutation->setName($annotation->name);
127 1
        $mutation->setDescription($annotation->description);
128 1
        $mutation->setDeprecationReason($annotation->deprecationReason);
129
130 1
        $formType = $annotation->form;
131 1
        $form = $this->formFactory->create($formType, null, $annotation->formOptions);
132
133 1
        $inputObject = $this->createFormInputObject($form, ucfirst($mutation->getName()));
134
135 1 View Code Duplication
        if ($annotation->clientMutationId) {
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...
136 1
            $clientMutationId = new FieldDefinition();
137 1
            $clientMutationId->setName('clientMutationId');
138 1
            $clientMutationId->setType(Type::STRING);
139 1
            $clientMutationId->setDescription('A unique identifier for the client performing the mutation.');
140 1
            $inputObject->prependField($clientMutationId);
141
        }
142
143 1 View Code Duplication
        if ($annotation->dryRun) {
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 1
            $clientMutationId = new FieldDefinition();
145 1
            $clientMutationId->setName('dryRun');
146 1
            $clientMutationId->setType(Type::BOOLEAN);
147 1
            $clientMutationId->setDescription(
148 1
                'Execute only a validation process without save anything.
149
Helpful to create a server side validation. 
150
Must check `constraintViolations` in the payload to get validation messages.'
151
            );
152 1
            $inputObject->prependField($clientMutationId);
153
        }
154
155 1
        $this->definitionManager->addType($inputObject);
156
157 1
        $input = new ArgumentDefinition();
158 1
        $input->setName('input');
159 1
        $input->setType($inputObject->getName());
160
161 1
        $mutation->addArgument($input);
162 1
        $mutation->setMeta('form', $formType);
163 1
        $mutation->setMeta('form_options', $annotation->formOptions);
164
165 1
        return $mutation;
166
    }
167
168
    /**
169
     * @param FormInterface $form
170
     * @param string        $name
171
     *
172
     * @return InputObjectDefinition
173
     */
174 1
    public function createFormInputObject(FormInterface $form, $name)
175
    {
176 1
        $inputObject = new InputObjectDefinition();
177 1
        $inputObject->setName($name.'Input');
178
179 1
        foreach ($form->all() as $formField) {
180 1
            $field = new FieldDefinition();
181 1
            $field->setName($formField->getConfig()->getOption('label') ?? $formField->getName());
182 1
            $field->setNonNull($formField->isRequired());
183 1
            $field->setOriginName($formField->getName());
184
185 1
            if ($formField->all()) {
186 1
                $childName = $name.ucfirst($formField->getName());
187 1
                $child = $this->createFormInputObject($formField, $childName);
188 1
                $this->definitionManager->addType($child);
189 1
                $field->setType($child->getName());
190
            } else {
191 1
                $field->setType($this->getFormType($formField));
192
            }
193
194 1
            $inputObject->addField($field);
195
        }
196
197 1
        return $inputObject;
198
    }
199
200
    /**
201
     * @param FormInterface $form
202
     *
203
     * @return string
204
     */
205 1
    public function getFormType(FormInterface $form)
206
    {
207 1
        $resolver = $form->getConfig()->getType()->getOptionsResolver();
208 1
        if ($resolver->hasDefault('graphql_type')) {
209
            return $resolver->resolve([])['graphql_type'];
210
        }
211
212 1
        if (is_a($form->getConfig()->getType()->getInnerType(), IDType::class, true)) {
213 1
            return Type::ID;
214
        }
215
216 1
        if (is_a($form->getConfig()->getType()->getInnerType(), TextType::class, true)) {
217 1
            return Type::STRING;
218
        }
219
220 1
        if (is_a($form->getConfig()->getType()->getInnerType(), EmailType::class, true)) {
221 1
            return Type::STRING;
222
        }
223
224 1
        if (is_a($form->getConfig()->getType()->getInnerType(), CheckboxType::class, true)) {
225 1
            return Type::BOOLEAN;
226
        }
227
228
        if (is_a($form->getConfig()->getType()->getInnerType(), IntegerType::class, true)) {
229
            return Type::INT;
230
        }
231
    }
232
}
233