DeepRelationsHook::addRelationship()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 25
rs 9.6333
c 1
b 0
f 0
cc 3
nc 4
nop 3
1
<?php
2
3
namespace Staudenmeir\EloquentHasManyDeep\IdeHelper;
4
5
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
6
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface;
7
use Illuminate\Database\Eloquent\Collection;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10
use Illuminate\Support\Str;
11
use ReflectionClass;
12
use ReflectionMethod;
13
use Staudenmeir\EloquentHasManyDeep\HasManyDeep;
14
use Staudenmeir\EloquentHasManyDeep\HasOneDeep;
15
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
16
use Throwable;
17
18
class DeepRelationsHook implements ModelHookInterface
19
{
20
    public function run(ModelsCommand $command, Model $model): void
21
    {
22
        $traits = class_uses_recursive($model);
23
24
        if (!in_array(HasRelationships::class, $traits)) {
25
            return; // @codeCoverageIgnore
26
        }
27
28
        $methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC);
29
30
        foreach ($methods as $method) {
31
            if ($method->isAbstract() || $method->isStatic() || !$method->isPublic()
32
                || $method->getNumberOfParameters() > 0 || $method->getDeclaringClass()->getName() === Model::class) {
33
                continue;
34
            }
35
36
            try {
37
                $relationship = $method->invoke($model);
38
            } catch (Throwable) { // @codeCoverageIgnore
39
                continue; // @codeCoverageIgnore
40
            }
41
42
            if ($relationship instanceof HasManyDeep) {
43
                $this->addRelationship($command, $method, $relationship);
44
            }
45
        }
46
    }
47
48
    protected function addRelationship(ModelsCommand $command, ReflectionMethod $method, Relation $relationship): void
49
    {
50
        $manyRelation = !$relationship instanceof HasOneDeep;
51
52
        $type = $manyRelation
53
            ? '\\' . Collection::class . '|\\' . $relationship->getRelated()::class . '[]'
54
            : '\\' . $relationship->getRelated()::class;
55
56
        $command->setProperty(
57
            $method->getName(),
58
            $type,
59
            true,
60
            false,
61
            '',
62
            !$manyRelation
63
        );
64
65
        if ($manyRelation) {
66
            $command->setProperty(
67
                Str::snake($method->getName()) . '_count',
68
                'int',
69
                true,
70
                false,
71
                null,
72
                true
73
            );
74
        }
75
    }
76
}
77