GraphQLInputGenerator   F
last analyzed

Complexity

Total Complexity 92

Size/Duplication

Total Lines 336
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 92
eloc 175
c 3
b 0
f 0
dl 0
loc 336
rs 2

9 Methods

Rating   Name   Duplication   Size   Complexity  
D sanitiseFieldTypes() 0 83 61
C prepareRelationship() 0 58 13
A __construct() 0 8 1
A generateRelation() 0 6 1
A generateRelations() 0 23 5
A generateSchema() 0 26 5
A generate() 0 13 2
A getRelationFunctionText() 0 9 2
A rollback() 0 5 2

How to fix   Complexity   

Complex Class

Complex classes like GraphQLInputGenerator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GraphQLInputGenerator, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PWWEB\Artomator\Generators\GraphQL;
4
5
use Illuminate\Support\Str;
6
use InfyOm\Generator\Generators\BaseGenerator;
7
use PWWEB\Artomator\Common\CommandData;
8
9
class GraphQLInputGenerator extends BaseGenerator
10
{
11
    /**
12
     * Command data.
13
     *
14
     * @var CommandData
15
     */
16
    private $commandData;
17
18
    /**
19
     * Filename.
20
     *
21
     * @var string
22
     */
23
    private $fileName;
24
25
    /**
26
     * File contents.
27
     *
28
     * @var string
29
     */
30
    private $fileContents;
31
32
    /**
33
     * Template data.
34
     *
35
     * @var string
36
     */
37
    private $templateData;
38
39
    /**
40
     * Constructor.
41
     *
42
     * @param CommandData $commandData Command Data.
43
     */
44
    public function __construct(CommandData $commandData)
45
    {
46
        $this->commandData = $commandData;
47
        $this->fileName = $commandData->config->pathGraphQL;
48
        $this->fileContents = file_get_contents($this->fileName);
49
        $this->templateData = get_artomator_template('graphql.inputs');
50
        $this->templateData = fill_template($this->commandData->dynamicVars, $this->templateData);
51
        $this->templateData = fill_template($this->generateSchema(), $this->templateData);
0 ignored issues
show
Bug introduced by
$this->generateSchema() of type void is incompatible with the type array expected by parameter $variables of fill_template(). ( Ignorable by Annotation )

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

51
        $this->templateData = fill_template(/** @scrutinizer ignore-type */ $this->generateSchema(), $this->templateData);
Loading history...
Bug introduced by
Are you sure the usage of $this->generateSchema() targeting PWWEB\Artomator\Generato...rator::generateSchema() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
52
    }
53
54
    /**
55
     * Generate Command.
56
     *
57
     * @return void
58
     */
59
    public function generate()
60
    {
61
        if (true === Str::contains($this->fileContents, $this->templateData)) {
62
            $this->commandData->commandObj->info('GraphQL Inputs '.$this->commandData->config->mHumanPlural.' already exist; Skipping');
63
64
            return;
65
        }
66
67
        $this->fileContents .= $this->templateData;
68
69
        file_put_contents($this->fileName, $this->fileContents);
70
71
        $this->commandData->commandComment("\nGraphQL Inputs created");
72
    }
73
74
    /**
75
     * Rollback.
76
     *
77
     * @return void
78
     */
79
    public function rollback()
80
    {
81
        if (true === Str::contains($this->fileContents, $this->templateData)) {
82
            file_put_contents($this->fileName, str_replace($this->templateData, '', $this->fileContents));
83
            $this->commandData->commandComment('GraphQL Inputs deleted');
84
        }
85
    }
86
87
    /**
88
     * Sanitise the field types.
89
     *
90
     * @param string $fieldType Field type.
91
     *
92
     * @return void
93
     */
94
    private function sanitiseFieldTypes(string $fieldType)
95
    {
96
        $needle = "/\(.+\)?/";
97
        $replace = '';
98
        $fieldType = preg_replace($needle, $replace, $fieldType);
99
        // There are 5 basic scalar types + 2 lighthouse ones (Date and DateTime);
100
        switch ($fieldType) {
101
            case 'bigIncrements':
102
            case 'bigInteger':
103
            case 'binary':
104
            case 'increments':
105
            case 'integer':
106
            case 'mediumIncrements':
107
            case 'mediumInteger':
108
            case 'smallIncrements':
109
            case 'smallInteger':
110
            case 'tinyIncrements':
111
            case 'tinyInteger':
112
            case 'unsignedBigInteger':
113
            case 'unsignedInteger':
114
            case 'unsignedMediumInteger':
115
            case 'unsignedSmallInteger':
116
            case 'unsignedTinyInteger':
117
            case 'year':
118
                return 'Int';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'Int' returns the type string which is incompatible with the documented return type void.
Loading history...
119
120
            case 'unsignedDecimal':
121
            case 'point':
122
            case 'polygon':
123
            case 'multiPoint':
124
            case 'multiPolygon':
125
            case 'float':
126
            case 'decimal':
127
            case 'double':
128
                return 'Float';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'Float' returns the type string which is incompatible with the documented return type void.
Loading history...
129
130
            case 'uuid':
131
            case 'string':
132
            case 'text':
133
            case 'rememberToken':
134
            case 'mediumText':
135
            case 'multiLineString':
136
            case 'ipAddress':
137
            case 'json':
138
            case 'jsonb':
139
            case 'lineString':
140
            case 'longText':
141
            case 'macAddress':
142
            case 'char':
143
                return 'String';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'String' returns the type string which is incompatible with the documented return type void.
Loading history...
144
145
            case 'boolean':
146
                return 'Boolean';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'Boolean' returns the type string which is incompatible with the documented return type void.
Loading history...
147
148
            case 'foreignId':
149
                return 'ID';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'ID' returns the type string which is incompatible with the documented return type void.
Loading history...
150
151
            case 'time':
152
            case 'timeTz':
153
            case 'timestamp':
154
            case 'timestampTz':
155
            case 'timestamps':
156
            case 'timestampsTz':
157
            case 'softDeletes':
158
            case 'softDeletesTz':
159
            case 'nullableTimestamps':
160
            case 'dateTime':
161
            case 'dateTimeTz':
162
                return 'DateTime';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'DateTime' returns the type string which is incompatible with the documented return type void.
Loading history...
163
164
            case 'date':
165
                return 'Date';
0 ignored issues
show
Bug Best Practice introduced by
The expression return 'Date' returns the type string which is incompatible with the documented return type void.
Loading history...
166
167
            case 'set':
168
            case 'nullableMorphs':
169
            case 'nullableUuidMorphs':
170
            case 'morphs':
171
            case 'uuidMorphs':
172
            case 'geometry':
173
            case 'geometryCollection':
174
            case 'enum':
175
            default:
176
                return ucfirst($fieldType);
0 ignored issues
show
Bug Best Practice introduced by
The expression return ucfirst($fieldType) returns the type string which is incompatible with the documented return type void.
Loading history...
177
        }
178
    }
179
180
    /**
181
     * Generate Schema.
182
     *
183
     * @return void
184
     */
185
    private function generateSchema()
186
    {
187
        $schema = [];
188
        foreach ($this->commandData->fields as $field) {
189
            if (true === $field->isFillable) {
190
                if ('foreignId' === $field->fieldType) {
191
                    continue;
192
                } else {
193
                    $field_type = $this->sanitiseFieldTypes($field->fieldType);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $field_type is correct as $this->sanitiseFieldTypes($field->fieldType) targeting PWWEB\Artomator\Generato...r::sanitiseFieldTypes() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
194
                }
195
196
                $field_type .= ((true === Str::contains($field->validations, 'required')) ? '!' : '');
197
198
                $schema[] = $field->name.': '.$field_type;
199
            }
200
        }
201
        $schema = array_merge($schema, $this->generateRelations());
0 ignored issues
show
Bug introduced by
$this->generateRelations() of type void is incompatible with the type array expected by parameter $arrays of array_merge(). ( Ignorable by Annotation )

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

201
        $schema = array_merge($schema, /** @scrutinizer ignore-type */ $this->generateRelations());
Loading history...
Bug introduced by
Are you sure the usage of $this->generateRelations() targeting PWWEB\Artomator\Generato...or::generateRelations() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
202
        $schema = implode(infy_nl_tab(1, 1), $schema);
203
        $create_schema = str_replace('$TYPE$', 'Create', $schema);
204
        $update_schema = str_replace('$TYPE$', 'Update', $schema);
205
        $upsert_schema = str_replace('$TYPE$', 'Upsert', $schema);
206
207
        return [
0 ignored issues
show
Bug Best Practice introduced by
The expression return array('$CREATE_SC...', '', $upsert_schema)) returns the type array<string,string> which is incompatible with the documented return type void.
Loading history...
208
            '$CREATE_SCHEMA$' => $create_schema,
209
            '$UPDATE_SCHEMA$' => str_replace('!', '', $update_schema),
210
            '$UPSERT_SCHEMA$' => str_replace('!', '', $upsert_schema),
211
        ];
212
    }
