Passed
Push — master ( 7a0761...b9ca99 )
by Bruno
03:45
created

processModelRelationshipDirective()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 53
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 7.0336

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 36
nc 8
nop 4
dl 0
loc 53
ccs 31
cts 34
cp 0.9118
crap 7.0336
rs 8.4106
c 1
b 0
f 0

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->type);
42 1
        $typeName = $type->name;
43
44 1
        $lowerName = mb_strtolower($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->getLowerName();
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
        $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...
52 1
        $generateRandom = true; // TODO
0 ignored issues
show
Unused Code introduced by
The assignment to $generateRandom is dead and can be removed.
Loading history...
53
54 1
        $relationship = RelationshipFactory::MORPH_ONE_TO_MANY;
55 1
        $isInverse = false;
56
57 1
        $targetType = $generator->parser->getType($typeName);
58 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...
59
            throw new Exception("Cannot get type {$typeName} as a relationship to {$generator->getBaseName()}");
60 1
        } elseif (!($targetType instanceof ObjectType)) {
61
            throw new Exception("{$typeName} is not a type for a relationship to {$generator->getBaseName()}");
62
        }
63 1
        $targetField = null;
64 1
        foreach ($targetType->getFields() as $subField) {
65 1
            $subDir = Parser::getDirectives($subField->astNode->directives);
66 1
            if (array_key_exists('morphTo', $subDir) || array_key_exists('morphedByMany', $subDir)) {
67 1
                $targetField = $subField->name;
68 1
                break;
69
            }
70
        }
71 1
        if (!$targetField) {
72
            throw new Exception("{$targetType} does not have a '@morphTo' or '@morphToMany' field");
73
        }
74
75 1
        $generator->class->addMethod($field->name)
76 1
        ->setReturnType('\Illuminate\Database\Eloquent\Relations\MorphMany')
77 1
            ->setPublic()
78 1
            ->setBody("return \$this->{$name}($typeName::class, '$targetField');");
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 = mb_strtolower($generator->getInflector()->singularize($field->name));
103
104 1
        if (strcasecmp($type1, $type2) < 0) { // TODO: check this, might not work
105
            $relationship = mb_strtolower($generator->getInflector()->pluralize($field->name));
106
            $generator->extraCode[] = self::makeManyToManySeed($type1, $type2, $relationship);
107
        }
108 1
    }
109
110
    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
        return <<<EOF
113
114
        try {
115
            \${$targetModel}Items = App\\Models\\$targetModel::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