Passed
Push — master ( 2dfbed...0dc38a )
by Jonas
13:30
created

JsonRelationsHook   A

Complexity

Total Complexity 9

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 9

2 Methods

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