Passed
Push — master ( 8a3253...7e9f7a )
by Jonas
13:23
created

MergedRelationsHook   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 96.43%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 47
ccs 27
cts 28
cp 0.9643
rs 10
wmc 8

2 Methods

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