BelongsToThroughRelationsHook::run()   B
last analyzed

Complexity

Conditions 10
Paths 6

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 10
eloc 14
c 3
b 0
f 0
nc 6
nop 2
dl 0
loc 24
rs 7.6666

How to fix   Complexity   

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
2
3
namespace Staudenmeir\BelongsToThrough\IdeHelper;
4
5
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
6
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use ReflectionClass;
10
use ReflectionMethod;
11
use Throwable;
12
use Znck\Eloquent\Relations\BelongsToThrough as BelongsToThroughRelation;
13
use Znck\Eloquent\Traits\BelongsToThrough as BelongsToThroughTrait;
14
15
class BelongsToThroughRelationsHook implements ModelHookInterface
16
{
17
    public function run(ModelsCommand $command, Model $model): void
18
    {
19
        $traits = class_uses_recursive($model);
20
21
        if (!in_array(BelongsToThroughTrait::class, $traits)) {
22
            return; // @codeCoverageIgnore
23
        }
24
25
        $methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC);
26
27
        foreach ($methods as $method) {
28
            if ($method->isAbstract() || $method->isStatic() || !$method->isPublic()
29
                || $method->getNumberOfParameters() > 0 || $method->getDeclaringClass()->getName() === Model::class) {
30
                continue;
31
            }
32
33
            try {
34
                $relationship = $method->invoke($model);
35
            } catch (Throwable) { // @codeCoverageIgnore
36
                continue; // @codeCoverageIgnore
37
            }
38
39
            if ($relationship instanceof BelongsToThroughRelation) {
40
                $this->addRelationship($command, $method, $relationship);
41
            }
42
        }
43
    }
44
45
    /**
46
     * @param \Illuminate\Database\Eloquent\Relations\Relation<\Illuminate\Database\Eloquent\Model> $relationship
47
     */
48
    protected function addRelationship(ModelsCommand $command, ReflectionMethod $method, Relation $relationship): void
49
    {
50
        $type = '\\' . $relationship->getRelated()::class;
51
52
        $command->setProperty(
53
            $method->getName(),
54
            $type,
55
            true,
56
            false,
57
            '',
58
            true
59
        );
60
    }
61
}
62