Passed
Push — master ( a41166...4c99b3 )
by Bruno
03:13
created

MigrationGenerator::generateManyToManyMorphTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 30
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 1

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 23
c 2
b 1
f 0
nc 1
nop 2
dl 0
loc 30
ccs 18
cts 18
cp 1
crap 1
rs 9.552
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 'migrationUniqueIndex':
237 1
                $extra[] = '$table->unique("' . $fieldName . '");';
238 1
                break;
239 1
            case 'migrationIndex':
240
                $extra[] = '$table->index("' . $fieldName . '");';
241
                break;
242 1
            case 'migrationDefaultValue':
243
                $x = ''; // TODO
244
                Parser::getDirectiveArgumentByName($directive, 'value');
245
                $base .= '->default(' . $x . ')';
246
                throw new Exception('Default value not implemented yet');
247
                // break;
248
            }
249
        }
250 21
        $base .= ';';
251
252 21
        $this->createCode[] = $base;
253 21
        $this->createCode = array_merge($this->createCode, $extra);
254 21
    }
255
256 8
    protected function processRelationship(
257
        \GraphQL\Type\Definition\FieldDefinition $field,
258
        \GraphQL\Language\AST\NodeList $directives
259
    ): void {
260 8
        $lowerName = mb_strtolower($this->getInflector()->singularize($field->name));
261 8
        $lowerNamePlural = $this->getInflector()->pluralize($lowerName);
262 8
        $fieldName = $lowerName . '_id';
263
264 8
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
265 8
        $typeName = $type->name;
266
267 8
        $base = null;
268 8
        $extra = [];
269
270
        // special types that should be skipped.
271 8
        if ($typeName === 'Can') {
272
            return;
273
        }
274
275 8
        $isManyToMany = false;
276 8
        foreach ($directives as $directive) {
277 8
            $name = $directive->name->value;
278 8
            switch ($name) {
279 8
            case 'migrationSkip':
280
                return;
281 8
            case 'migrationUniqueIndex':
282
                $extra[] = '$table->unique("' . $fieldName . '");';
283
                break;
284 8
            case 'migrationIndex':
285
                $extra[] = '$table->index("' . $fieldName . '");';
286
                break;
287 8
            case 'belongsTo':
288 4
                $targetType = $this->parser->getType($typeName);
289 4
                if (!$targetType) {
290
                    throw new Exception("Cannot get type {$typeName} as a relationship to {$this->baseName}");
291 4
                } elseif (!($targetType instanceof ObjectType)) {
292
                    throw new Exception("{$typeName} is not a type for a relationship to {$this->baseName}");
293
                }
294
                try {
295 4
                    $targetField = $targetType->getField($this->lowerName); // TODO: might have another name than lowerName
296 1
                } catch (\GraphQL\Error\InvariantViolation $e) {
297 1
                    $targetField = $targetType->getField($this->lowerNamePlural);
298
                }
299
300 4
                $targetDirectives = $targetField->astNode->directives;
301 4
                foreach ($targetDirectives as $targetDirective) {
302 4
                    switch ($targetDirective->name->value) {
303 4
                    case 'hasOne':
304 1
                    case 'hasMany':
305 4
                        $base = '$table->unsignedBigInteger("' . $fieldName . '")';
306 4
                    break;
307
                    }
308
                }
309 4
                break;
310
311 8
            case 'belongsToMany':
312 1
                $type1 = $this->lowerName;
313 1
                $type2 = $lowerName;
314
315
                // we only generate once, so use a comparison for that
316 1
                $isManyToMany = true;
317 1
                if (strcasecmp($type1, $type2) < 0) {
318 1
                    $this->generateManyToManyTable($type1, $type2);
319
                }
320 1
                break;
321
322 7
            case 'morphTo':
323 2
                $relation = Parser::getDirectiveArgumentByName($directive, 'relation', $lowerName);
324 2
                $base = '$table->unsignedBigInteger("' . $relation . '_id")';
325 2
                $extra[] = '$table->string("' . $relation . '_type")' .
326 2
                    ($isRequired ? '' : '->nullable()') . ';';
327 2
                break;
328
329 7
            case 'morphedByMany':
330 1
                $isManyToMany = true;
331 1
                $relation = Parser::getDirectiveArgumentByName($directive, 'relation', $lowerName);
332 1
                $this->generateManyToManyMorphTable($this->lowerName, $relation);
333 1
                break;
334
            }
335
        }
336
337 8
        foreach ($directives as $directive) {
338 8
            $name = $directive->name->value;
339
            switch ($name) {
340 8
            case 'migrationForeign':
341
                
342 4
                if (!$isManyToMany) {
343 4
                    $arguments = array_merge(
344
                        [
345 4
                            'references' => 'id',
346 4
                            'on' => $lowerNamePlural
347
                        ],
348 4
                        Parser::getDirectiveArguments($directive)
349
                    );
350
    
351 4
                    $extra[] = '$table->foreign("' . $fieldName . '")' .
352 4
                        "->references(\"{$arguments['references']}\")" .
353 4
                        "->on(\"{$arguments['on']}\")" .
354 4
                        (($arguments['onDelete'] ?? '') ? "->onDelete(\"{$arguments['onDelete']}\")" : '') .
355 4
                        (($arguments['onUpdate'] ?? '') ? "->onUpdate(\"{$arguments['onUpdate']}\")" : '') .
356 4
                        ';';
357
                }
358 4
                break;
359
            }
360
        }
361
362 8
        if ($base) {
363 6
            if (!($field->type instanceof NonNull)) {
364
                $base .= '->nullable()';
365
            }
366 6
            $base .= ';';
367 6
            $this->createCode[] = $base;
368
        }
369 8
        $this->createCode = array_merge($this->createCode, $extra);
370 8
    }
371
372 21
    protected function processDirectives(
373
        \GraphQL\Language\AST\NodeList $directives
374
    ): void {
375 21
        foreach ($directives as $directive) {
376 6
            $name = $directive->name->value;
377 6
            $className = $this->getDirectiveClass($name);
378 6
            if ($className) {
379 6
                $methodName = "$className::processMigrationTypeDirective";
380
                /** @phpstan-ignore-next-line */
381 6
                $methodName(
382 6
                    $this,
383
                    $directive
384
                );
385
            }
386
        }
387 21
    }
388
389 21
    public function generateString(): string
390
    {
391 21
        foreach ($this->type->getFields() as $field) {
392 21
            $directives = $field->astNode->directives;
393
            if (
394 21
                ($field->type instanceof ObjectType) ||
395 21
                ($field->type instanceof ListOfType) ||
396 21
                ($field->type instanceof UnionType) ||
397 21
                ($field->type instanceof NonNull && (
398 21
                    ($field->type->getWrappedType() instanceof ObjectType) ||
399 21
                    ($field->type->getWrappedType() instanceof ListOfType) ||
400 21
                    ($field->type->getWrappedType() instanceof UnionType)
401
                ))
402
            ) {
403
                // relationship
404 8
                $this->processRelationship($field, $directives);
405
            } else {
406 21
                $this->processBasetype($field, $directives);
407
            }
408
        }
409
410
        assert($this->type->astNode !== null);
411
        /**
412
         * @var \GraphQL\Language\AST\NodeList|null
413
         */
414 21
        $directives = $this->type->astNode->directives;
415 21
        if ($directives) {
416 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

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