MorphToManyDirective::makeManyToManySeed()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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

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