|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Staudenmeir\BelongsToThrough\IdeHelper; |
|
4
|
|
|
|
|
5
|
|
|
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; |
|
6
|
|
|
use Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface; |
|
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
8
|
|
|
use Illuminate\Database\Eloquent\Relations\Relation; |
|
9
|
|
|
use ReflectionClass; |
|
10
|
|
|
use ReflectionMethod; |
|
11
|
|
|
use Throwable; |
|
12
|
|
|
use Znck\Eloquent\Relations\BelongsToThrough as BelongsToThroughRelation; |
|
13
|
|
|
use Znck\Eloquent\Traits\BelongsToThrough as BelongsToThroughTrait; |
|
14
|
|
|
|
|
15
|
|
|
class BelongsToThroughRelationsHook implements ModelHookInterface |
|
16
|
|
|
{ |
|
17
|
|
|
public function run(ModelsCommand $command, Model $model): void |
|
18
|
|
|
{ |
|
19
|
|
|
$traits = class_uses_recursive($model); |
|
20
|
|
|
|
|
21
|
|
|
if (!in_array(BelongsToThroughTrait::class, $traits)) { |
|
22
|
|
|
return; // @codeCoverageIgnore |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
$methods = (new ReflectionClass($model))->getMethods(ReflectionMethod::IS_PUBLIC); |
|
26
|
|
|
|
|
27
|
|
|
foreach ($methods as $method) { |
|
28
|
|
|
if ($method->isAbstract() || $method->isStatic() || !$method->isPublic() |
|
29
|
|
|
|| $method->getNumberOfParameters() > 0 || $method->getDeclaringClass()->getName() === Model::class) { |
|
30
|
|
|
continue; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
try { |
|
34
|
|
|
$relationship = $method->invoke($model); |
|
35
|
|
|
} catch (Throwable) { // @codeCoverageIgnore |
|
36
|
|
|
continue; // @codeCoverageIgnore |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
if ($relationship instanceof BelongsToThroughRelation) { |
|
40
|
|
|
$this->addRelationship($command, $method, $relationship); |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param \Illuminate\Database\Eloquent\Relations\Relation<\Illuminate\Database\Eloquent\Model> $relationship |
|
47
|
|
|
*/ |
|
48
|
|
|
protected function addRelationship(ModelsCommand $command, ReflectionMethod $method, Relation $relationship): void |
|
49
|
|
|
{ |
|
50
|
|
|
$type = '\\' . $relationship->getRelated()::class; |
|
51
|
|
|
|
|
52
|
|
|
$command->setProperty( |
|
53
|
|
|
$method->getName(), |
|
54
|
|
|
$type, |
|
55
|
|
|
true, |
|
56
|
|
|
false, |
|
57
|
|
|
'', |
|
58
|
|
|
true |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|