1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Staudenmeir\EloquentHasManyDeep\IdeHelper; |
4
|
|
|
|
5
|
|
|
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; |
6
|
|
|
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface; |
7
|
|
|
use Exception; |
8
|
|
|
use Illuminate\Database\Eloquent\Collection; |
9
|
|
|
use Illuminate\Database\Eloquent\Model; |
10
|
|
|
use Illuminate\Support\Str; |
11
|
|
|
use ReflectionClass; |
12
|
|
|
use ReflectionMethod; |
13
|
|
|
use Staudenmeir\EloquentHasManyDeep\HasManyDeep; |
14
|
|
|
use Staudenmeir\EloquentHasManyDeep\HasOneDeep; |
15
|
|
|
use Staudenmeir\EloquentHasManyDeep\HasRelationships; |
16
|
|
|
|
17
|
|
|
class DeepRelationsHook implements ModelHookInterface |
18
|
|
|
{ |
19
|
2 |
|
public function run(ModelsCommand $command, Model $model): void |
20
|
|
|
{ |
21
|
2 |
|
$traits = class_uses_recursive($model); |
22
|
|
|
|
23
|
2 |
|
if (!in_array(HasRelationships::class, $traits)) { |
24
|
|
|
return; |
25
|
|
|
} |
26
|
|
|
|
27
|
2 |
|
$methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC); |
28
|
|
|
|
29
|
2 |
|
foreach ($methods as $method) { |
30
|
2 |
|
if ($method->isStatic() || $method->getNumberOfParameters() > 0) { |
31
|
2 |
|
continue; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
try { |
35
|
2 |
|
$relation = $method->invoke($model); |
36
|
2 |
|
} catch (Exception) { |
37
|
2 |
|
continue; |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
if (!$relation instanceof HasManyDeep) { |
41
|
2 |
|
continue; |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
$this->addRelation($command, $method, $relation); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
protected function addRelation(ModelsCommand $command, ReflectionMethod $method, HasManyDeep $relation): void |
49
|
|
|
{ |
50
|
2 |
|
$isHasOneDeep = $relation instanceof HasOneDeep; |
51
|
|
|
|
52
|
2 |
|
$type = $isHasOneDeep |
53
|
2 |
|
? '\\' . $relation->getRelated()::class |
54
|
2 |
|
: '\\' . Collection::class . '|\\' . $relation->getRelated()::class . '[]'; |
55
|
|
|
|
56
|
2 |
|
$command->setProperty( |
57
|
2 |
|
$method->getName(), |
58
|
2 |
|
$type, |
59
|
2 |
|
true, |
60
|
2 |
|
false, |
61
|
2 |
|
'', |
62
|
2 |
|
$isHasOneDeep |
63
|
2 |
|
); |
64
|
|
|
|
65
|
2 |
|
if (!$isHasOneDeep) { |
66
|
2 |
|
$command->setProperty( |
67
|
2 |
|
Str::snake($method->getName()) . '_count', |
68
|
2 |
|
'int', |
69
|
2 |
|
true, |
70
|
2 |
|
false, |
71
|
2 |
|
null, |
72
|
2 |
|
true |
73
|
2 |
|
); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|