| 1 |
<?php |
| 2 |
|
| 3 |
use Illuminate\Support\Traits\ReflectsClosures; |
| 4 |
|
| 5 |
if (! function_exists('lazy')) { |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
function lazy($class, $callback = 0, $options = 0, $eager = []) |
| 18 |
{ |
| 19 |
static $closureReflector; |
| 20 |
|
| 21 |
$closureReflector ??= new class |
| 22 |
{ |
| 23 |
use ReflectsClosures; |
| 24 |
|
| 25 |
public function typeFromParameter($callback) |
| 26 |
{ |
| 27 |
return $this->firstClosureParameterType($callback); |
| 28 |
} |
| 29 |
}; |
| 30 |
|
| 31 |
[$class, $callback, $options] = is_string($class) |
| 32 |
? [$class, $callback, $options] |
| 33 |
: [$closureReflector->typeFromParameter($class), $class, $callback ?: $options]; |
| 34 |
|
| 35 |
$reflectionClass = new ReflectionClass($class); |
| 36 |
|
| 37 |
$instance = $reflectionClass->newLazyGhost(function ($instance) use ($callback) { |
| 38 |
$result = $callback($instance); |
| 39 |
|
| 40 |
if (is_array($result)) { |
| 41 |
$instance->__construct(...$result); |
| 42 |
} |
| 43 |
}, $options); |
| 44 |
|
| 45 |
foreach ($eager as $property => $value) { |
| 46 |
$reflectionClass->getProperty($property)->setRawValueWithoutLazyInitialization($instance, $value); |
| 47 |
} |
| 48 |
|
| 49 |
return $instance; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
if (! function_exists('proxy')) { |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
function proxy($class, $callback = 0, $options = 0, $eager = []) |
| 66 |
{ |
| 67 |
static $closureReflector; |
| 68 |
|
| 69 |
$closureReflector = new class |
| 70 |
{ |
| 71 |
use ReflectsClosures; |
| 72 |
|
| 73 |
public function get($callback) |
| 74 |
{ |
| 75 |
return $this->closureReturnTypes($callback)[0] ?? $this->firstClosureParameterType($callback); |
| 76 |
} |
| 77 |
}; |
| 78 |
|
| 79 |
[$class, $callback, $options] = is_string($class) |
| 80 |
? [$class, $callback, $options] |
| 81 |
: [$closureReflector->get($class), $class, $callback ?: $options]; |
| 82 |
|
| 83 |
$reflectionClass = new ReflectionClass($class); |
| 84 |
|
| 85 |
$proxy = $reflectionClass->newLazyProxy(function () use ($callback, $eager, &$proxy) { |
| 86 |
$instance = $callback($proxy, $eager); |
| 87 |
|
| 88 |
return $instance; |
| 89 |
}, $options); |
| 90 |
|
| 91 |
foreach ($eager as $property => $value) { |
| 92 |
$reflectionClass->getProperty($property)->setRawValueWithoutLazyInitialization($proxy, $value); |
| 93 |
} |
| 94 |
|
| 95 |
return $proxy; |
| 96 |
} |
| 97 |
} |