213
214
    /**
215
     * Generate Relations.
216
     *
217
     * @return void
218
     */
219
    private function generateRelations()
220
    {
221
        $relations = [];
222
223
        $count = 1;
224
        $fieldsArr = [];
225
        foreach ($this->commandData->relations as $relation) {
226
            $field = (true === isset($relation->inputs[0])) ? $relation->inputs[0] : null;
227
228
            $relationShipText = $field;
229
            if (true === in_array($field, $fieldsArr)) {
230
                $relationShipText = $relationShipText.'_'.$count;
231
                $count++;
232
            }
233
234
            $relationText = $this->getRelationFunctionText($relation, $relationShipText);
0 ignored issues
show
Bug introduced by
$relation of type InfyOm\Generator\Common\GeneratorFieldRelation is incompatible with the type string expected by parameter $relationship of PWWEB\Artomator\Generato...tRelationFunctionText(). ( Ignorable by Annotation )

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

234
            $relationText = $this->getRelationFunctionText(/** @scrutinizer ignore-type */ $relation, $relationShipText);
Loading history...
Bug introduced by
Are you sure the assignment to $relationText is correct as $this->getRelationFuncti...ion, $relationShipText) targeting PWWEB\Artomator\Generato...tRelationFunctionText() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
235
            if (false === empty($relationText)) {
236
                $fieldsArr[] = $field;
237
                $relations[] = $relationText;
238
            }
239
        }
