Passed
Push — master ( cab6b5...845ff4 )
by Bruno
04:13 queued 01:09
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
       \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
        $generateRandom = true; // TODO
0 ignored issues
show
Unused Code introduced by
The assignment to $generateRandom is dead and can be removed.
Loading history...
50
51 1
        $relationship = RelationshipFactory::MORPH_ONE_TO_MANY;
52 1
        $isInverse = false;
53
54 1
        $targetType = $generator->parser->getType($typeName);
55 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...
56
            throw new Exception("Cannot get type {$typeName} as a relationship to {$generator->getBaseName()}");
57 1
        } elseif (!($targetType instanceof ObjectType)) {
58
            throw new Exception("{$typeName} is not a type for a relationship to {$generator->getBaseName()}");
59
        }
60 1
        $targetField = null;
61 1
        foreach ($targetType->getFields() as $subField) {
62 1
            $subDir = Parser::getDirectives($subField->astNode->directives);
63 1
            if (array_key_exists('morphTo', $subDir) || array_key_exists('morphedByMany', $subDir)) {
64 1
                $targetField = $subField->name;
65 1
                break;
66
            }
67
        }
68 1
        if (!$targetField) {
69
            throw new Exception("{$targetType} does not have a '@morphTo' or '@morphToMany' field");
70
        }
71
72 1
        $generator->class->addMethod($field->name)
73 1
            ->setReturnType('\Illuminate\Database\Eloquent\Relations\MorphToMany')
74 1
            ->setPublic()
75 1
            ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
76
77
78 1
        return $generator->getRelationshipDatatypeName(
79 1
            $relationship,
80
            $isInverse,
81
            $sourceTypeName,
82
            $targetTypeName
83
        );
84
    }
85
86
    public static function processSeedTypeDirective(
87
        SeedGenerator $generator,
88
        \GraphQL\Language\AST\DirectiveNode $directive
89
    ): void {
90
        // empty
91
    }
92
93 1
    public static function processSeedFieldDirective(
94
        SeedGenerator $generator,
95
        \GraphQL\Type\Definition\FieldDefinition $field,
96
        \GraphQL\Language\AST\DirectiveNode $directive
97
    ): void {
98 1
        $type1 = $generator->getLowerName();
99 1
        $type2 = mb_strtolower($generator->getInflector()->singularize($field->name));
100
101 1
        if (strcasecmp($type1, $type2) < 0) { // TODO: check this, might not work
102 1
            $relationship = mb_strtolower($generator->getInflector()->pluralize($field->name));
103 1
            $generator->extraCode[] = self::makeManyToManySeed($type1, $type2, $relationship);
104
        }
105 1
    }
106
107 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

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