|
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
|
|
|
return $this->items()->all(); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
protected function items(): Collection |
|
23
|
|
|
{ |
|
24
|
|
|
$class = new ReflectionClass($this); |
|
25
|
|
|
|
|
26
|
|
|
$publicProperties = collect($class->getProperties(ReflectionProperty::IS_PUBLIC)) |
|
27
|
|
|
->reject(function (ReflectionProperty $property) { |
|
28
|
|
|
return $this->shouldIgnore($property->getName()); |
|
29
|
|
|
}) |
|
30
|
|
|
->mapWithKeys(function (ReflectionProperty $property) { |
|
31
|
|
|
return [$property->getName() => $this->{$property->getName()}]; |
|
32
|
|
|
}); |
|
33
|
|
|
|
|
34
|
|
|
$publicMethods = collect($class->getMethods(ReflectionMethod::IS_PUBLIC)) |
|
35
|
|
|
->reject(function (ReflectionMethod $method) { |
|
36
|
|
|
return $this->shouldIgnore($method->getName()); |
|
37
|
|
|
}) |
|
38
|
|
|
->mapWithKeys(function (ReflectionMethod $method) { |
|
39
|
|
|
return [$method->getName() => $this->createVariableFromMethod($method)]; |
|
40
|
|
|
}); |
|
41
|
|
|
|
|
42
|
|
|
return $publicProperties->merge($publicMethods); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
protected function shouldIgnore(string $methodName): bool |
|
46
|
|
|
{ |
|
47
|
|
|
if (Str::startsWith($methodName, '__')) { |
|
48
|
|
|
return true; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
return in_array($methodName, $this->ignoredMethods()); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
protected function ignoredMethods(): array |
|
55
|
|
|
{ |
|
56
|
|
|
return array_merge([ |
|
57
|
|
|
'toArray', |
|
58
|
|
|
'toResponse', |
|
59
|
|
|
'view', |
|
60
|
|
|
], $this->ignore); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
protected function createVariableFromMethod(ReflectionMethod $method) |
|
64
|
|
|
{ |
|
65
|
|
|
if ($method->getNumberOfParameters() === 0) { |
|
66
|
|
|
return $this->{$method->getName()}(); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return Closure::fromCallable([$this, $method->getName()]); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|