Passed
Push — master ( 4c99b3...1b0c60 )
by Bruno
02:54
created

MigrationGenerator   F

Complexity

Total Complexity 71

Size/Duplication

Total Lines 507
Duplicated Lines 0 %

Test Coverage

Coverage 74.06%

Importance

Changes 7
Bugs 3 Features 0
Metric Value
wmc 71
eloc 294
c 7
b 3
f 0
dl 0
loc 507
ccs 197
cts 266
cp 0.7406
rs 2.7199

8 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 15 2
A generateManyToManyTable() 0 31 1
A processDirectives() 0 12 3
B generateString() 0 48 11
F processRelationship() 0 114 25
F processBasetype() 0 133 23
A generateFilename() 0 37 5
A generateManyToManyMorphTable() 0 30 1

How to fix   Complexity   

Complex Class

Complex classes like MigrationGenerator 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 MigrationGenerator, 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\Datatype_enum;
6
use Formularium\Exception\ClassNotFoundException;
7
use Formularium\Factory\DatatypeFactory;
8
use Illuminate\Support\Str;
9
use GraphQL\Language\AST\DirectiveNode;
10
use GraphQL\Type\Definition\BooleanType;
11
use GraphQL\Type\Definition\CustomScalarType;
12
use GraphQL\Type\Definition\Directive;
13
use GraphQL\Type\Definition\EnumType;
14
use GraphQL\Type\Definition\FloatType;
15
use GraphQL\Type\Definition\IDType;
16
use GraphQL\Type\Definition\IntType;
17
use GraphQL\Type\Definition\ListOfType;
18
use GraphQL\Type\Definition\NonNull;
19
use GraphQL\Type\Definition\ObjectType;
20
use GraphQL\Type\Definition\StringType;
21
use GraphQL\Type\Definition\UnionType;
22
use Modelarium\BaseGenerator;
23
use Modelarium\Exception\Exception;
24
use Modelarium\Exception\ScalarNotFoundException;
25
use Modelarium\GeneratedCollection;
26
use Modelarium\GeneratedItem;
27
use Modelarium\Parser;
28
use Modelarium\Types\FormulariumScalarType;
29
use Nette\PhpGenerator\ClassType;
30
31
use function Safe\array_combine;
32
use function Safe\rsort;
33
use function Safe\date;
34
35
function getStringBetween(string $string, string $start, string $end): string
36
{
37
    $ini = mb_strpos($string, $start);
38
    if ($ini === false) {
39
        return '';
40
    }
41
    $ini += mb_strlen($start);
42
    $len = mb_strpos($string, $end, $ini) - $ini;
43
    return mb_substr($string, $ini, $len);
44
}
45
46
function endsWith(string $haystack, string $needle): bool
47
{
48
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;
49
}
50
class MigrationGenerator extends BaseGenerator
51
{
52
    /**
53
     * @var string
54
     */
55
    protected $stubDir = __DIR__ . "/stubs/";
56
57
    protected const MODE_CREATE = 'create';
58
    protected const MODE_PATCH = 'patch';
59
    protected const MODE_NO_CHANGE = 'nochange';
60
61
    /**
62
     * Unique counter
63
     *
64
     * @var integer
65
     */
66
    public static $counter = 0;
67
68
    /**
69
     * @var ObjectType
70
     */
71
    protected $type = null;
72
73
    /**
74
     * @var GeneratedCollection
75
     */
76
    protected $collection = null;
77
78
    /**
79
     * Code used in the create() call
80
     *
81
     * @var string[]
82
     */
83
    public $createCode = [];
84
85
    /**
86
     * Code used post the create() call
87
     *
88
     * @var string[]
89
     */
90
    public $postCreateCode = [];
91
92
    /**
93
     * 'create' or 'patch'
94
     *
95
     * @var string
96
     */
97
    protected $mode = self::MODE_CREATE;
98
99
    /**
100
     * Code used in the create() call
101
     *
102
     * @var string
103
     */
104
    protected $currentModel = '';
105
106 8
    public function generate(): GeneratedCollection
107
    {
108 8
        $this->collection = new GeneratedCollection();
109 8
        $this->currentModel = \GraphQL\Language\Printer::doPrint($this->type->astNode);
110 8
        $filename = $this->generateFilename($this->lowerName);
111
112 8
        if ($this->mode !== self::MODE_NO_CHANGE) {
113 8
            $item = new GeneratedItem(
114 8
                GeneratedItem::TYPE_MIGRATION,
115 8
                $this->generateString(),
116
                $filename
117
            );
118 8
            $this->collection->prepend($item);
119
        }
120 8
        return $this->collection;
121
    }
122
123 21
    protected function processBasetype(
124
        \GraphQL\Type\Definition\FieldDefinition $field,
125
        \GraphQL\Language\AST\NodeList $directives
126
    ): void {
127 21
        $fieldName = $field->name;
128 21
        $extra = [];
129
130
        // TODO: scalars
131
132 21
        if ($field->type instanceof NonNull) {
133 21
            $type = $field->type->getWrappedType();
134
        } else {
135 1
            $type = $field->type;
136
        }
137
138 21
        $base = '';
139 21
        if ($type instanceof IDType) {
140 21
            $base = '$table->bigIncrements("id")';
141 16
        } elseif ($type instanceof StringType) {
142 16
            $base = '$table->string("' . $fieldName . '")';
143 4
        } elseif ($type instanceof IntType) {
144 1
            $base = '$table->integer("' . $fieldName . '")';
145 4
        } elseif ($type instanceof BooleanType) {
146 1
            $base = '$table->bool("' . $fieldName . '")';
147 4
        } elseif ($type instanceof FloatType) {
148 1
            $base = '$table->float("' . $fieldName . '")';
149 3
        } elseif ($type instanceof EnumType) {
150
            $ourType = $this->parser->getScalarType($type->name);
151
            $parsedValues = $type->config['values'];
152
153
            if (!$ourType) {
154
                $parsedKeys = array_keys($parsedValues);
155
                $enumValues = array_combine($parsedKeys, $parsedKeys);
156
157
                // let's create this for the user
158
                $code = DatatypeFactory::generate(
159
                    $type->name,
160
                    'enum',
161
                    'App\\Datatypes',
162
                    'Tests\\Unit',
163
                    function (ClassType $enumClass) use ($enumValues) {
164
                        $enumClass->addConstant('CHOICES', $enumValues);
165
                        $enumClass->getMethod('__construct')->addBody('$this->choices = self::CHOICES;');
166
                    }
167
                );
168
        
169
                $path = base_path('app/Datatypes');
0 ignored issues
show
Bug introduced by
The function base_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

169
                $path = /** @scrutinizer ignore-call */ base_path('app/Datatypes');
Loading history...
170
                $lowerTypeName = mb_strtolower($type->name);
171
172
                $retval = DatatypeFactory::generateFile(
173
                    $code,
174
                    $path,
175
                    base_path('tests/Unit/')
176
                );
177
178
                $php = \Modelarium\Util::generateLighthouseTypeFile($lowerTypeName, 'App\\Datatypes\\Types');
179
                $filename = $path . "/Types/Datatype_{$lowerTypeName}.php";
180
                if (!is_dir($path . "/Types")) {
181
                    \Safe\mkdir($path . "/Types", 0777, true);
182
                }
183
                \Safe\file_put_contents($filename, $php);
184
        
185
                // recreate scalars
186
                \Modelarium\Util::generateScalarFile('App\\Datatypes', base_path('graphql/types.graphql'));
187
188
                // load php files that were just created
189
                require_once($retval['filename']);
190
                require_once($filename);
191
                $this->parser->appendScalar($type->name, 'App\\Datatypes\\Types\\Datatype_' . $lowerTypeName);
192
                $ourType = $this->parser->getScalarType($type->name);
193
            }
194
            if (!($ourType instanceof FormulariumScalarType)) {
195
                throw new Exception("Enum {$type->name} {$fieldName} is not a FormulariumScalarType");
196
            }
197
198
            /**
199
             * @var FormulariumScalarType $ourType
200
             */
201
            /**
202
             * @var Datatype_enum $ourDatatype
203
             */
204
            $ourDatatype = $ourType->getDatatype();
205
            $currentChoices = $ourDatatype->getChoices();
206
            if (array_diff_key($currentChoices, $parsedValues) || array_diff_key($parsedValues, $currentChoices)) {
207
                // TODO???
208
            }
209 3
        } elseif ($type instanceof UnionType) {
210
            return;
211 3
        } elseif ($type instanceof CustomScalarType) {
212 3
            $ourType = $this->parser->getScalarType($type->name);
213 3
            if (!$ourType) {
214
                throw new Exception("Invalid extended scalar type: " . get_class($type));
215
            }
216 3
            $options = []; // TODO: from directives
217 3
            $base = '$table->' . $ourType->getLaravelSQLType($fieldName, $options);
218
        } elseif ($type instanceof ListOfType) {
219
            throw new Exception("Invalid field type: " . get_class($type));
220
        } else {
221
            throw new Exception("Invalid field type: " . get_class($type));
222
        }
223
224 21
        if (!($field->type instanceof NonNull)) {
225 1
            $base .= '->nullable()';
226
        }
227
228
        // TODO: call directive class
229
230 21
        foreach ($directives as $directive) {
231
            /**
232
             * @var DirectiveNode $directive
233
             */
234 2
            $name = $directive->name->value;
235 2
            switch ($name) {
236 2
            case 'migrationSkip':
237
                return;
238 2
            case 'migrationUniqueIndex':
239 1
                $extra[] = '$table->unique("' . $fieldName . '");';
240 1
                break;
241 1
            case 'migrationIndex':
242
                $extra[] = '$table->index("' . $fieldName . '");';
243
                break;
244 1
            case 'migrationDefaultValue':
245
                $x = ''; // TODO
246
                Parser::getDirectiveArgumentByName($directive, 'value');
247
                $base .= '->default(' . $x . ')';
248
                throw new Exception('Default value not implemented yet');
249
                // break;
250
            }
251
        }
252 21
        $base .= ';';
253
254 21
        $this->createCode[] = $base;
255 21
        $this->createCode = array_merge($this->createCode, $extra);
256 21
    }
257
258 8
    protected function processRelationship(
259
        \GraphQL\Type\Definition\FieldDefinition $field,
260
        \GraphQL\Language\AST\NodeList $directives
261
    ): void {
262 8
        $lowerName = mb_strtolower($this->getInflector()->singularize($field->name));
263 8
        $lowerNamePlural = $this->getInflector()->pluralize($lowerName);
264 8
        $fieldName = $lowerName . '_id';
265
266 8
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
267 8
        $typeName = $type->name;
268
269 8
        $base = null;
270 8
        $extra = [];
271
272
        // special types that should be skipped.
273 8
        if ($typeName === 'Can') {
274
            return;
275
        }
276
277 8
        $isManyToMany = false;
278 8
        foreach ($directives as $directive) {
279 8
            $name = $directive->name->value;
280 8
            switch ($name) {
281 8
            case 'migrationSkip':
282
                return;
283 8
            case 'migrationUniqueIndex':
284
                $extra[] = '$table->unique("' . $fieldName . '");';
285
                break;
286 8
            case 'migrationIndex':
287
                $extra[] = '$table->index("' . $fieldName . '");';
288
                break;
289 8
            case 'belongsTo':
290 4
                $targetType = $this->parser->getType($typeName);
291 4
                if (!$targetType) {
292
                    throw new Exception("Cannot get type {$typeName} as a relationship to {$this->baseName}");
293 4
                } elseif (!($targetType instanceof ObjectType)) {
294
                    throw new Exception("{$typeName} is not a type for a relationship to {$this->baseName}");
295
                }
296
                try {
297 4
                    $targetField = $targetType->getField($this->lowerName); // TODO: might have another name than lowerName
298 1
                } catch (\GraphQL\Error\InvariantViolation $e) {
299 1
                    $targetField = $targetType->getField($this->lowerNamePlural);
300
                }
301
302 4
                $targetDirectives = $targetField->astNode->directives;
303 4
                foreach ($targetDirectives as $targetDirective) {
304 4
                    switch ($targetDirective->name->value) {
305 4
                    case 'hasOne':
306 1
                    case 'hasMany':
307 4
                        $base = '$table->unsignedBigInteger("' . $fieldName . '")';
308 4
                    break;
309
                    }
310
                }
311 4
                break;
312
313 8
            case 'belongsToMany':
314 1
                $type1 = $this->lowerName;
315 1
                $type2 = $lowerName;
316
317
                // we only generate once, so use a comparison for that
318 1
                $isManyToMany = true;
319 1
                if (strcasecmp($type1, $type2) < 0) {
320 1
                    $this->generateManyToManyTable($type1, $type2);
321
                }
322 1
                break;
323
324 7
            case 'morphTo':
325 2
                $relation = Parser::getDirectiveArgumentByName($directive, 'relation', $lowerName);
326 2
                $base = '$table->unsignedBigInteger("' . $relation . '_id")';
327 2
                $extra[] = '$table->string("' . $relation . '_type")' .
328 2
                    ($isRequired ? '' : '->nullable()') . ';';
329 2
                break;
330
331 7
            case 'morphedByMany':
332 1
                $isManyToMany = true;
333 1
                $relation = Parser::getDirectiveArgumentByName($directive, 'relation', $lowerName);
334 1
                $this->generateManyToManyMorphTable($this->lowerName, $relation);
335 1
                break;
336
            }
337
        }
338
339 8
        foreach ($directives as $directive) {
340 8
            $name = $directive->name->value;
341
            switch ($name) {
342 8
            case 'migrationForeign':
343
                
344 4
                if (!$isManyToMany) {
345 4
                    $arguments = array_merge(
346
                        [
347 4
                            'references' => 'id',
348 4
                            'on' => $lowerNamePlural
349
                        ],
350 4
                        Parser::getDirectiveArguments($directive)
351
                    );
352
    
353 4
                    $extra[] = '$table->foreign("' . $fieldName . '")' .
354 4
                        "->references(\"{$arguments['references']}\")" .
355 4
                        "->on(\"{$arguments['on']}\")" .
356 4
                        (($arguments['onDelete'] ?? '') ? "->onDelete(\"{$arguments['onDelete']}\")" : '') .
357 4
                        (($arguments['onUpdate'] ?? '') ? "->onUpdate(\"{$arguments['onUpdate']}\")" : '') .
358 4
                        ';';
359
                }
360 4
                break;
361
            }
362
        }
363
364 8
        if ($base) {
365 6
            if (!($field->type instanceof NonNull)) {
366
                $base .= '->nullable()';
367
            }
368 6
            $base .= ';';
369 6
            $this->createCode[] = $base;
370
        }
371 8
        $this->createCode = array_merge($this->createCode, $extra);
372 8
    }
373
374 21
    protected function processDirectives(
375
        \GraphQL\Language\AST\NodeList $directives
376
    ): void {
377 21
        foreach ($directives as $directive) {
378 6
            $name = $directive->name->value;
379 6
            $className = $this->getDirectiveClass($name);
380 6
            if ($className) {
381 6
                $methodName = "$className::processMigrationTypeDirective";
382
                /** @phpstan-ignore-next-line */
383 6
                $methodName(
384 6
                    $this,
385
                    $directive
386
                );
387
            }
388
        }
389 21
    }
390
391 21
    public function generateString(): string
392
    {
393 21
        foreach ($this->type->getFields() as $field) {
394 21
            $directives = $field->astNode->directives;
395
            if (
396 21
                ($field->type instanceof ObjectType) ||
397 21
                ($field->type instanceof ListOfType) ||
398 21
                ($field->type instanceof UnionType) ||
399 21
                ($field->type instanceof NonNull && (
400 21
                    ($field->type->getWrappedType() instanceof ObjectType) ||
401 21
                    ($field->type->getWrappedType() instanceof ListOfType) ||
402 21
                    ($field->type->getWrappedType() instanceof UnionType)
403
                ))
404
            ) {
405
                // relationship
406 8
                $this->processRelationship($field, $directives);
407
            } else {
408 21
                $this->processBasetype($field, $directives);
409
            }
410
        }
411
412
        assert($this->type->astNode !== null);
413
        /**
414
         * @var \GraphQL\Language\AST\NodeList|null
415
         */
416 21
        $directives = $this->type->astNode->directives;
417 21
        if ($directives) {
418 21
            $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

418
            $this->processDirectives(/** @scrutinizer ignore-type */ $directives);
Loading history...
419
        }
420
421
        $context = [
422 21
            'dummytablename' => $this->lowerNamePlural,
423
            'modelSchemaCode' => "# start graphql\n" .
424 21
                $this->currentModel .
425 21
                "\n# end graphql",
426
        ];
427
428 21
        if ($this->mode === self::MODE_CREATE) {
429 21
            $context['className'] = 'Create' . $this->studlyName;
430 21
            $context['dummyCode'] = join("\n            ", $this->createCode);
431 21
            $context['dummyPostCreateCode'] = join("\n            ", $this->postCreateCode);
432
        } else {
433
            $context['className'] = 'Patch' . $this->studlyName . date('YmdHis');
434
            $context['dummyCode'] = '// TODO: write the patch please';
435
            $context['dummyPostCreateCode'] = '';
436
        }
437
438 21
        return $this->templateStub('migration', $context);
439
    }
440
441
    /**
442
     * creates a many-to-many morph relationship table
443
     *
444
     * @param string $name
445
     * @param string $relation
446
     * @return string The table name.
447
     */
448 1
    protected function generateManyToManyMorphTable(string $name, string $relation): string
449
    {
450
        $dummyCode = <<<EOF
451
452 1
            \$table->unsignedBigInteger("{$name}_id");
453 1
            \$table->unsignedBigInteger("{$relation}_id");
454 1
            \$table->string("{$relation}_type");
455
EOF;
456
        $context = [
457 1
            'dummyCode' => $dummyCode,
458 1
            'dummytablename' => $this->getInflector()->pluralize($relation),
459 1
            'modelSchemaCode' => ''
460
        ];
461 1
        $contents = $this->templateStub('migration', $context);
462
463 1
        $item = new GeneratedItem(
464 1
            GeneratedItem::TYPE_MIGRATION,
465
            $contents,
466 1
            $this->getBasePath(
467
                'database/migrations/' .
468 1
                date('Y_m_d_His') .
469 1
                str_pad((string)(static::$counter++), 3, "0", STR_PAD_LEFT) . // so we keep the same order of types in schema
470 1
                '_' . $this->mode . '_' .
471 1
                $relation .
472 1
                '_table.php'
473
            )
474
        );
475 1
        $this->collection->push($item);
476
477 1
        return $context['dummytablename'];
478
    }
479
480
    /**
481
     * creates a many-to-many relationship table
482
     *
483
     * @param string $type1
484
     * @param string $type2
485
     * @return string The table name.
486
     */
487 1
    protected function generateManyToManyTable(string $type1, string $type2): string
488
    {
489
        $dummyCode = <<<EOF
490
491
            \$table->increments("id");
492 1
            \$table->unsignedBigInteger("{$type1}_id")->references('id')->on('{$type1}');
493 1
            \$table->unsignedBigInteger("{$type2}_id")->references('id')->on('{$type2}');
494
EOF;
495
        $context = [
496 1
            'dummyCode' => $dummyCode,
497 1
            'dummytablename' => "{$type1}_{$type2}",
498 1
            'className' => Str::studly($this->mode) . Str::studly($type1) . Str::studly($type2),
499 1
            'modelSchemaCode' => ''
500
        ];
501 1
        $contents = $this->templateStub('migration', $context);
502
503 1
        $item = new GeneratedItem(
504 1
            GeneratedItem::TYPE_MIGRATION,
505
            $contents,
506 1
            $this->getBasePath(
507
                'database/migrations/' .
508 1
                date('Y_m_d_His') .
509 1
                str_pad((string)(static::$counter++), 3, "0", STR_PAD_LEFT) . // so we keep the same order of types in schema
510 1
                '_' . $this->mode . '_' .
511 1
                $type1 . '_' . $type2 .
512 1
                '_table.php'
513
            )
514
        );
515 1
        $this->collection->push($item);
516
517 1
        return $context['dummytablename'];
518
    }
519
520 8
    protected function generateFilename(string $basename): string
521
    {
522 8
        $this->mode = self::MODE_CREATE;
523 8
        $match = '_' . $basename . '_table.php';
524
525 8
        $basepath = $this->getBasePath('database/migrations/');
526 8
        if (is_dir($basepath)) {
527
            $migrationFiles = \Safe\scandir($basepath);
528
            rsort($migrationFiles);
529
            foreach ($migrationFiles as $m) {
530
                if (!endsWith($m, $match)) {
531
                    continue;
532
                }
533
534
                // get source
535
                $data = \Safe\file_get_contents($basepath . '/' . $m);
536
537
                // compare with this source
538
                $model = trim(getStringBetween($data, '# start graphql', '# end graphql'));
539
540
                // if equal ignore and don't output file
541
                if ($model === $this->currentModel) {
542
                    $this->mode = self::MODE_NO_CHANGE;
543
                } else {
544
                    // else we'll generate a diff and patch
545
                    $this->mode = self::MODE_PATCH;
546
                }
547
                break;
548
            }
549
        }
550
551 8
        return $this->getBasePath(
552
            'database/migrations/' .
553 8
            date('Y_m_d_His') .
554 8
            str_pad((string)(static::$counter++), 3, "0", STR_PAD_LEFT) . // so we keep the same order of types in schema
555 8
            '_' . $this->mode . '_' .
556 8
            $basename . '_table.php'
557
        );
558
    }
559
}
560