Passed
Push — master ( c0a95b...c5e7d6 )
by Bruno
04:51
created

processModelRelationshipDirective()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 50
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 7.0403

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 34
nc 8
nop 3
dl 0
loc 50
ccs 29
cts 32
cp 0.9063
crap 7.0403
rs 8.4426
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 MorphToManyDirective 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
        \GraphQL\Language\AST\DirectiveNode $directive
28
    ): void {
29
        // nothing
30 1
    }
31
32 1
    public static function processModelRelationshipDirective(
33
        ModelGenerator $generator,
34
        \GraphQL\Type\Definition\FieldDefinition $field,
35
        \GraphQL\Language\AST\DirectiveNode $directive
36
    ): string {
37 1
        $name = $directive->name->value;
38 1
        list($type, $isRequired) = Parser::getUnwrappedType($field->type);
39 1
        $typeName = $type->name;
40
41 1
        $lowerName = mb_strtolower($generator->getInflector()->singularize($field->name));
42 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...
43
44 1
        $sourceTypeName = $generator->getLowerName();
45 1
        $targetTypeName = $lowerName;
46 1
        $relationship = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $relationship is dead and can be removed.
Loading history...
47 1
        $isInverse = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isInverse is dead and can be removed.
Loading history...
48 1
        $generateRandom = true; // TODO
0 ignored issues
show
Unused Code introduced by
The assignment to $generateRandom is dead and can be removed.
Loading history...
49
50 1
        $relationship = RelationshipFactory::MORPH_ONE_TO_MANY;
51 1
        $isInverse = false;
52
53 1
        $targetType = $generator->parser->getType($typeName);
54 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...
55
            throw new Exception("Cannot get type {$typeName} as a relationship to {$this->baseName}");
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using $this inside a static method is generally not recommended and can lead to errors in newer PHP versions.
Loading history...
56 1
        } elseif (!($targetType instanceof ObjectType)) {
57
            throw new Exception("{$typeName} is not a type for a relationship to {$this->baseName}");
0 ignored issues
show
Bug Best Practice introduced by
The property baseName does not exist on Modelarium\Laravel\Directives\MorphToManyDirective. Did you maybe forget to declare it?
Loading history...
58
        }
59 1
        $targetField = null;
60 1
        foreach ($targetType->getFields() as $subField) {
61 1
            $subDir = Parser::getDirectives($subField->astNode->directives);
62 1
            if (array_key_exists('morphTo', $subDir) || array_key_exists('morphedByMany', $subDir)) {
63 1
                $targetField = $subField->name;
64 1
                break;
65
            }
66
        }
67 1
        if (!$targetField) {
68
            throw new Exception("{$targetType} does not have a '@morphTo' or '@morphToMany' field");
69
        }
70
71 1
        $generator->class->addMethod($field->name)
72 1
            ->setReturnType('\Illuminate\Database\Eloquent\Relations\MorphToMany')
73 1
            ->setPublic()
74 1
            ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
75
76
77 1
        return $generator->getRelationshipDatatypeName(
78 1
            $relationship,
79
            $isInverse,
80
            $sourceTypeName,
81
            $targetTypeName
82
        );
83
    }
84
85 1
    public static function processSeedFieldDirective(
86
        SeedGenerator $generator,
87
        \GraphQL\Type\Definition\FieldDefinition $field,
88
        \GraphQL\Language\AST\DirectiveNode $directive
89
    ): void {
90 1
        $type1 = $generator->getLowerName();
91 1
        $type2 = mb_strtolower($generator->getInflector()->singularize($field->name));
92
93 1
        if (strcasecmp($type1, $type2) < 0) { // TODO: check this, might not work
94 1
            $relationship = mb_strtolower($generator->getInflector()->pluralize($field->name));
95 1
            $generator->extraCode[] = self::makeManyToManySeed($type1, $type2, $relationship);
96
        }
97 1
    }
98
99 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

99
    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...
100
    {
101
        return <<<EOF
102
103
        try {
104 1
            \${$targetModel}Items = App\\Models\\$targetModel::all();
105 1
            \$model->{$relationship}()->attach(
106 1
                \${$targetModel}Items->random(rand(1, 3))->pluck('id')->toArray()
107
            );
108
        }
109
        catch (\InvalidArgumentException \$e) {
110 1
            \$model->{$relationship}()->attach(
111 1
                \${$targetModel}Items->random(1)->pluck('id')->toArray()
112
            );
113
        }
114
EOF;
115
    }
116
}
117