MergedRelationsHook   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 28
c 3
b 0
f 0
dl 0
loc 48
rs 10
wmc 11

2 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 24 10
A addRelationship() 0 18 1
1
<?php
2
3
namespace Staudenmeir\LaravelMergedRelations\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\LaravelMergedRelations\Eloquent\HasMergedRelationships;
14
use Staudenmeir\LaravelMergedRelations\Eloquent\Relations\MergedRelation;
15
use Throwable;
16
17
class MergedRelationsHook implements ModelHookInterface
18
{
19
    public function run(ModelsCommand $command, Model $model): void
20
    {
21
        $traits = class_uses_recursive($model);
22
23
        if (!in_array(HasMergedRelationships::class, $traits)) {
24
            return; // @codeCoverageIgnore
25
        }
26
27
        $methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC);
28
29
        foreach ($methods as $method) {
30
            if ($method->isAbstract() || $method->isStatic() || !$method->isPublic()
31
                || $method->getNumberOfParameters() > 0 || $method->getDeclaringClass()->getName() === Model::class) {
32
                continue;
33
            }
34
35
            try {
36
                $relationship = $method->invoke($model);
37
            } catch (Throwable) { // @codeCoverageIgnore
38
                continue; // @codeCoverageIgnore
39
            }
40
41
            if ($relationship instanceof MergedRelation) {
42
                $this->addRelationship($command, $method, $relationship);
43
            }
44
        }
45
    }
46
47
    protected function addRelationship(ModelsCommand $command, ReflectionMethod $method, Relation $relationship): void
48
    {
49
        $type = '\\' . Collection::class . '|\\' . $relationship->getRelated()::class . '[]';
50
51
        $command->setProperty(
52
            $method->getName(),
53
            $type,
54
            true,
55
            false
56
        );
57
58
        $command->setProperty(
59
            Str::snake($method->getName()) . '_count',
60
            'int',
61
            true,
62
            false,
63
            null,
64
            true
65
        );
66
    }
67
}
68