Skip to content

Commit

Permalink
Avoid extra object allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Dec 29, 2023
1 parent 3de79a6 commit 6f852fa
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ function weakClosure(\Closure $closure): \Closure
return $closure;
}

$reference = \WeakReference::create($that);

// For internal classes use \Closure::bindTo() without scope.
$scope = $reflection->getClosureScopeClass();
$useBindTo = !$scope || $that::class !== $scope->name || $scope->isInternal();
Expand All @@ -158,15 +160,13 @@ function weakClosure(\Closure $closure): \Closure
}
} else {
// Rebind to remove reference to $that
$closure = $closure->bindTo(new \stdClass());
$closure = $closure->bindTo($reference);
}

if (!$closure) {
throw new \RuntimeException('Unable to rebind function to type ' . ($scope?->name ?? $that::class));
throw new \RuntimeException('Unable to rebind closure scoped to ' . ($scope?->name ?? $that::class));
}

$reference = \WeakReference::create($that);

/** @var \Closure(mixed...):TReturn */
return static function (mixed ...$args) use ($reference, $closure, $useBindTo): mixed {
$that = $reference->get();
Expand Down

0 comments on commit 6f852fa

Please sign in to comment.