RelationMapper   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 68
rs 10
c 0
b 0
f 0

2 Methods

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