Passed
Push — master ( 2fa866...3020a3 )
by Bruno
07:44
created

ModelGenerator::directiveToExtradata()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 4.3145

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 13
ccs 1
cts 6
cp 0.1666
rs 10
cc 2
nc 2
nop 1
crap 4.3145
1
<?php declare(strict_types=1);
2
3
namespace Modelarium\Laravel\Targets;
4
5
use Formularium\Datatype;
6
use Formularium\Extradata;
0 ignored issues
show
Bug introduced by
The type Formularium\Extradata 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...
7
use Formularium\ExtradataParameter;
0 ignored issues
show
Bug introduced by
The type Formularium\ExtradataParameter 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...
8
use Formularium\Model;
9
use Illuminate\Support\Str;
10
use GraphQL\Type\Definition\ListOfType;
11
use GraphQL\Type\Definition\NonNull;
12
use GraphQL\Type\Definition\ObjectType;
13
use GraphQL\Type\Definition\UnionType;
14
use Modelarium\BaseGenerator;
15
use Modelarium\Datatypes\Datatype_relationship;
16
use Modelarium\Datatypes\RelationshipFactory;
17
use Modelarium\Exception\Exception;
18
use Modelarium\FormulariumUtils;
19
use Modelarium\GeneratedCollection;
20
use Modelarium\GeneratedItem;
21
use Modelarium\Parser;
22
use Modelarium\Types\FormulariumScalarType;
23
use Nette\PhpGenerator\Method;
24
use GraphQL\Language\AST\DirectiveNode;
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
    protected $class = null;
47
48
    /**
49
     * fillable attributes
50
     *
51
     * @var array
52
     */
53
    protected $fillable = [];
54
55
    /**
56
     * fillable attributes
57
     *
58
     * @var array
59
     */
60
    protected $hidden = [];
61
62
    /**
63
     * cast attributes
64
     *
65
     * @var array
66
     */
67
    protected $casts = [];
68
69
    /**
70
     *
71
     * @var string
72
     */
73
    protected $parentClassName = '\Illuminate\Database\Eloquent\Model';
74
75
    /**
76
     * fields
77
     *
78
     * @var Model
79
     */
80
    protected $fModel = null;
81
82
    /**
83
     *
84
     * @var array
85 8
     */
86
    protected $traits = [];
87 8
88 8
    /**
89 8
     * cast attributes
90 8
     *
91 8
     * @var Method
92
     */
93 8
    protected $methodRandom = null;
94 8
95 8
    public function generate(): GeneratedCollection
96 8
    {
97 8
        $this->fModel = Model::create($this->studlyName);
98
        $x = new GeneratedCollection([
99
            new GeneratedItem(
100 8
                GeneratedItem::TYPE_MODEL,
101
                $this->generateString(),
102
                $this->getGenerateFilename()
103 10
            ),
104
            new GeneratedItem(
105
                GeneratedItem::TYPE_MODEL,
106
                $this->templateStub('model'),
107
                $this->getGenerateFilename(false),
108
                true
109 10
            )
110
        ]);
111 10
        return $x;
112 10
    }
113
114
    protected function processField(
115 10
        string $typeName,
116
        \GraphQL\Type\Definition\FieldDefinition $field,
117 10
        \GraphQL\Language\AST\NodeList $directives,
118 10
        bool $isRequired
119
    ): void {
120 8
        $fieldName = $field->name;
121 8
122 8
        if ($typeName === 'ID') {
123 8
            return;
124
        }
125 5
126 5
        $scalarType = $this->parser->getScalarType($typeName);
127 5
128 5
        /**
129 5
         * @var Field $field
130
         */
131
        $field = null;
132
        if (!$scalarType) {
133
            // probably another model
134
            $field = FormulariumUtils::getFieldFromDirectives(
135 10
                $fieldName,
136 10
                $typeName,
137 10
                $directives
138 10
            );
139 10
        } elseif ($scalarType instanceof FormulariumScalarType) {
140
            $field = FormulariumUtils::getFieldFromDirectives(
141
                $fieldName,
142
                $scalarType->getDatatype()->getName(),
143 10
                $directives
144 10
            );
145
        } else {
146 10
            return;
147
        }
148
149
        if ($isRequired) {
150 10
            $field->setValidatorOption(
151
                Datatype::REQUIRED,
152 10
                'value',
153
                true
154 10
            );
155
        }
156
157
        $this->fModel->appendField($field);
158
    }
159
160
    protected function processBasetype(
161
        \GraphQL\Type\Definition\FieldDefinition $field,
162
        \GraphQL\Language\AST\NodeList $directives
163
    ): void {
164
        $fieldName = $field->name;
165
166
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
167
168
        foreach ($directives as $directive) {
169
            $name = $directive->name->value;
170
            switch ($name) {
171
            case 'modelFillable':
172
                $this->fillable[] = $fieldName;
173
                break;
174
            case 'modelHidden':
175
                $this->hidden[] = $fieldName;
176
                break;
177
            case 'casts':
178
                foreach ($directive->arguments as $arg) {
179
                    /**
180 10
                     * @var \GraphQL\Language\AST\ArgumentNode $arg
181 10
                     */
182 10
183
                    $value = $arg->value->value;
0 ignored issues
show
Bug introduced by
Accessing value on the interface GraphQL\Language\AST\ValueNode suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
184 8
185
                    switch ($arg->name->value) {
186
                    case 'type':
187
                        $this->casts[$fieldName] = $value;
188 8
                    }
189 8
                }
190
                break;
191 8
            }
192
        }
193 8
194 8
        $typeName = $type->name;
195
        $this->processField($typeName, $field, $directives, $isRequired);
196
    }
197 8
198
    protected function processRelationship(
199
        \GraphQL\Type\Definition\FieldDefinition $field,
200
        \GraphQL\Language\AST\NodeList $directives
201 8
    ): void {
202 8
        $lowerName = mb_strtolower($this->getInflector()->singularize($field->name));
203 8
        $lowerNamePlural = $this->getInflector()->pluralize($lowerName);
204 8
205
        $targetClass = '\\App\\Models\\' . Str::studly($this->getInflector()->singularize($field->name));
206 8
207 8
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
208 8
        $typeName = $type->name;
209 8
210 4
        // special types that should be skipped.
211 4
        if ($typeName === 'Can') {
212 4
            return;
213 4
        }
214 4
215 4
        $generateRandom = false;
216 4
        $sourceTypeName = $this->lowerName;
217
        $targetTypeName = $lowerName;
218 8
        $relationship = null;
219 1
        $isInverse = false;
220 1
221 1
        foreach ($directives as $directive) {
222 1
            $name = $directive->name->value;
223 1
            switch ($name) {
224 1
            case 'belongsTo':
225 1
                $generateRandom = true;
226
                $relationship = RelationshipFactory::RELATIONSHIP_ONE_TO_MANY;
227 7
                $isInverse = true;
228 3
                $this->class->addMethod($lowerName)
229 3
                    ->setPublic()
230 3
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\BelongsTo')
231 3
                    ->setBody("return \$this->belongsTo($targetClass::class);");
232 3
                break;
233 3
234
            case 'belongsToMany':
235 7
                $generateRandom = true;
236 1
                $relationship = RelationshipFactory::RELATIONSHIP_MANY_TO_MANY;
237 1
                $isInverse = true;
238 1
                $this->class->addMethod($lowerNamePlural)
239 1
                    ->setPublic()
240 1
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany')
241 1
                    ->setBody("return \$this->belongsToMany($targetClass::class);");
242 1
                break;
243
244 7
            case 'hasOne':
245 7
                $relationship = RelationshipFactory::RELATIONSHIP_ONE_TO_ONE;
246 7
                $isInverse = false;
247 3
                $this->class->addMethod($lowerName)
248 1
                    ->setPublic()
249
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\HasOne')
250 2
                    ->setBody("return \$this->hasOne($targetClass::class);");
251
                break;
252
253 3
            case 'hasMany':
254 3
                $relationship = RelationshipFactory::RELATIONSHIP_ONE_TO_MANY;
255
                $isInverse = false;
256 3
                $target = $this->getInflector()->singularize($targetClass);
257
                $this->class->addMethod($lowerNamePlural)
258
                    ->setPublic()
259 3
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\HasMany')
260 3
                    ->setBody("return \$this->hasMany($target::class);");
261 3
                break;
262 3
263 3
            case 'morphOne':
264 3
            case 'morphMany':
265
            case 'morphToMany':
266
                if ($name === 'morphOne') {
267 3
                    $relationship = RelationshipFactory::MORPH_ONE_TO_ONE;
268
                } else {
269
                    $relationship = RelationshipFactory::MORPH_ONE_TO_MANY;
270
                }
271 3
                $isInverse = false;
272
273 3
                $targetType = $this->parser->getType($typeName);
274 3
                if (!$targetType) {
275 3
                    throw new Exception("Cannot get type {$typeName} as a relationship to {$this->baseName}");
276
                } elseif (!($targetType instanceof ObjectType)) {
277 7
                    throw new Exception("{$typeName} is not a type for a relationship to {$this->baseName}");
278 2
                }
279 2
                $targetField = null;
280 2
                foreach ($targetType->getFields() as $subField) {
281 2
                    $subDir = Parser::getDirectives($subField->astNode->directives);
282 2
                    if (array_key_exists('morphTo', $subDir) || array_key_exists('morphedByMany', $subDir)) {
283 2
                        $targetField = $subField->name;
284
                        break;
285 5
                    }
286 1
                }
287 1
                if (!$targetField) {
288
                    throw new Exception("{$targetType} does not have a '@morphTo' or '@morphToMany' field");
289 1
                }
290 1
291 1
                $this->class->addMethod($field->name)
292
                    // TODO: return type
293
                    ->setPublic()
294
                    ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
295
                break;
296
    
297
            case 'morphTo':
298 1
                $relationship = RelationshipFactory::MORPH_ONE_TO_MANY; // TODO
299
                $isInverse = true;
300 1
                $this->class->addMethod($field->name)
301
                    ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\MorphTo')
302
                    ->setPublic()
303 1
                    ->setBody("return \$this->morphTo();");
304 1
                break;
305
306 1
            case 'morphedByMany':
307 1
                $relationship = RelationshipFactory::MORPH_MANY_TO_MANY; // TODO
308
                $isInverse = true;
309
                $typeMap = $this->parser->getSchema()->getTypeMap();
310 1
       
311 1
                foreach ($typeMap as $name => $object) {
312 1
                    if (!($object instanceof ObjectType) || $name === 'Query' || $name === 'Mutation' || $name === 'Subscription') {
313 1
                        continue;
314 1
                    }
315
316
                    /**
317 1
                     * @var ObjectType $object
318
                     */
319
320 4
                    if (str_starts_with((string)$name, '__')) {
321
                        // internal type
322
                        continue;
323 8
                    }
324
325
                    foreach ($object->getFields() as $subField) {
326
                        $subDirectives = Parser::getDirectives($subField->astNode->directives);
327 8
328
                        if (!array_key_exists('morphToMany', $subDirectives)) {
329 8
                            continue;
330
                        }
331 8
332 5
                        $methodName = $this->getInflector()->pluralize(mb_strtolower((string)$name));
333 5
                        $this->class->addMethod($methodName)
334 5
                                ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\MorphToMany')
335 5
                                ->setPublic()
336
                                ->setBody("return \$this->morphedByMany($name::class, '$lowerName');");
337
                    }
338 8
                }
339
                break;
340 10
            
341
            default:
342
                break;
343 10
            }
344 1
        }
345 1
        if (!$relationship) {
346 1
            throw new Exception("Could not find a relationship in {$typeName}");
347 1
        }
348 1
349 1
        $relationshipDatatype = "relationship:" . ($isInverse ? "inverse:" : "") .
350
            "$relationship:$sourceTypeName:$targetTypeName";
351
352 1
        $this->processField($relationshipDatatype, $field, $directives, $isRequired);
353
354
        if ($generateRandom) {
355 1
            if ($relationship == RelationshipFactory::RELATIONSHIP_MANY_TO_MANY || $relationship == RelationshipFactory::MORPH_MANY_TO_MANY) {
356 1
                // TODO: do we generate it? seed should do it?
357 1
            } else {
358 1
                $this->methodRandom->addBody(
359
                    '$data["' . $lowerName . '_id"] = function () {' . "\n" .
360
                '    return factory(' . $targetClass . '::class)->create()->id;'  . "\n" .
361
                '};'
362
                );
363
            }
364
        }
365
    }
