Passed
Push — master ( d5bfdb...c7ecad )
by Jonas
18:10 queued 05:37
created

MergedRelationsHook::addRelationship()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 13
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 18
ccs 15
cts 15
cp 1
crap 1
rs 9.8333
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; // @codeCoverageIgnore
25
        }
26
27 4
        $methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC);
28
29 4
        foreach ($methods as $method) {
30 4
            if ($method->isAbstract() || $method->isStatic() || !$method->isPublic()
31 4
                || $method->getNumberOfParameters() > 0 || $method->getDeclaringClass()->getName() === Model::class) {
32 4
                continue;
33
            }
34
35
            try {
36 4
                $relationship = $method->invoke($model);
37
            } catch (Throwable) { // @codeCoverageIgnore
38
                continue; // @codeCoverageIgnore
39
            }
40
41 4
            if ($relationship instanceof MergedRelation) {
42 4
                $this->addRelationship($command, $method, $relationship);
43
            }
44
        }
45
    }
46
47 4
    protected function addRelationship(ModelsCommand $command, ReflectionMethod $method, Relation $relationship): void
48
    {
49 4
        $type = '\\' . Collection::class . '|\\' . $relationship->getRelated()::class . '[]';
50
51 4
        $command->setProperty(
52 4
            $method->getName(),
53 4
            $type,
54 4
            true,
55 4
            false
56 4
        );
57
58 4
        $command->setProperty(
59 4
            Str::snake($method->getName()) . '_count',
60 4
            'int',
61 4
            true,
62 4
            false,
63 4
            null,
64 4
            true
65 4
        );
66
    }
67
}
68