Passed
Push — master ( c0a95b...c5e7d6 )
by Bruno
04:51
created

ModelGenerator   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 445
Duplicated Lines 0 %

Test Coverage

Coverage 89.76%

Importance

Changes 26
Bugs 11 Features 1
Metric Value
eloc 214
dl 0
loc 445
ccs 184
cts 205
cp 0.8976
rs 9.1199
c 26
b 11
f 1
wmc 41

10 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 17 1
A processField() 0 44 5
A processFieldDirectives() 0 22 3
A processDirectives() 0 14 3
B generateString() 0 122 5
A setModelDir() 0 3 1
A getGenerateFilename() 0 3 2
A getRelationshipDatatypeName() 0 8 2
B processRelationship() 0 67 9
B processGraphql() 0 27 10

How to fix   Complexity   

Complex Class

Complex classes like ModelGenerator 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 ModelGenerator, and based on these observations, apply Extract Interface, too.

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 10
        $scalarType = $this->parser->getScalarType($typeName);
141
142
        /**
143
         * @var Field $field
144
         */
145 10
        $field = null;
146 10
        if (!$scalarType) {
147
            // probably another model
148 8
            $field = FormulariumUtils::getFieldFromDirectives(
149 8
                $fieldName,
150 8
                $typeName,
151 8
                $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 10
        if ($isRequired) {
164 10
            $field->setValidatorOption(
165 10
                Datatype::REQUIRED,
166 10
                'value',
167 10
                true
168
            );
169
        }
170
171 10
        $this->fModel->appendField($field);
172 10
    }
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);
0 ignored issues
show
Unused Code introduced by
The assignment to $lowerNamePlural is dead and can be removed.
Loading history...
204
205 8
        $targetClass = '\\App\\Models\\' . Str::studly($this->getInflector()->singularize($field->name));
0 ignored issues
show
Unused Code introduced by
The assignment to $targetClass is dead and can be removed.
Loading history...
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 8
                $methodName = "$className::processModelFieldDirective";
229
                /** @phpstan-ignore-next-line */
230 8
                $methodName(
231 8
                    $this,
232
                    $field,
233
                    $directive
234
                );
235
236 8
                $methodName = "$className::processModelRelationshipDirective";
237
                /** @phpstan-ignore-next-line */
238 8
                $r = $methodName(
239 8
                    $this,
240
                    $field,
241
                    $directive
242
                );
243 8
                if ($r) {
244 8
                    if ($relationshipDatatype) {
245
                        throw new Exception("Overwrting relationship in {$typeName} for {$field->name} in {$this->lowerName}");
246
                    }
247 8
                    $relationshipDatatype = $r;
248
                }
249 8
                continue;
250
            }
251
        }
252
253 8
        if (!$relationshipDatatype) {
254
            if (!$relationship) {
0 ignored issues
show
introduced by
$relationship is of type null, thus it always evaluated to false.
Loading history...
255
                // TODO: generate a warning, perhaps?
256
                // throw new Exception("Could not find a relationship in {$typeName} for {$field->name} in {$sourceTypeName}");
257
                return;
258
            }
259
    
260
            $relationshipDatatype = "relationship:" . ($isInverse ? "inverse:" : "") .
261
               "$relationship:$sourceTypeName:$targetTypeName";
262
        }
263
264 8
        $this->processField($relationshipDatatype, $field, $directives, $isRequired);
265
266
        // TODO
267
        // if ($generateRandom) {
268
        //     if ($relationship == RelationshipFactory::RELATIONSHIP_MANY_TO_MANY || $relationship == RelationshipFactory::MORPH_MANY_TO_MANY) {
269
        //         // TODO: do we generate it? seed should do it?
270
        //     } else {
271
        //         $this->methodRandom->addBody(
272
        //             '$data["' . $lowerName . '_id"] = function () {' . "\n" .
273
        //         '    return factory(' . $targetClass . '::class)->create()->id;'  . "\n" .
274
        //         '};'
275
        //         );
276
        //     }
277
        // }
278 8
    }
279
280 8
    public static function getRelationshipDatatypeName(
281
        string $relationship,
282
        bool $isInverse,
283
        string $sourceTypeName,
284
        string $targetTypeName
285
    ): string {
286 8
        return "relationship:" . ($isInverse ? "inverse:" : "") .
287 8
            "$relationship:$sourceTypeName:$targetTypeName";
288
    }
289
290 10
    protected function processDirectives(
291
        \GraphQL\Language\AST\NodeList $directives
292
    ): void {
293 10
        foreach ($directives as $directive) {
294 1
            $name = $directive->name->value;
295 1
            $this->fModel->appendExtradata(FormulariumUtils::directiveToExtradata($directive));
296
297 1
            $className = $this->getDirectiveClass($name);
298 1
            if ($className) {
299 1
                $methodName = "$className::processModelTypeDirective";
300
                /** @phpstan-ignore-next-line */
301 1
                $methodName(
302 1
                    $this,
303
                    $directive
304
                );
305
            }
306
        }
307 10
    }
308
309 10
    public function generateString(): string