366
367
    protected function processDirectives(
368
        \GraphQL\Language\AST\NodeList $directives
369
    ): void {
370
        foreach ($directives as $directive) {
371
            $name = $directive->name->value;
372
            $this->fModel->appendExtradata(FormulariumUtils::directiveToExtradata($directive));
0 ignored issues
show
Bug introduced by
The method appendExtradata() does not exist on Formularium\Model. ( Ignorable by Annotation )

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

372
            $this->fModel->/** @scrutinizer ignore-call */ 
373
                           appendExtradata(FormulariumUtils::directiveToExtradata($directive));

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...
373 10
374
            switch ($name) {
375
            case 'migrationSoftDeletes':
376
                $this->traits[] = '\Illuminate\Database\Eloquent\SoftDeletes';
377
                break;
378
            case 'modelNotifiable':
379
                $this->traits[] = '\Illuminate\Notifications\Notifiable';
380
                break;
381
            case 'modelMustVerifyEmail':
382
                $this->traits[] = '\Illuminate\Notifications\MustVerifyEmail';
383
                break;
384
            case 'migrationRememberToken':
385
                $this->hidden[] = 'remember_token';
386
                break;
387
            case 'modelExtends':
388
                foreach ($directive->arguments as $arg) {
389
                    /**
390
                     * @var \GraphQL\Language\AST\ArgumentNode $arg
391
                     */
392
393 10
                    $value = $arg->value->value;
0 ignored issues
show
Bug introduced by
Accessing value on the interface GraphQL\Language\AST\ValueNode suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
394
395 10
                    switch ($arg->name->value) {
396 10
                    case 'class':
397 10
                        $this->parentClassName = $value;
398 10
                    }
399 10
                }
400 10
            }
401 10
        }
402
    }
