Skip to content

Instantly share code, notes, and snippets.

@cs278
Created September 3, 2026 11:26
Show Gist options
  • Select an option

  • Save cs278/0ed0f562a5038f79657a5d9bc7cc16e8 to your computer and use it in GitHub Desktop.

Select an option

Save cs278/0ed0f562a5038f79657a5d9bc7cc16e8 to your computer and use it in GitHub Desktop.
Helpful PHPUnit helpers
<?php
trait HelpersTrait
{
/**
* Execute a callback with a custom error handler for the life of the callback.
*
* This is useful to suppress targeted PHP errors/warnings/notices.
*
* The error handler should return true to suppress an error, false to trigger
* the default PHP handler or null to defer to the previously registered error
* handler.
*
* @template TResult
*
* @param callable(int,string,?string,?int,array<mixed>):?bool $errorHandler
* @param \Closure():TResult $callback
*
* @return \Closure():TResult
*/
private static function withErrorHandler(callable $errorHandler, \Closure $callback): mixed
{
$currentHandler = \get_error_handler();
\set_error_handler(function (int $code, string $message, ?string $file, ?int $line, array $context = []) use ($currentHandler, $errorHandler): bool {
$result = $errorHandler($code, $message, $file, $line, $context);
if ($result === null) {
if ($currentHandler === null) {
return false;
}
return $currentHandler($code, $message, $file, $line, $context);
}
return $result;
}, \E_ALL);
try {
return $callback();
} finally {
\restore_error_handler();
}
}
/**
* Execute a given callback so that it runs with Zend assertions disabled.
*
* @template TReturn
*
* @param \Closure():TReturn $callback
*
* @return TReturn
*/
private static function withoutZendAssertions(\Closure $callback): mixed
{
// When zend assertions are disabled (as opposed to inactive) then
// there is nothing to do.
if (\ini_get('zend.assertions') === '-1') {
return $callback();
}
$oldValue = ini_set('zend.assertions', '0');
try {
return $callback();
} finally {
ini_set('zend.assertions', $oldValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment