Passed
Push — master ( 1b0c60...f71ccb )
by Bruno
03:25
created

ModelGenerator::processGraphql()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 10

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 10
eloc 16
nc 6
nop 0
dl 0
loc 27
rs 7.6666
c 1
b 1
f 0
ccs 15
cts 15
cp 1
crap 10

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 declare(strict_types=1);
2
3
namespace Modelarium\Laravel\Targets;
4
5
use Formularium\Datatype;
6
use Formularium\Extradata;
7
use Formularium\ExtradataParameter;
8
use Formularium\Field;
9
use Formularium\Model;
10
use Illuminate\Support\Str;
11
use GraphQL\Type\Definition\ListOfType;
12
use GraphQL\Type\Definition\NonNull;
13
use GraphQL\Type\Definition\ObjectType;
14
use GraphQL\Type\Definition\UnionType;
15
use Modelarium\BaseGenerator;
16
use Modelarium\Datatypes\Datatype_relationship;
17
use Modelarium\Datatypes\RelationshipFactory;
18
use Modelarium\Exception\Exception;
19
use Modelarium\FormulariumUtils;
20
use Modelarium\GeneratedCollection;
21
use Modelarium\GeneratedItem;
22
use Modelarium\Parser;
23
use Modelarium\Types\FormulariumScalarType;
24
use Nette\PhpGenerator\Method;
25
26
class ModelGenerator extends BaseGenerator
27
{
28
    /**
29
     * @var string
30
     */
31
    protected $stubDir = __DIR__ . "/stubs/";
32
33
    /**
34
     * @var string
35
     */
36
    protected static $modelDir = 'app/Models/';
37
38
    /**
39
     * @var ObjectType
40
     */
41
    protected $type = null;
42
43
    /**
44
     * @var \Nette\PhpGenerator\ClassType
45
     */
46
    public $class = null;
47
48
    /**
49
     * fillable attributes
50
     *
51
     * @var array
52
     */
53
    public $fillable = [];
54
55
    /**
56
     * fillable attributes
57
     *
58
     * @var array
59
     */
60
    public $hidden = [];
61
62
    /**
63
     * cast attributes
64
     *
65
     * @var array
66
     */
67
    public $casts = [];
68
69
    /**
70
     *
71
     * @var string
72
     */
73
    public $parentClassName = '\Illuminate\Database\Eloquent\Model';
74
75
    /**
76
     * fields
77
     *
78
     * @var Model
79
     */
80
    public $fModel = null;
81
82
    /**
83
     *
84
     * @var array
85
     */
86
    public $traits = [];
87
88
    /**
89
     * Random generation
90
     *
91
     * @var Method
92
     */
93
    protected $methodRandom = null;
94
95
    /**
96
     * Do we have a 'can' attribute?
97
     *
98
     * @var boolean
99
     */
100
    protected $hasCan = true;
101
102
    /**
103
     * If true, we have timestamps on the migration.
104
     *
105
     * @var boolean
106
     */
107
    public $migrationTimestamps = false;
108
109 10
    public function generate(): GeneratedCollection
110
    {
111 10
        $this->fModel = Model::create($this->studlyName);
112 10
        $x = new GeneratedCollection([
113 10
            new GeneratedItem(
114 10
                GeneratedItem::TYPE_MODEL,
115 10
                $this->generateString(),
116 10
                $this->getGenerateFilename()
117
            ),
118 10
            new GeneratedItem(
119 10
                GeneratedItem::TYPE_MODEL,
120 10
                $this->templateStub('model'),
121 10
                $this->getGenerateFilename(false),
122 10
                true
123
            )
124
        ]);
125 10
        return $x;
126
    }
127
128 10
    protected function processField(
129
        string $typeName,
130
        \GraphQL\Type\Definition\FieldDefinition $field,
131
        \GraphQL\Language\AST\NodeList $directives,
132
        bool $isRequired
133
    ): void {
134 10
        $fieldName = $field->name;
135
136 10
        if ($typeName === 'ID') {
137 10
            return;
138
        }
139
140 9
        $scalarType = $this->parser->getScalarType($typeName);
141
142
        /**
143
         * @var Field $field
144
         */
145 9
        $field = null;
146 9
        if (!$scalarType) {
147
            // probably another model
148 7
            $field = FormulariumUtils::getFieldFromDirectives(
149 7
                $fieldName,
150 7
                $typeName,
151 7
                $directives
152
            );
153 5
        } elseif ($scalarType instanceof FormulariumScalarType) {
154 5
            $field = FormulariumUtils::getFieldFromDirectives(
155 5
                $fieldName,
156 5
                $scalarType->getDatatype()->getName(),
157 5
                $directives
158
            );
159
        } else {
160
            return;
161
        }
162
163 9
        if ($isRequired) {
164 8
            $field->setValidatorOption(
165 8
                Datatype::REQUIRED,
166 8
                'value',
167 8
                true
168
            );
169
        }
170
171 9
        $this->fModel->appendField($field);
172 9
    }
173
174 10
    protected function processFieldDirectives(
175
        \GraphQL\Type\Definition\FieldDefinition $field,
176
        \GraphQL\Language\AST\NodeList $directives
177
    ): void {
178 10
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
179
180 10
        foreach ($directives as $directive) {
181
            $name = $directive->name->value;
182
            $className = $this->getDirectiveClass($name);
183
            if ($className) {
184
                $methodName = "$className::processModelFieldDirective";
185
                /** @phpstan-ignore-next-line */
186
                $methodName(
187
                    $this,
188
                    $field,
189
                    $directive
190
                );
191
            }
192
        }
193
194 10
        $typeName = $type->name;
195 10
        $this->processField($typeName, $field, $directives, $isRequired);
196 10
    }
197
198 8
    protected function processRelationship(
199
        \GraphQL\Type\Definition\FieldDefinition $field,
200
        \GraphQL\Language\AST\NodeList $directives
201
    ): void {
202 8
        $lowerName = mb_strtolower($this->getInflector()->singularize($field->name));
203 8
        $lowerNamePlural = $this->getInflector()->pluralize($lowerName);
204
205 8
        $targetClass = '\\App\\Models\\' . Str::studly($this->getInflector()->singularize($field->name));
206
207 8
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
208 8
        $typeName = $type->name;
209
210
        // special types that should be skipped.
211 8
        if ($typeName === 'Can') {
212
            $this->hasCan = true;
213
            return;
214
        }
215
216 8
        $relationshipDatatype = null;
217
218 8
        $generateRandom = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $generateRandom is dead and can be removed.
Loading history...
219 8
        $sourceTypeName = $this->lowerName;
220 8
        $targetTypeName = $lowerName;
221 8
        $relationship = null;
222 8
        $isInverse = false;
223
224 8
        foreach ($directives as $directive) {
225 8
            $name = $directive->name->value;
226 8
            $className = $this->getDirectiveClass($name);
227 8
            if ($className) {
228 5
                $methodName = "$className::processModelFieldDirective";
229
                /** @phpstan-ignore-next-line */
230 5
                $methodName(
231 5
                    $this,
232
                    $field,
233
                    $directive
234
                );
235
236 5
                $methodName = "$className::processModelRelationshipDirective";
237
                /** @phpstan-ignore-next-line */
238 5
                $r = $methodName(
239 5
                    $this,
240
                    $field,
241
                    $directive
242
                );
243 5
                if ($r) {
244 5
                    if ($relationshipDatatype) {
245
                        throw new Exception("Overwrting relationship in {$typeName} for {$field->name} in {$this->lowerName}");
246
                    }
247 5
                    $relationshipDatatype = $r;
248
                }
249 5
                continue;
250
            }
251
252
            // TODO: convert to separate classes
253 7
            switch ($name) {
254 7
            case 'hasOne':
255 3
                $relationship = RelationshipFactory::RELATIONSHIP_ONE_TO_ONE;
256 3
                $isInverse = false;
257 3
                $this->class->addMethod($lowerName)
258 3
                    ->setPublic()
259 3
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\HasOne')
260 3
                    ->setBody("return \$this->hasOne($targetClass::class);");
261 3
                break;
262
263 7
            case 'hasMany':
264 1
                $relationship = RelationshipFactory::RELATIONSHIP_ONE_TO_MANY;
265 1
                $isInverse = false;
266 1
                $target = $this->getInflector()->singularize($targetClass);
267 1
                $this->class->addMethod($lowerNamePlural)
268 1
                    ->setPublic()
269 1
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\HasMany')
270 1
                    ->setBody("return \$this->hasMany($target::class);");
271 1
                break;
272
273 7
            case 'morphOne':
274 7
            case 'morphMany':
275 7
            case 'morphToMany':
276 3
                if ($name === 'morphOne') {
277 1
                    $relationship = RelationshipFactory::MORPH_ONE_TO_ONE;
278
                } else {
279 2
                    $relationship = RelationshipFactory::MORPH_ONE_TO_MANY;
280
                }
281 3
                $isInverse = false;
282
283 3
                $targetType = $this->parser->getType($typeName);
284 3
                if (!$targetType) {
285
                    throw new Exception("Cannot get type {$typeName} as a relationship to {$this->baseName}");
286 3
                } elseif (!($targetType instanceof ObjectType)) {
287
                    throw new Exception("{$typeName} is not a type for a relationship to {$this->baseName}");
288
                }
289 3
                $targetField = null;
290 3
                foreach ($targetType->getFields() as $subField) {
291 3
                    $subDir = Parser::getDirectives($subField->astNode->directives);
292 3
                    if (array_key_exists('morphTo', $subDir) || array_key_exists('morphedByMany', $subDir)) {
293 3
                        $targetField = $subField->name;
294 3
                        break;
295
                    }
296
                }
297 3
                if (!$targetField) {
298
                    throw new Exception("{$targetType} does not have a '@morphTo' or '@morphToMany' field");
299
                }
300
301 3
                $this->class->addMethod($field->name)
302
                    // TODO: return type
303 3
                    ->setPublic()
304 3
                    ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
305 3
                break;
306
    
307 7
            case 'morphTo':
308 2
                $relationship = RelationshipFactory::MORPH_ONE_TO_MANY; // TODO
309 2
                $isInverse = true;
310 2
                $this->class->addMethod($field->name)
311 2
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\MorphTo')
312 2
                    ->setPublic()
313 2
                    ->setBody("return \$this->morphTo();");
314 2
                break;
315
316 5
            case 'morphedByMany':
317 1
                $relationship = RelationshipFactory::MORPH_MANY_TO_MANY; // TODO
318 1
                $isInverse = true;
319 1
                $typeMap = $this->parser->getSchema()->getTypeMap();
320
       
321 1
                foreach ($typeMap as $name => $object) {
322 1
                    if (!($object instanceof ObjectType) || $name === 'Query' || $name === 'Mutation' || $name === 'Subscription') {
323 1
                        continue;
324
                    }
325
326
                    /**
327
                     * @var ObjectType $object
328
                     */
329
330 1
                    if (str_starts_with((string)$name, '__')) {
331
                        // internal type
332 1
                        continue;
333
                    }
334
335 1
                    foreach ($object->getFields() as $subField) {
336 1
                        $subDirectives = Parser::getDirectives($subField->astNode->directives);
337
338 1
                        if (!array_key_exists('morphToMany', $subDirectives)) {
339 1
                            continue;
340
                        }
341
342 1
                        $methodName = $this->getInflector()->pluralize(mb_strtolower((string)$name));
343 1
                        $this->class->addMethod($methodName)
344 1
                                ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\MorphToMany')
345 1
                                ->setPublic()
346 1
                                ->setBody("return \$this->morphedByMany($name::class, '$lowerName');");
347
                    }
348
                }
349 1
                break;
350
            
351
            default:
352 4
                break;
353
            }
354
        }
355 8
        if (!$relationship) {
356
            // TODO: generate a warning, perhaps?
357
            // throw new Exception("Could not find a relationship in {$typeName} for {$field->name} in {$sourceTypeName}");
358 5
            return;
359
        }
360
361 7
        if (!$relationshipDatatype) {
362 7
            $relationshipDatatype = "relationship:" . ($isInverse ? "inverse:" : "") .
363 7
               "$relationship:$sourceTypeName:$targetTypeName";
364
        }
365
366 7
        $this->processField($relationshipDatatype, $field, $directives, $isRequired);
367
368
        // TODO
369
        // if ($generateRandom) {
370
        //     if ($relationship == RelationshipFactory::RELATIONSHIP_MANY_TO_MANY || $relationship == RelationshipFactory::MORPH_MANY_TO_MANY) {
371
        //         // TODO: do we generate it? seed should do it?
372
        //     } else {
373
        //         $this->methodRandom->addBody(
374
        //             '$data["' . $lowerName . '_id"] = function () {' . "\n" .
375
        //         '    return factory(' . $targetClass . '::class)->create()->id;'  . "\n" .
376
        //         '};'
377
        //         );
378
        //     }
379
        // }
380 7
    }
381
382 10
    protected function processDirectives(
383
        \GraphQL\Language\AST\NodeList $directives
384
    ): void {
385 10
        foreach ($directives as $directive) {
386 1
            $name = $directive->name->value;
387 1
            $this->fModel->appendExtradata(FormulariumUtils::directiveToExtradata($directive));
388
389 1
            $className = $this->getDirectiveClass($name);
390 1
            if ($className) {
391 1
                $methodName = "$className::processModelTypeDirective";
392
                /** @phpstan-ignore-next-line */
393 1
                $methodName(
394 1
                    $this,
395
                    $directive
396
                );
397
            }
398
        }
399 10
    }
400
401 10
    public function generateString(): string
402
    {
403 10
        $namespace = new \Nette\PhpGenerator\PhpNamespace('App\\Models');
404 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\BelongsTo');
405 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\HasOne');
406 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\HasMany');
407 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphTo');
408 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphOne');
409 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphToMany');
410 10
        $namespace->addUse('\\Illuminate\\Support\\Facades\\Auth');
411 10
        $namespace->addUse('\\Formularium\\Exception\\NoRandomException');
412 10
        $namespace->addUse('\\Modelarium\\Laravel\\Datatypes\\Datatype_relationship');
413
414 10
        $this->class = $namespace->addClass('Base' . $this->studlyName);
415 10
        $this->class
416 10
            ->addComment("This file was automatically generated by Modelarium.")
417 10
            ->setAbstract();
418
419 10
        $this->methodRandom = new Method('getRandomData');
420 10
        $this->methodRandom->addBody(
421 10
            '$data = static::getFormularium()->getRandom(get_called_class() . \'::getRandomFieldData\');' . "\n"
422
        );
423
424 10
        $this->processGraphql();
425
426
        // this might have changed
427 10
        $this->class->setExtends($this->parentClassName);
428
429 10
        foreach ($this->traits as $trait) {
430 1
            $this->class->addTrait($trait);
431
        }
432
433 10
        $this->class->addProperty('fillable')
434 10
            ->setProtected()
435 10
            ->setValue($this->fillable)
436 10
            ->setComment("The attributes that are mass assignable.\n@var array")
437 10
            ->setInitialized();
438
439 10
        $this->class->addProperty('hidden')
440 10
            ->setProtected()
441 10
            ->setValue($this->hidden)
442 10
            ->setComment("The attributes that should be hidden for arrays.\n@var array")
443 10
            ->setInitialized();
444
445 10
        if (!$this->migrationTimestamps) {
446 9
            $this->class->addProperty('timestamps')
447 9
                ->setPublic()
448 9
                ->setValue(false)
449 9
                ->setComment("Do not set timestamps.\n@var boolean")
450 9
                ->setInitialized();
451
        }
452
453 10
        if ($this->casts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->casts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
454
            $this->class->addProperty('casts')
455
                ->setProtected()
456
                ->setValue($this->casts)
457
                ->setComment("The attributes that should be cast.\n@var array")
458
                ->setInitialized();
459
        }
460
461 10
        $this->class->addMethod('getFields')
462 10
            ->setPublic()
463 10
            ->setStatic()
464 10
            ->setReturnType('array')
465 10
            ->addComment('@return array')
466 10
            ->addBody(
467 10
                "return ?;\n",
468
                [
469 10
                    $this->fModel->serialize()
470
                ]
471
            );
472
473 10
        $this->class->addMethod('getFormularium')
474 10
            ->setPublic()
475 10
            ->setStatic()
476 10
            ->setReturnType('\Formularium\Model')
477 10
            ->addComment('@return \Formularium\Model')
478 10
            ->addBody(
479
                '$model = \Formularium\Model::fromStruct(static::getFields());' . "\n" .
480 10
                'return $model;',
481
                [
482
                    //$this->studlyName,
483 10
                ]
484
            );
485
        
486 10
        $this->methodRandom
487 10
            ->addComment('@return array')
488 10
            ->setPublic()
489 10
            ->setStatic()
490 10
            ->setReturnType('array')
491 10
            ->addBody('return $data;');
492 10
        $this->class->addMember($this->methodRandom);
493
494 10
        $this->class->addMethod('getRandomFieldData')
495 10
            ->setPublic()
496 10
            ->setStatic()
497 10
            ->addComment("Filters fields and generate random data. Throw NoRandomException for fields you don't want to generate random data, or return a valid value.")
498 10
            ->addBody('
499
$d = $f->getDatatype();
500
if ($d instanceof Datatype_relationship) {
501
    throw new NoRandomException($f->getName());
502
}
503
return $f->getDatatype()->getRandom();')
504 10
            ->addParameter('f')->setType('Formularium\Field');
505
506
        // TODO perhaps we can use PolicyGenerator->policyClasses to auto generate
507 10
        if ($this->hasCan) {
508 10
            $this->class->addMethod('getCanAttribute')
509 10
                ->setPublic()
510 10
                ->setReturnType('array')
511 10
                ->addComment("Returns the policy permissions for actions such as editing or deleting.\n@return \Formularium\Model")
512 10
                ->addBody(
513 10
                    '$policy = new \\App\\Policies\\' . $this->studlyName . 'Policy();' . "\n" .
514 10
                    '$user = Auth::user();' . "\n" .
515 10
                    'return [' . "\n" .
516 10
                    '    //[ "ability" => "create", "value" => $policy->create($user) ]' . "\n" .
517 10
                    '];'
518
                );
519
        }
520
        
521 10
        $printer = new \Nette\PhpGenerator\PsrPrinter;
522 10
        return $this->phpHeader() . $printer->printNamespace($namespace);
523
    }
524
525 10
    protected function processGraphql(): void
526
    {
527 10
        foreach ($this->type->getFields() as $field) {
528 10
            $directives = $field->astNode->directives;
529
            if (
530 10
                ($field->type instanceof ObjectType) ||
531 10
                ($field->type instanceof ListOfType) ||
532 10
                ($field->type instanceof UnionType) ||
533 10
                ($field->type instanceof NonNull && (
534 10
                    ($field->type->getWrappedType() instanceof ObjectType) ||
535 10
                    ($field->type->getWrappedType() instanceof ListOfType) ||
536 10
                    ($field->type->getWrappedType() instanceof UnionType)
537
                ))
538
            ) {
539
                // relationship
540 8
                $this->processRelationship($field, $directives);
541
            } else {
542 10
                $this->processFieldDirectives($field, $directives);
543
            }
544
        }
545
546
        /**
547
         * @var \GraphQL\Language\AST\NodeList|null
548
         */
549 10
        $directives = $this->type->astNode->directives;
550 10
        if ($directives) {
551 10
            $this->processDirectives($directives);
0 ignored issues
show
Bug introduced by
$directives of type GraphQL\Language\AST\DirectiveNode[] is incompatible with the type GraphQL\Language\AST\NodeList expected by parameter $directives of Modelarium\Laravel\Targe...or::processDirectives(). ( Ignorable by Annotation )

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

551
            $this->processDirectives(/** @scrutinizer ignore-type */ $directives);
Loading history...
552
        }
553 10
    }
554
555 10
    public function getGenerateFilename(bool $base = true): string
556
    {
557 10
        return $this->getBasePath(self::$modelDir . '/' . ($base ? 'Base' : '') . $this->studlyName . '.php');
558
    }
559
560
    public static function setModelDir(string $dir): void
561
    {
562
        self::$modelDir = $dir;
563
    }
564
}
565