1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MathieuTu\JsonSyncer\Helpers; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Str; |
7
|
|
|
|
8
|
|
|
class RelationsInModelFinder |
9
|
|
|
{ |
10
|
|
|
private $model; |
11
|
|
|
private $relationsType; |
12
|
|
|
|
13
|
17 |
|
public function __construct(Model $model, array $relationsType) |
14
|
|
|
{ |
15
|
17 |
|
$this->model = $model; |
16
|
17 |
|
$this->relationsType = $relationsType; |
17
|
17 |
|
} |
18
|
|
|
|
19
|
17 |
|
public static function hasOneOrMany(Model $model): array |
20
|
|
|
{ |
21
|
17 |
|
return (new static($model, ['hasMany', 'hasOne']))->find(); |
22
|
|
|
} |
23
|
|
|
|
24
|
17 |
|
protected function find(): array |
25
|
|
|
{ |
26
|
17 |
|
return collect(get_class_methods($this->model))->sort() |
27
|
17 |
|
->reject(function ($method) { |
28
|
17 |
|
return $this->isAnEloquentMethod($method); |
29
|
17 |
|
})->filter(function ($method) { |
30
|
17 |
|
$code = $this->getMethodCode($method); |
31
|
|
|
|
32
|
17 |
|
return collect($this->relationsType)->contains(function ($relation) use ($code) { |
33
|
17 |
|
return Str::contains($code, '$this->' . $relation . '('); |
34
|
17 |
|
}); |
35
|
17 |
|
})->toArray(); |
36
|
|
|
} |
37
|
|
|
|
38
|
17 |
|
protected function isAnEloquentMethod($method): bool |
39
|
|
|
{ |
40
|
17 |
|
return Str::startsWith($method, 'get') || |
41
|
17 |
|
Str::startsWith($method, 'set') || |
42
|
17 |
|
Str::startsWith($method, 'scope') || |
43
|
17 |
|
method_exists(Model::class, $method); |
44
|
|
|
} |
45
|
|
|
|
46
|
17 |
|
protected function getMethodCode($method): string |
47
|
|
|
{ |
48
|
17 |
|
$reflection = new \ReflectionMethod($this->model, $method); |
49
|
|
|
|
50
|
17 |
|
$file = new \SplFileObject($reflection->getFileName()); |
51
|
17 |
|
$file->seek($reflection->getStartLine() - 1); |
52
|
|
|
|
53
|
17 |
|
$code = ''; |
54
|
17 |
|
while ($file->key() < $reflection->getEndLine()) { |
55
|
17 |
|
$code .= $file->current(); |
56
|
17 |
|
$file->next(); |
57
|
|
|
} |
58
|
|
|
|
59
|
17 |
|
$code = trim(preg_replace('/\s\s+/', '', $code)); |
60
|
|
|
|
61
|
17 |
|
return $code; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|