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

Clean up any garbage references when awaiting rejected promise #28

Merged
merged 1 commit into from
Feb 10, 2022
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: 19 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,25 @@ function (mixed $throwable) use (&$rejected, &$rejectedThrowable, &$fiber): void
$throwable = new \UnexpectedValueException(
'Promise rejected with unexpected value of type ' . (is_object($throwable) ? get_class($throwable) : gettype($throwable))
);

// avoid garbage references by replacing all closures in call stack.
// what a lovely piece of code!
$r = new \ReflectionProperty('Exception', 'trace');
$trace = $r->getValue($throwable);

// Exception trace arguments only available when zend.exception_ignore_args is not set
// @codeCoverageIgnoreStart
foreach ($trace as $ti => $one) {
if (isset($one['args'])) {
foreach ($one['args'] as $ai => $arg) {
if ($arg instanceof \Closure) {
$trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')';
}
}
}
}
// @codeCoverageIgnoreEnd
$r->setValue($throwable, $trace);
}

if ($fiber === null) {
Expand Down
12 changes: 9 additions & 3 deletions tests/AwaitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,15 @@ public function testAwaitThrowsUnexpectedValueExceptionWhenPromiseIsRejectedWith
$reject(null);
});

$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('Promise rejected with unexpected value of type NULL');
$await($promise);
try {
$await($promise);
} catch (\UnexpectedValueException $exception) {
$this->assertInstanceOf(\UnexpectedValueException::class, $exception);
$this->assertEquals('Promise rejected with unexpected value of type NULL', $exception->getMessage());
$this->assertEquals(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
$this->assertNotEquals('', $exception->getTraceAsString());
}
}

/**
Expand Down