Completed
Push — master ( efdc7e...8e7c5b )
by Maarten
01:54 queued 12s
created

RelationMapper::map()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.2888
c 0
b 0
f 0
cc 5
nc 5
nop 1
1
<?php
2
3
namespace Mtolhuys\LaravelSchematics\Services;
4
5
use Illuminate\Database\Eloquent\Relations\Relation;
6
7
use ReflectionException;
8
use Illuminate\Support\Collection;
9
use ReflectionClass;
10
use ReflectionMethod;
11
12
class RelationMapper extends ClassReader
13
{
14
    public static $relations = [];
15
16
    /**
17
     * Maps relations details map through array of Eloquent models
18
     *
19
     * @param null $models
20
     * @return array
21
     * @throws ReflectionException
22
     */
23
    public static function map($models = null): array
24
    {
25
        $models = $models ?? ModelMapper::map();
26
27
        foreach ($models as $model) {
28
            foreach (self::getMethods($model) as $method) {
29
                $details = self::getDetails($method, $model);
30
31
                if ($details) {
32
                    if (empty(self::$relations[$details->table])) {
33
                        self::$relations[$details->table] = [];
34
                    }
35
36
                    self::$relations[$details->table][] = $details;
37
                }
38
            }
39
        }
40
41
        return self::$relations;
42
    }
43
44
    /**
45
     * @param ReflectionMethod $method
46
     * @param string $model
47
     * @return object|null
48
     */
49
    protected static function getDetails(ReflectionMethod $method, string $model)
50
    {
51
        try {
52
            $class = app($model);
53
            $invocation = $method->invoke($class);
54
55
            if ($invocation instanceof Relation) {
56
                $related = $invocation->getRelated();
57
58
                return (object)[
59
                    'model' => $model,
60
                    'table' => $class->getTable(),
61
                    'type' => (new ReflectionClass($invocation))->getShortName(),
62
                    'relation' => (object)[
63
                        'model' => get_class($related),
64
                        'table' => $related->getTable(),
65
                    ],
66
                    'method' => (object)[
67
                        'name' => $method->getName(),
68
                        'file' => $method->getFileName(),
69
                        'line' => $method->getStartLine(),
70
                    ],
71
                ];
72
            }
73
        } catch (\Throwable $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
74
75
        return null;
76
    }
77
78
}
79