403 10
404 10
    public function generateString(): string
405 10
    {
406 10
        $namespace = new \Nette\PhpGenerator\PhpNamespace('App\\Models');
407
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\BelongsTo');
408 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\HasOne');
409 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\HasMany');
410 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphTo');
411
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphToMany');
412
        $namespace->addUse('\\Illuminate\\Support\\Facades\\Auth');
413 10
        $namespace->addUse('\\Modelarium\\Laravel\\Datatypes\\Datatype_relationship');
414
415 10
        $this->class = $namespace->addClass('Base' . $this->studlyName);
416 1
        $this->class
417
            ->addComment("This file was automatically generated by Modelarium.")
418
            ->setAbstract();
419 10
420 10
        $this->methodRandom = new Method('getRandomData');
421 10
        $this->methodRandom->addBody(
422 10
            '$data = static::getFormularium()->getRandom(get_called_class() . \'::getRandomDataFilterFields\');' . "\n"
423 10
        );
424
425 10
        $this->processGraphql();
426 10
427 10
        // this might have changed
428 10
        $this->class->setExtends($this->parentClassName);
429 10
430
        foreach ($this->traits as $trait) {
431 10
            $this->class->addTrait($trait);
432 10
        }
433 10
434 10
        $this->class->addProperty('fillable')
435 10
            ->setProtected()
436
            ->setValue($this->fillable)
437 10
            ->setComment("The attributes that are mass assignable.\n@var array")
438 10
            ->setInitialized();
439 10
440 10
        $this->class->addProperty('hidden')
441 10
            ->setProtected()
442 10
            ->setValue($this->hidden)
443 10
            ->setComment("The attributes that should be hidden for arrays.\n@var array")
444
            ->setInitialized();
445 10
446
        $this->class->addProperty('casts')
447
            ->setProtected()
448
            ->setValue($this->casts)
449 10
            ->setComment("The attributes that should be cast to native types.\n@var array")
450 10
            ->setInitialized();
451 10
452 10
        $this->class->addMethod('getFields')
453 10
            ->setPublic()
454 10
            ->setStatic()
455
            ->setReturnType('array')
456 10
            ->addComment('@return array')
457
            ->addBody(
458 10
                "return ?;\n",
459
                [
460
                    $this->fModel->serialize()
461
                ]
462 10
            );
463 10
464 10
        $this->class->addMethod('getFormularium')
465 10
            ->setPublic()
466 10
            ->setStatic()
467 10
            ->setReturnType('\Formularium\Model')
468 10
            ->addComment('@return \Formularium\Model')
469
            ->addBody(
470
                '$model = \Formularium\Model::fromStruct(static::getFields());' . "\n" .
471 10
                'return $model;',
472 10
                [
473 10
                    //$this->studlyName,
474 10
                ]
475 10
            );
476 10
        
477 10
        $this->methodRandom
478 10
            ->addComment('@return array')
479 10
            ->setPublic()
480 10
            ->setStatic()
481
            ->setReturnType('array')
482
            ->addBody('return $data;');
483 10
        $this->class->addMember($this->methodRandom);
484 10
485
        $this->class->addMethod('getRandomDataFilterFields')
486
            ->setPublic()
487 10
            ->setStatic()
488
            ->setReturnType('bool')
489 10
            ->addComment("Filters fields used for random data generation.")
490 10
            ->addBody('
491
$d = $f->getDatatype();
492 10
if ($d instanceof Datatype_relationship) {
493 10
    return false;
494 10
}
495 10
return true;')
496 10
            ->addParameter('f')->setType('Formularium\Field');
497 10
498 10
        // TODO perhaps we can use PolicyGenerator->policyClasses to auto generate
499
        $this->class->addMethod('getCanAttribute')
500
            ->setPublic()
501
            ->setReturnType('array')
502 8
            ->addComment("Returns the policy permissions for actions such as editing or deleting.\n@return \Formularium\Model")
503
            ->addBody(
504 10
                '$policy = new \\App\\Policies\\' . $this->studlyName . 'Policy();' . "\n" .
505
                '$user = Auth::user();' . "\n" .
506
                'return [' . "\n" .
507
                '    //[ "ability" => "create", "value" => $policy->create($user) ]' . "\n" .
508
                '];'
509
            );
510
        
511 10
        $printer = new \Nette\PhpGenerator\PsrPrinter;
512 10
        return $this->phpHeader() . $printer->printNamespace($namespace);
513 10
    }
514
515 10
    protected function processGraphql(): void
516
    {
517 8
        foreach ($this->type->getFields() as $field) {
518
            $directives = $field->astNode->directives;
519 8
            if (
520
                ($field->type instanceof ObjectType) ||
521
                ($field->type instanceof ListOfType) ||
522
                ($field->type instanceof UnionType) ||
523
                ($field->type instanceof NonNull && (
524
                    ($field->type->getWrappedType() instanceof ObjectType) ||
525
                    ($field->type->getWrappedType() instanceof ListOfType) ||
526
                    ($field->type->getWrappedType() instanceof UnionType)
527
                ))
528
            ) {
529
                // relationship
530
                $this->processRelationship($field, $directives);
531
            } else {
532
                $this->processBasetype($field, $directives);
533
            }
534
        }
535
536
        /**
537
         * @var \GraphQL\Language\AST\NodeList|null
538
         */
539
        $directives = $this->type->astNode->directives;
540
        if ($directives) {
541
            $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

541
            $this->processDirectives(/** @scrutinizer ignore-type */ $directives);
Loading history...
542
        }
543
    }
544
545
    public function getGenerateFilename(bool $base = true): string
546
    {
547
        return $this->getBasePath(self::$modelDir . '/' . ($base ? 'Base' : '') . $this->studlyName . '.php');
548
    }
549
550
    public static function setModelDir(string $dir): void
551
    {
552
        self::$modelDir = $dir;
553
    }
554
}
555