Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Reaper::forget() #14

Merged
merged 1 commit into from
Feb 9, 2025
Merged
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
37 changes: 33 additions & 4 deletions src/Reaper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,30 @@ final class Reaper
/** @var \WeakMap<object,list<self>> */
private static \WeakMap $dd;

private function __construct(private readonly \Closure $callback) {}
private bool $active = true;

private function __construct(
/** @var \Closure(): void */
private readonly \Closure $callback,
) {}

/**
* Detach the reaper from its target
*
* ```php
* $a = (object) [];
*
* $reaper = Reaper::watch($a, function () { echo "Good Bye"; });
* $reaper->forget();
*
* unset($b);
* // prints nothing
* ```
*/
public function forget(): void
{
$this->active = false;
}

/**
* Attach a callback to an object to be called when that object is destroyed.
Expand Down Expand Up @@ -52,16 +75,22 @@ private function __construct(private readonly \Closure $callback) {}
*
* @param callable(): void $callback
*/
public static function watch(object $subject, callable $callback): void {
public static function watch(object $subject, callable $callback): self
{
self::$dd ??= new \WeakMap();

self::$dd[$subject] ??= [];

self::$dd[$subject][] = new self(\Closure::fromCallable($callback));
return self::$dd[$subject][] = new self(\Closure::fromCallable($callback));
}

/** @nodoc */
public function __destruct() {
public function __destruct()
{
if (!$this->active) {
return;
}

($this->callback)();
}
}