1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Modelarium\Laravel\Directives; |
4
|
|
|
|
5
|
|
|
use Modelarium\Exception\DirectiveException; |
6
|
|
|
use Modelarium\Exception\Exception; |
7
|
|
|
use Modelarium\Laravel\Targets\MigrationGenerator; |
8
|
|
|
use Modelarium\Laravel\Targets\Interfaces\MigrationDirectiveInterface; |
9
|
|
|
use Modelarium\Laravel\Targets\MigrationCodeFragment; |
10
|
|
|
use Modelarium\Parser; |
11
|
|
|
|
12
|
|
|
class MigrationForeignDirective implements MigrationDirectiveInterface |
13
|
|
|
{ |
14
|
|
|
public static function processMigrationTypeDirective( |
15
|
|
|
MigrationGenerator $generator, |
16
|
|
|
\GraphQL\Language\AST\DirectiveNode $directive |
17
|
|
|
): void { |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
public static function processMigrationFieldDirective( |
21
|
|
|
MigrationGenerator $generator, |
22
|
|
|
\GraphQL\Type\Definition\FieldDefinition $field, |
23
|
|
|
\GraphQL\Language\AST\DirectiveNode $directive, |
24
|
|
|
MigrationCodeFragment $code |
25
|
|
|
): void { |
26
|
|
|
throw new DirectiveException("Directive not supported here"); |
27
|
|
|
} |
28
|
|
|
|
29
|
4 |
|
public static function processMigrationRelationshipDirective( |
30
|
|
|
MigrationGenerator $generator, |
31
|
|
|
\GraphQL\Type\Definition\FieldDefinition $field, |
32
|
|
|
\GraphQL\Language\AST\DirectiveNode $directive, |
33
|
|
|
MigrationCodeFragment $code |
34
|
|
|
): void { |
35
|
4 |
|
$tableName = MigrationGenerator::toTableName($field->name); |
36
|
4 |
|
$lowerName = mb_strtolower($generator->getInflector()->singularize($field->name)); |
37
|
4 |
|
$fieldName = $lowerName . '_id'; |
38
|
4 |
|
$directives = $field->astNode->directives; |
39
|
|
|
|
40
|
4 |
|
foreach ($directives as $directive) { |
41
|
4 |
|
$name = $directive->name->value; |
42
|
|
|
|
43
|
4 |
|
switch ($name) { |
44
|
4 |
|
case 'belongToMany': |
45
|
4 |
|
case 'morphedByMany': |
46
|
|
|
throw new DirectiveException("Foreign keys cannot be used with many-to-many-relationships. Check field: " . $field->name); |
47
|
|
|
break; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
$arguments = array_merge( |
52
|
|
|
[ |
53
|
4 |
|
'references' => 'id', |
54
|
4 |
|
'on' => $tableName |
55
|
|
|
], |
56
|
4 |
|
Parser::getDirectiveArguments($directive) |
57
|
|
|
); |
58
|
|
|
|
59
|
4 |
|
$code->appendExtraLine( |
60
|
4 |
|
'$table->foreign("' . $fieldName . '")' . |
61
|
4 |
|
"->references(\"{$arguments['references']}\")" . |
62
|
4 |
|
"->on(\"{$arguments['on']}\")" . |
63
|
4 |
|
(($arguments['onDelete'] ?? '') ? "->onDelete(\"{$arguments['onDelete']}\")" : '') . |
64
|
4 |
|
(($arguments['onUpdate'] ?? '') ? "->onUpdate(\"{$arguments['onUpdate']}\")" : '') . |
65
|
4 |
|
';' |
66
|
|
|
); |
67
|
4 |
|
} |
68
|
|
|
} |
69
|
|
|
|