Skip to content

Commit 15e99d8

Browse files
committed
Add lazy and proxy helpers
1 parent b4d8576 commit 15e99d8

File tree

3 files changed

+546
-0
lines changed

3 files changed

+546
-0
lines changed

src/Illuminate/Support/helpers.php

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Illuminate\Support\Sleep;
1414
use Illuminate\Support\Str;
1515
use Illuminate\Support\Stringable as SupportStringable;
16+
use Illuminate\Support\Traits\ReflectsClosures;
1617

1718
if (! function_exists('append_config')) {
1819
/**
@@ -196,6 +197,43 @@ function literal(...$arguments)
196197
}
197198
}
198199

200+
if (! function_exists('lazy')) {
201+
/**
202+
* Create a lazy instance.
203+
*
204+
* @template TValue of object
205+
*
206+
* @param class-string<TValue>|(\Closure(TValue): mixed) $class
207+
* @param (\Closure(TValue): mixed)|int $callback
208+
* @param int $options
209+
* @return TValue
210+
*/
211+
function lazy($class, $callback = 0, $options = 0)
212+
{
213+
static $reflector = new class
214+
{
215+
use ReflectsClosures;
216+
217+
public function get($callback)
218+
{
219+
return $this->firstClosureParameterType($callback);
220+
}
221+
};
222+
223+
[$class, $callback, $options] = is_string($class)
224+
? [$class, $callback, $options]
225+
: [$reflector->get($class), $class, $callback ?: $options];
226+
227+
return (new ReflectionClass($class))->newLazyGhost(function ($instance) use ($callback) {
228+
$result = $callback($instance);
229+
230+
if (is_array($result)) {
231+
$instance->__construct(...$result);
232+
}
233+
}, $options);
234+
}
235+
}
236+
199237
if (! function_exists('object_get')) {
200238
/**
201239
* Get an item from an object using "dot" notation.
@@ -295,6 +333,37 @@ function preg_replace_array($pattern, array $replacements, $subject): string
295333
}
296334
}
297335

336+
if (! function_exists('proxy')) {
337+
/**
338+
* Create a lazy proxy instance.
339+
*
340+
* @template TValue of object
341+
*
342+
* @param class-string<TValue>|(\Closure(TValue): TValue) $class
343+
* @param (\Closure(TValue): TValue)|int $callback
344+
* @param int $options
345+
* @return TValue
346+
*/
347+
function proxy($class, $callback = 0, $options = 0)
348+
{
349+
static $reflector = new class
350+
{
351+
use ReflectsClosures;
352+
353+
public function get($callback)
354+
{
355+
return $this->firstClosureParameterType($callback);
356+
}
357+
};
358+
359+
[$class, $callback, $options] = is_string($class)
360+
? [$class, $callback, $options]
361+
: [$reflector->get($class), $class, $callback ?: $options];
362+
363+
return (new ReflectionClass($class))->newLazyProxy($callback, $options);
364+
}
365+
}
366+
298367
if (! function_exists('retry')) {
299368
/**
300369
* Retry an operation a given number of times.

0 commit comments

Comments
 (0)