Completed
Push — master ( 12099c...c51309 )
by Freek
01:16
created

ViewModel   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 54
rs 10
c 0
b 0
f 0

4 Methods

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