/
SupportLegacyComputedPropertySyntax.php
74 lines (61 loc) · 2.29 KB
/
SupportLegacyComputedPropertySyntax.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace Livewire\Features\SupportComputed;
use Livewire\ComponentHook;
use Livewire\Drawer\Utils as SyntheticUtils;
use function Livewire\on;
use function Livewire\store;
use function Livewire\wrap;
class SupportLegacyComputedPropertySyntax extends ComponentHook
{
static function provide()
{
on('__get', function ($target, $property, $returnValue) {
if (static::hasComputedProperty($target, $property)) {
$returnValue(static::getComputedProperty($target, $property));
}
});
on('__unset', function ($target, $property) {
if (static::hasComputedProperty($target, $property)) {
store($target)->unset('computedProperties', $property);
}
});
}
public static function getComputedProperties($target)
{
return collect(static::getComputedPropertyNames($target))
->mapWithKeys(function ($property) use ($target) {
return [$property => static::getComputedProperty($target, $property)];
})
->all();
}
public static function hasComputedProperty($target, $property)
{
return array_search((string) str($property)->camel(), static::getComputedPropertyNames($target)) !== false;
}
public static function getComputedProperty($target, $property)
{
if (! static::hasComputedProperty($target, $property)) {
throw new \Exception('No computed property found: $'.$property);
}
$method = 'get'.str($property)->studly().'Property';
store($target)->push(
'computedProperties',
$value = store($target)->find('computedProperties', $property, fn() => wrap($target)->$method()),
$property,
);
return $value;
}
public static function getComputedPropertyNames($target)
{
$methodNames = SyntheticUtils::getPublicMethodsDefinedBySubClass($target);
return collect($methodNames)
->filter(function ($method) {
return str($method)->startsWith('get')
&& str($method)->endsWith('Property');
})
->map(function ($method) {
return (string) str($method)->between('get', 'Property')->camel();
})
->all();
}
}