Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Illuminate\Support\Sleep;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable as SupportStringable;
use Illuminate\Support\Traits\ReflectsClosures;

if (! function_exists('append_config')) {
/**
Expand Down Expand Up @@ -196,6 +197,54 @@ function literal(...$arguments)
}
}

if (! function_exists('lazy') && version_compare(phpversion(), '8.4.0', '>=')) {
/**
* Create a lazy instance.
*
* @template TValue of object
*
* @param class-string<TValue>|(\Closure(TValue): mixed) $class
* @param (\Closure(TValue): mixed)|int $callback
* @param int $options
* @param array<string, mixed> $eager
* @return TValue
*/
function lazy($class, $callback = 0, $options = 0, $eager = [])
{
static $closureReflector;

$closureReflector ??= new class
{
use ReflectsClosures;

public function typeFromParameter($callback)
{
return $this->firstClosureParameterType($callback);
}
};

[$class, $callback, $options] = is_string($class)
? [$class, $callback, $options]
: [$closureReflector->typeFromParameter($class), $class, $callback ?: $options];

$reflectionClass = new ReflectionClass($class);

$instance = $reflectionClass->newLazyGhost(function ($instance) use ($callback) {
$result = $callback($instance);

if (is_array($result)) {
$instance->__construct(...$result);
}
}, $options);

foreach ($eager as $property => $value) {
$reflectionClass->getProperty($property)->setRawValueWithoutLazyInitialization($instance, $value);
}

return $instance;
}
}

if (! function_exists('object_get')) {
/**
* Get an item from an object using "dot" notation.
Expand Down Expand Up @@ -295,6 +344,39 @@ function preg_replace_array($pattern, array $replacements, $subject): string
}
}

if (! function_exists('proxy') && version_compare(phpversion(), '8.4.0', '>=')) {
/**
* Create a lazy proxy instance.
*
* @template TValue of object
*
* @param class-string<TValue>|(\Closure(TValue): TValue) $class
* @param (\Closure(TValue): TValue)|int $callback
* @param int $options
* @return TValue
*/
function proxy($class, $callback = 0, $options = 0)
{
static $closureReflector;

$closureReflector = new class
{
use ReflectsClosures;

public function typeFromParameter($callback)
{
return $this->firstClosureParameterType($callback);
}
};

[$class, $callback, $options] = is_string($class)
? [$class, $callback, $options]
: [$closureReflector->typeFromParameter($class), $class, $callback ?: $options];

return (new ReflectionClass($class))->newLazyProxy($callback, $options);
}
}

if (! function_exists('retry')) {
/**
* Retry an operation a given number of times.
Expand Down
Loading