Passed
Push — master ( 1dbc05...713241 )
by Bruno
03:36
created

processModelRelationshipDirective()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 52
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 7.0368

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 35
c 1
b 0
f 0
nc 8
nop 4
dl 0
loc 52
ccs 30
cts 33
cp 0.9091
crap 7.0368
rs 8.4266

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Datatypes\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 MorphManyDirective 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
46 1
        $sourceTypeName = $generator->getBaseName();
47 1
        $targetTypeName = $lowerName;
48 1
        $relationship = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $relationship is dead and can be removed.
Loading history...
49 1
        $isInverse = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $isInverse is dead and can be removed.
Loading history...
50 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...
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\MorphMany')
76 1
            ->setPublic()
77 1
            ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
78
79 1
        $datatypeName = $generator->getRelationshipDatatypeName(
80 1
            $relationship,
81
            $isInverse,
82
            $sourceTypeName,
83
            $targetTypeName
84
        );
85 1
        return DatatypeFactory::factory($datatypeName);
86
    }
87
88
    public static function processSeedTypeDirective(
89
        SeedGenerator $generator,
90
        \GraphQL\Language\AST\DirectiveNode $directive
91
    ): void {
92
        // empty
93
    }
94
95 1
    public static function processSeedFieldDirective(
96
        SeedGenerator $generator,
97
        \GraphQL\Type\Definition\FieldDefinition $field,
98
        \GraphQL\Language\AST\DirectiveNode $directive
99
    ): void {
100 1
        $type1 = $generator->getLowerName();
101 1
        $type2 = $generator->getInflector()->singularize($field->name);
102
103 1
        if (strcasecmp($type1, $type2) < 0) { // TODO: check this, might not work
104
            $relationship = lcfirst($generator->getInflector()->pluralize($field->name));
105
            $generator->extraCode[] = self::makeManyToManySeed($type1, $type2, $relationship);
106
        }
107 1
    }
108
109
    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

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