240
241
        return $relations;
242
    }
243
244
    /**
245
     * Get the relation function tex.t.
246
     *
247
     * @param string      $relationship Relationship type.
248
     * @param string|null $relationText Relationship text.
249
     *
250
     * @return void
251
     */
252
    protected function getRelationFunctionText($relationship, $relationText = null)
253
    {
254
        extract($this->prepareRelationship($relationship, $relationText));
0 ignored issues
show
Bug introduced by
$relationship of type string is incompatible with the type PWWEB\Artomator\Generators\GraphQL\Model expected by parameter $relationship of PWWEB\Artomator\Generato...::prepareRelationship(). ( Ignorable by Annotation )

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

254
        extract($this->prepareRelationship(/** @scrutinizer ignore-type */ $relationship, $relationText));
Loading history...
255
256
        if (false === empty($functionName)) {
257
            return $this->generateRelation($functionName, $template);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->generateRelation($functionName, $template) targeting PWWEB\Artomator\Generato...tor::generateRelation() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
258
        }
259
260
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type void.
Loading history...
261
    }
262
263
    /**
264
     * Generate Relation.
265
     *
266
     * @param string $functionName Function name.
267
     * @param string $template     Template text.
268
     *
269
     * @return void
270
     */
271
    private function generateRelation($functionName, $template)
272
    {
273
        $template = str_replace('$FUNCTION_NAME$', $functionName, $template);
274
        $template = str_replace('$RELATION_GRAPHQL_NAME$', ucfirst(Str::singular($functionName)), $template);
275
276
        return $template;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $template returns the type string which is incompatible with the documented return type void.
Loading history...
277
    }
278
279
    /**
280
     * Prepare Relationship.
281
     *
282
     * @param Model       $relationship Relationship.
0 ignored issues
show
Bug introduced by
The type PWWEB\Artomator\Generators\GraphQL\Model was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
283
     * @param string|null $relationText Relation Text.
284
     *
285
     * @return array
286
     */
287
    protected function prepareRelationship($relationship, $relationText = null)
288
    {
289
        $singularRelation = (false === empty($relationship->relationName)) ? $relationship->relationName : Str::camel(Str::singular($relationText));
290
        $pluralRelation = (false === empty($relationship->relationName)) ? $relationship->relationName : Str::camel(Str::plural($relationText));
291
292
        switch ($relationship->type) {
293
            case '1t1':
294
                $functionName = $singularRelation;
295
                $template = '$FUNCTION_NAME$: $TYPE$$RELATION_GRAPHQL_NAME$';
296
                $templateFile = '';
297
298
                break;
299
            case '1tm':
300
                $functionName = $pluralRelation;
301
                $template = '$FUNCTION_NAME$: $TYPE$$RELATION_GRAPHQL_NAME$HasMany';
302
                $templateFile = 'hasMany';
303
304
                break;
305
            case 'mt1':
306
                if (false === empty($relationship->relationName)) {
307
                    $singularRelation = $relationship->relationName;
308
                } elseif (true === isset($relationship->inputs[1])) {
309
                    $singularRelation = Str::camel(str_replace('_id', '', strtolower($relationship->inputs[1])));
310
                }
311
                $functionName = $singularRelation;
312
                $template = '$FUNCTION_NAME$: $TYPE$$RELATION_GRAPHQL_NAME$BelongsTo';
313
                $templateFile = 'belongsTo';
314
315
                break;
316
            case 'mtm':
317
                $functionName = $pluralRelation;
318
                $template = '$FUNCTION_NAME$: $TYPE$$RELATION_GRAPHQL_NAME$BelongsToMany';
319
                $templateFile = 'belongsToMany';
320
321
                break;
322
            case 'hmt':
323
                $functionName = $pluralRelation;
324
                $template = '';
325
                $templateFile = '';
326
327
                break;
328
            default:
329
                $functionName = '';
330
                $template = '';
331
                $templateFile = '';
332
333
                break;
334
        }
335
        if (false === empty($templateFile)) {
336
            $templateFile = get_artomator_template('graphql.relations.'.$templateFile);
337
            $templateFile = str_replace('$RELATION_GRAPHQL_NAME$', ucfirst(Str::singular($functionName)), $templateFile);
338
339
            if (false === Str::contains($this->fileContents, $templateFile) && false === Str::contains($this->templateData, $templateFile)) {
340
                $this->templateData .= $templateFile;
341
            }
342
        }
343
344
        return compact('functionName', 'template');
345
    }
346
}
347