ViewModel::ignoredMethods()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\BladeX;
4
5
use Closure;
6
use Illuminate\Contracts\Support\Arrayable;
7
use Illuminate\Support\Str;
8
use ReflectionClass;
9
use ReflectionMethod;
10
use ReflectionProperty;
11
12
abstract class ViewModel implements Arrayable
13
{
14
    protected $ignore = [];
15
16
    public function toArray(): array
17
    {
18
        $class = new ReflectionClass($this);
19
20
        $publicProperties = collect($class->getProperties(ReflectionProperty::IS_PUBLIC))
21
            ->reject(function (ReflectionProperty $property) {
22
                return $this->shouldIgnore($property->getName());
23
            })
24
            ->mapWithKeys(function (ReflectionProperty $property) {
25
                return [$property->getName() => $this->{$property->getName()}];
26
            });
27
28
        $publicMethods = collect($class->getMethods(ReflectionMethod::IS_PUBLIC))
29
            ->reject(function (ReflectionMethod $method) {
30
                return $this->shouldIgnore($method->getName());
31
            })
32
            ->mapWithKeys(function (ReflectionMethod $method) {
33
                return [$method->getName() => $this->createVariableFromMethod($method)];
34
            });
35
36
        return $publicProperties->merge($publicMethods)->all();
37
    }
38
39
    protected function shouldIgnore(string $methodName): bool
40
    {
41
        if (Str::startsWith($methodName, '__')) {
42
            return true;
43
        }
44
45
        return in_array($methodName, $this->ignoredMethods());
46
    }
47
48
    protected function ignoredMethods(): array
49
    {
50
        return array_merge([
51
            'toArray',
52
            'toResponse',
53
            'view',
54
        ], $this->ignore);
55
    }
56
57
    protected function createVariableFromMethod(ReflectionMethod $method)
58
    {
59
        if ($method->getNumberOfParameters() === 0) {
60
            return $this->{$method->getName()}();
61
        }
62
63
        return Closure::fromCallable([$this, $method->getName()]);
64
    }
65
}
66