RelationsInModelFinder::isAnEloquentMethod()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 4
nc 4
nop 1
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 4
rs 10
c 0
b 0
f 0
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