Passed
Push — master ( 19e483...625e7f )
by Mathieu
04:13
created

RelationsInModelFinder::find()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 12
ccs 9
cts 9
cp 1
crap 1
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 16
    public function __construct(Model $model, array $relationsType)
14
    {
15 16
        $this->model = $model;
16 16
        $this->relationsType = $relationsType;
17 16
    }
18
19 16
    public static function hasOneOrMany(Model $model): array
20
    {
21 16
        return (new static($model, ['hasMany', 'hasOne']))->find();
22
    }
23
24 16
    protected function find(): array
25
    {
26 16
        return collect(get_class_methods($this->model))->sort()
27 16
            ->reject(function ($method) {
28 16
                return $this->isAnEloquentMethod($method);
29
            })->filter(function ($method) {
30 16
                $code = $this->getMethodCode($method);
31
32 16
                return collect($this->relationsType)->contains(function ($relation) use ($code) {
33 16
                    return Str::contains($code, '$this->' . $relation . '(');
34 16
                });
35 16
            })->toArray();
36
    }
37
38 16
    protected function isAnEloquentMethod($method): bool
39
    {
40 16
        return Str::startsWith($method, 'get') ||
41 16
            Str::startsWith($method, 'set') ||
42 16
            Str::startsWith($method, 'scope') ||
43 16
            method_exists(Model::class, $method);
44
    }
45
46 16
    protected function getMethodCode($method): string
47
    {
48 16
        $reflection = new \ReflectionMethod($this->model, $method);
49
50 16
        $file = new \SplFileObject($reflection->getFileName());
51 16
        $file->seek($reflection->getStartLine() - 1);
52
53 16
        $code = '';
54 16
        while ($file->key() < $reflection->getEndLine()) {
55 16
            $code .= $file->current();
56 16
            $file->next();
57
        }
58
59 16
        $code = trim(preg_replace('/\s\s+/', '', $code));
60
61 16
        return $code;
62
    }
63
}
64