Passed
Push — master ( cab6b5...845ff4 )
by Bruno
04:13 queued 01:09
created

MorphManyDirective::makeManyToManySeed()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
nc 1
nop 3
dl 0
loc 13
ccs 0
cts 6
cp 0
crap 2
rs 9.9666
c 1
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\Laravel\Targets\ModelGenerator;
11
use Modelarium\Laravel\Targets\SeedGenerator;
12
use Modelarium\Laravel\Targets\Interfaces\ModelDirectiveInterface;
13
use Modelarium\Laravel\Targets\Interfaces\SeedDirectiveInterface;
14
15
class MorphManyDirective implements ModelDirectiveInterface, SeedDirectiveInterface
16
{
17
    public static function processModelTypeDirective(
18
        ModelGenerator $generator,
19
        \GraphQL\Language\AST\DirectiveNode $directive
20
    ): void {
21
        // nothing
22
    }
23
24 1
    public static function processModelFieldDirective(
25
        ModelGenerator $generator,
26
        \GraphQL\Type\Definition\FieldDefinition $field,
27
       \Formularium\Field $fieldFormularium,
28
        \GraphQL\Language\AST\DirectiveNode $directive
29
    ): void {
30
        // nothing
31 1
    }
32
33 1
    public static function processModelRelationshipDirective(
34
        ModelGenerator $generator,
35
        \GraphQL\Type\Definition\FieldDefinition $field,
36
        \GraphQL\Language\AST\DirectiveNode $directive
37
    ): string {
38 1
        $name = $directive->name->value;
39 1
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
40 1
        $typeName = $type->name;
41
42 1
        $lowerName = mb_strtolower($generator->getInflector()->singularize($field->name));
43 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...
44
45 1
        $sourceTypeName = $generator->getLowerName();
46 1
        $targetTypeName = $lowerName;
47 1
        $relationship = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $relationship is dead and can be removed.
Loading history...
48 1
        $isInverse = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isInverse is dead and can be removed.
Loading history...
49 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...
50 1
        $generateRandom = true; // TODO
0 ignored issues
show
Unused Code introduced by
The assignment to $generateRandom is dead and can be removed.
Loading history...
51
52 1
        $relationship = RelationshipFactory::MORPH_ONE_TO_MANY;
53 1
        $isInverse = false;
54
55 1
        $targetType = $generator->parser->getType($typeName);
56 1
        if (!$targetType) {
0 ignored issues
show
introduced by
$targetType is of type GraphQL\Type\Definition\Type, thus it always evaluated to true.
Loading history...
57
            throw new Exception("Cannot get type {$typeName} as a relationship to {$generator->getBaseName()}");
58 1
        } elseif (!($targetType instanceof ObjectType)) {
59
            throw new Exception("{$typeName} is not a type for a relationship to {$generator->getBaseName()}");
60
        }
61 1
        $targetField = null;
62 1
        foreach ($targetType->getFields() as $subField) {
63 1
            $subDir = Parser::getDirectives($subField->astNode->directives);
64 1
            if (array_key_exists('morphTo', $subDir) || array_key_exists('morphedByMany', $subDir)) {
65 1
                $targetField = $subField->name;
66 1
                break;
67
            }
68
        }
69 1
        if (!$targetField) {
70
            throw new Exception("{$targetType} does not have a '@morphTo' or '@morphToMany' field");
71
        }
72
73 1
        $generator->class->addMethod($field->name)
74 1
        ->setReturnType('\Illuminate\Database\Eloquent\Relations\MorphMany')
75 1
            ->setPublic()
76 1
            ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
77
78
79 1
        return $generator->getRelationshipDatatypeName(
80 1
            $relationship,
81
            $isInverse,
82
            $sourceTypeName,
83
            $targetTypeName
84
        );
85
    }
86
87
    public static function processSeedTypeDirective(
88
        SeedGenerator $generator,
89
        \GraphQL\Language\AST\DirectiveNode $directive
90
    ): void {
91
        // empty
92
    }
93
94 1
    public static function processSeedFieldDirective(
95
        SeedGenerator $generator,
96
        \GraphQL\Type\Definition\FieldDefinition $field,
97
        \GraphQL\Language\AST\DirectiveNode $directive
98
    ): void {
99 1
        $type1 = $generator->getLowerName();
100 1
        $type2 = mb_strtolower($generator->getInflector()->singularize($field->name));
101
102 1
        if (strcasecmp($type1, $type2) < 0) { // TODO: check this, might not work
103
            $relationship = mb_strtolower($generator->getInflector()->pluralize($field->name));
104
            $generator->extraCode[] = self::makeManyToManySeed($type1, $type2, $relationship);
105
        }
106 1
    }
107
108
    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

108
    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...
109
    {
110
        return <<<EOF
111
112
        try {
113
            \${$targetModel}Items = App\\Models\\$targetModel::all();
114
            \$model->{$relationship}()->attach(
115
                \${$targetModel}Items->random(rand(1, 3))->pluck('id')->toArray()
116
            );
117
        }
118
        catch (\InvalidArgumentException \$e) {
119
            \$model->{$relationship}()->attach(
120
                \${$targetModel}Items->random(1)->pluck('id')->toArray()
121
            );
122
        }
123
EOF;
124
    }
125
}
126