Passed
Push — master ( efc350...73a53e )
by Bruno
08:12
created

processMigrationFieldDirective()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 4
dl 0
loc 7
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Modelarium\Laravel\Directives;
4
5
use GraphQL\Type\Definition\ObjectType;
6
use Illuminate\Support\Str;
7
use Modelarium\Exception\Exception;
8
use Modelarium\Parser;
9
use Modelarium\Datatypes\RelationshipFactory;
10
use Modelarium\Exception\DirectiveException;
11
use Modelarium\Laravel\Targets\Interfaces\MigrationDirectiveInterface;
12
use Modelarium\Laravel\Targets\ModelGenerator;
13
use Modelarium\Laravel\Targets\SeedGenerator;
14
use Modelarium\Laravel\Targets\Interfaces\ModelDirectiveInterface;
15
use Modelarium\Laravel\Targets\Interfaces\SeedDirectiveInterface;
16
use Modelarium\Laravel\Targets\MigrationCodeFragment;
17
use Modelarium\Laravel\Targets\MigrationGenerator;
18
19
class MorphedByManyDirective implements MigrationDirectiveInterface, ModelDirectiveInterface, SeedDirectiveInterface
20
{
21
    public static function processMigrationTypeDirective(
22
        MigrationGenerator $generator,
23
        \GraphQL\Language\AST\DirectiveNode $directive
24 1
    ): void {
25
        throw new DirectiveException("Directive not supported here");
26
    }
27
28
    public static function processMigrationFieldDirective(
29
        MigrationGenerator $generator,
30
        \GraphQL\Type\Definition\FieldDefinition $field,
31 1
        \GraphQL\Language\AST\DirectiveNode $directive,
32
        MigrationCodeFragment $code
33 1
    ): void {
34
        throw new DirectiveException("Directive not supported here");
35
    }
36
37
    public static function processMigrationRelationshipDirective(
38 1
        MigrationGenerator $generator,
39 1
        \GraphQL\Type\Definition\FieldDefinition $field,
40 1
        \GraphQL\Language\AST\DirectiveNode $directive,
41
        MigrationCodeFragment $codeFragment
42 1
    ): void {
43 1
        $lowerName = mb_strtolower($generator->getInflector()->singularize($field->name));
44
        $relation = Parser::getDirectiveArgumentByName($directive, 'relation', $lowerName);
45 1
        $generator->generateManyToManyMorphTable($generator->getLowerName(), $relation);
46 1
    }
47 1
48 1
    public static function processModelTypeDirective(
49 1
        ModelGenerator $generator,
50 1
        \GraphQL\Language\AST\DirectiveNode $directive
51
    ): void {
52 1
        // nothing
53 1
    }
54 1
55
    public static function processModelFieldDirective(
56 1
        ModelGenerator $generator,
57 1
        \GraphQL\Type\Definition\FieldDefinition $field,
58 1
        \Formularium\Field $fieldFormularium,
59
        \GraphQL\Language\AST\DirectiveNode $directive
60
    ): void {
61
        // nothing
62
    }
63
64
    public static function processModelRelationshipDirective(
65 1
        ModelGenerator $generator,
66
        \GraphQL\Type\Definition\FieldDefinition $field,
67 1
        \GraphQL\Language\AST\DirectiveNode $directive
68
    ): string {
69
        $name = $directive->name->value;
0 ignored issues
show
Unused Code introduced by
The assignment to $name is dead and can be removed.
Loading history...
70 1
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
71 1
        $typeName = $type->name;
0 ignored issues
show
Unused Code introduced by
The assignment to $typeName is dead and can be removed.
Loading history...
72
73 1
        $lowerName = mb_strtolower($generator->getInflector()->singularize($field->name));
74 1
        $lowerNamePlural = $generator->getInflector()->pluralize($lowerName);
0 ignored issues
show
Unused Code introduced by
The assignment to $lowerNamePlural is dead and can be removed.
Loading history...
75
76
        $sourceTypeName = $generator->getLowerName();
77 1
        $targetTypeName = $lowerName;
78 1
        $relationship = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $relationship is dead and can be removed.
Loading history...
79 1
        $isInverse = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isInverse is dead and can be removed.
Loading history...
80 1
        $targetClass = '\\App\\Models\\' . Str::studly($generator->getInflector()->singularize($field->name));
0 ignored issues
show
Unused Code introduced by
The assignment to $targetClass is dead and can be removed.
Loading history...
81 1
        $generateRandom = true; // TODO
0 ignored issues
show
Unused Code introduced by
The assignment to $generateRandom is dead and can be removed.
Loading history...
82
83
        $relationship = RelationshipFactory::MORPH_MANY_TO_MANY; // TODO
84
        $isInverse = true;
85 1
        $typeMap = $generator->parser->getSchema()->getTypeMap();
86 1
87
        foreach ($typeMap as $name => $object) {
88
            if (!($object instanceof ObjectType) || $name === 'Query' || $name === 'Mutation' || $name === 'Subscription') {
89
                continue;
90
            }
91
92
            /**
93 1
             * @var ObjectType $object
94
             */
95
96
            if (str_starts_with((string)$name, '__')) {
97
                // internal type
98 1
                continue;
99 1
            }
100
101 1
            foreach ($object->getFields() as $subField) {
102 1
                $subDirectives = Parser::getDirectives($subField->astNode->directives);
103 1
104
                if (!array_key_exists('morphToMany', $subDirectives)) {
105 1
                    continue;
106
                }
107 1
108
                $methodName = $generator->getInflector()->pluralize(mb_strtolower((string)$name));
109
                $generator->class->addMethod($methodName)
110
                        ->setReturnType('\\Illuminate\\Database\\Eloquent\\Relations\\MorphToMany')
111
                        ->setPublic()
112 1
                        ->setBody("return \$this->morphedByMany($name::class, '$lowerName');");
113 1
            }
114 1
        }
115
116
        return $generator->getRelationshipDatatypeName(
117
            $relationship,
118 1
            $isInverse,
119 1
            $sourceTypeName,
120
            $targetTypeName
121
        );
122
    }
123
124
    public static function processSeedFieldDirective(
125
        SeedGenerator $generator,
126
        \GraphQL\Type\Definition\FieldDefinition $field,
127
        \GraphQL\Language\AST\DirectiveNode $directive
128
    ): void {
129
        $type1 = $generator->getLowerName();
130
        $type2 = mb_strtolower($generator->getInflector()->singularize($field->name));
131
132
        if (strcasecmp($type1, $type2) < 0) { // TODO: check this, might not work
133
            $relationship = mb_strtolower($generator->getInflector()->pluralize($field->name));
134
            $generator->extraCode[] = self::makeManyToManySeed($type1, $type2, $relationship);
135
        }
136
    }
137
138
    protected static function makeManyToManySeed(string $sourceModel, string $targetModel, string $relationship): string
0 ignored issues
show
Unused Code introduced by
The parameter $sourceModel is not used and could be removed. ( Ignorable by Annotation )

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

138
    protected static function makeManyToManySeed(/** @scrutinizer ignore-unused */ string $sourceModel, string $targetModel, string $relationship): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
139
    {
140
        return <<<EOF
141
142
        try {
143
            \${$targetModel}Items = App\\Models\\$targetModel::all();
144
            \$model->{$relationship}()->attach(
145
                \${$targetModel}Items->random(rand(1, 3))->pluck('id')->toArray()
146
            );
147
        }
148
        catch (\InvalidArgumentException \$e) {
149
            \$model->{$relationship}()->attach(
150
                \${$targetModel}Items->random(1)->pluck('id')->toArray()
151
            );
152
        }
153
EOF;
154
    }
155
}
156