Skip to content
Merged
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
19 changes: 8 additions & 11 deletions src/Once.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,23 @@ final class Once
*/
private mixed $value;

/**
* @var \Closure(T): bool
*/
private readonly mixed $isAlive;

private bool $isResolved = false;

/**
* @param \Closure(): T $function
* @param ?\Closure(T): bool $isAlive
*/
public function __construct(
private readonly \Closure $function,
?\Closure $isAlive = null,
) {
$this->isAlive = $isAlive ?? static fn(): true => true;
}
private \Closure $function,
private readonly ?\Closure $isAlive = null,
) {}

/**
* @return T
*/
public function await(?Cancellation $cancellation = null): mixed
{
if ($this->isResolved && ($this->isAlive)($this->value)) {
if ($this->isResolved && ($this->isAlive === null || ($this->isAlive)($this->value))) {
return $this->value;
}

Expand All @@ -63,6 +56,10 @@ public function await(?Cancellation $cancellation = null): mixed

$this->isResolved = true;

if ($this->isAlive === null) {
$this->function = static fn() => throw new \LogicException('Function has been freed from memory');
}

return $this->value;
}
}
14 changes: 14 additions & 0 deletions tests/OnceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,18 @@ static function (): int {
self::assertSame(2, $once->await());
self::assertSame(2, $once->await());
}

public function testFunctionIsFreedIfIsAliveIsNull(): void
{
$value = new \stdClass();
$weakValue = \WeakReference::create($value);
$once = new Once(static fn() => $value::class);
unset($value);

self::assertNotNull($weakValue->get());

$once->await();

self::assertNull($weakValue->get());
}
}