310
    {
311 10
        $namespace = new \Nette\PhpGenerator\PhpNamespace('App\\Models');
312 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\BelongsTo');
313 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\HasOne');
314 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\HasMany');
315 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphTo');
316 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphOne');
317 10
        $namespace->addUse('\\Illuminate\\Database\\Eloquent\\Relations\\MorphToMany');
318 10
        $namespace->addUse('\\Illuminate\\Support\\Facades\\Auth');
319 10
        $namespace->addUse('\\Formularium\\Exception\\NoRandomException');
320 10
        $namespace->addUse('\\Modelarium\\Laravel\\Datatypes\\Datatype_relationship');
321
322 10
        $this->class = $namespace->addClass('Base' . $this->studlyName);
323 10
        $this->class
324 10
            ->addComment("This file was automatically generated by Modelarium.")
325 10
            ->setAbstract();
326
327 10
        $this->methodRandom = new Method('getRandomData');
328 10
        $this->methodRandom->addBody(
329 10
            '$data = static::getFormularium()->getRandom(get_called_class() . \'::getRandomFieldData\');' . "\n"
330
        );
331
332 10
        $this->processGraphql();
333
334
        // this might have changed
335 10
        $this->class->setExtends($this->parentClassName);
336
337 10
        foreach ($this->traits as $trait) {
338 1
            $this->class->addTrait($trait);
339
        }
340
341 10
        $this->class->addProperty('fillable')
342 10
            ->setProtected()
343 10
            ->setValue($this->fillable)
344 10
            ->setComment("The attributes that are mass assignable.\n@var array")
345 10
            ->setInitialized();
346
347 10
        $this->class->addProperty('hidden')
348 10
            ->setProtected()
349 10
            ->setValue($this->hidden)
350 10
            ->setComment("The attributes that should be hidden for arrays.\n@var array")
351 10
            ->setInitialized();
352
353 10
        if (!$this->migrationTimestamps) {
354 9
            $this->class->addProperty('timestamps')
355 9
                ->setPublic()
356 9
                ->setValue(false)
357 9
                ->setComment("Do not set timestamps.\n@var boolean")
358 9
                ->setInitialized();
359
        }
360
361 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...
362
            $this->class->addProperty('casts')
363
                ->setProtected()
364
                ->setValue($this->casts)
365
                ->setComment("The attributes that should be cast.\n@var array")
366
                ->setInitialized();
367
        }
368
369 10
        $this->class->addMethod('getFields')
370 10
            ->setPublic()
371 10
            ->setStatic()
372 10
            ->setReturnType('array')
373 10
            ->addComment('@return array')
374 10
            ->addBody(
375 10
                "return ?;\n",
376
                [
377 10
                    $this->fModel->serialize()
378
                ]
379
            );
380
381 10
        $this->class->addMethod('getFormularium')
382 10
            ->setPublic()
383 10
            ->setStatic()
384 10
            ->setReturnType('\Formularium\Model')
385 10
            ->addComment('@return \Formularium\Model')
386 10
            ->addBody(
387
                '$model = \Formularium\Model::fromStruct(static::getFields());' . "\n" .
388 10
                'return $model;',
389
                [
390
                    //$this->studlyName,
391 10
                ]
392
            );
393
        
394 10
        $this->methodRandom
395 10
            ->addComment('@return array')
396 10
            ->setPublic()
397 10
            ->setStatic()
398 10
            ->setReturnType('array')
399 10
            ->addBody('return $data;');
400 10
        $this->class->addMember($this->methodRandom);
401
402 10
        $this->class->addMethod('getRandomFieldData')
403 10
            ->setPublic()
404 10
            ->setStatic()
405 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.")
406 10
            ->addBody('
407
$d = $f->getDatatype();
408
if ($d instanceof Datatype_relationship) {
409
    throw new NoRandomException($f->getName());
410
}
411
return $f->getDatatype()->getRandom();')
412 10
            ->addParameter('f')->setType('Formularium\Field');
413
414
        // TODO perhaps we can use PolicyGenerator->policyClasses to auto generate
415 10
        if ($this->hasCan) {
416 10
            $this->class->addMethod('getCanAttribute')
417 10
                ->setPublic()
418 10
                ->setReturnType('array')
419 10
                ->addComment("Returns the policy permissions for actions such as editing or deleting.\n@return \Formularium\Model")
420 10
                ->addBody(
421 10
                    '$policy = new \\App\\Policies\\' . $this->studlyName . 'Policy();' . "\n" .
422 10
                    '$user = Auth::user();' . "\n" .
423 10
                    'return [' . "\n" .
424 10
                    '    //[ "ability" => "create", "value" => $policy->create($user) ]' . "\n" .
425 10
                    '];'
426
                );
427
        }
428
        
429 10
        $printer = new \Nette\PhpGenerator\PsrPrinter;
430 10
        return $this->phpHeader() . $printer->printNamespace($namespace);
431
    }
432
433 10
    protected function processGraphql(): void
434
    {
435 10
        foreach ($this->type->getFields() as $field) {
436 10
            $directives = $field->astNode->directives;
437
            if (
438 10
                ($field->type instanceof ObjectType) ||
439 10
                ($field->type instanceof ListOfType) ||
440 10
                ($field->type instanceof UnionType) ||
441 10
                ($field->type instanceof NonNull && (
442 10
                    ($field->type->getWrappedType() instanceof ObjectType) ||
443 10
                    ($field->type->getWrappedType() instanceof ListOfType) ||
444 10
                    ($field->type->getWrappedType() instanceof UnionType)
445
                ))
446
            ) {
447
                // relationship
448 8
                $this->processRelationship($field, $directives);
449
            } else {
450 10
                $this->processFieldDirectives($field, $directives);
451
            }
452
        }
453
454
        /**
455
         * @var \GraphQL\Language\AST\NodeList|null
456
         */
457 10
        $directives = $this->type->astNode->directives;
458 10
        if ($directives) {
459 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

459
            $this->processDirectives(/** @scrutinizer ignore-type */ $directives);
Loading history...
460
        }
461 10
    }
462
463 10
    public function getGenerateFilename(bool $base = true): string
464
    {
465 10
        return $this->getBasePath(self::$modelDir . '/' . ($base ? 'Base' : '') . $this->studlyName . '.php');
466
    }
467
468
    public static function setModelDir(string $dir): void
469
    {
470
        self::$modelDir = $dir;
471
    }
472
}
473