Skip to content

Instantly share code, notes, and snippets.

@imliam
Last active March 13, 2018 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imliam/e802bc7545f01a3d5ad997b1ab83b975 to your computer and use it in GitHub Desktop.
Save imliam/e802bc7545f01a3d5ad997b1ab83b975 to your computer and use it in GitHub Desktop.
<?php
if (! function_exists('catch_exit')) {
/**
* Catch when a part of a script exits and execute a custom function at
* that point. Note that if exiting, the script does not continue.
* You can use this to, for example, flash a message and
* redirect the user instead of showing the default
* black text on white background "exit" view.
*
* @param Closure $run
* @param mixed $fallback
* @return mixed
*/
function catch_exit($run, $fallback)
{
$shouldExit = true;
register_shutdown_function(function () use ($fallback, &$shouldExit) {
if (! $shouldExit) {
return;
}
$exitMessage = ob_get_contents();
if ($exitMessage) {
ob_end_clean();
}
if (is_object($fallback) && $fallback instanceof Closure) {
$result = $fallback($exitMessage);
} else {
$result = $fallback;
}
echo $result;
});
ob_start();
$result = $run();
ob_end_clean();
$shouldExit = false;
return $result;
}
}
if (! function_exists('catch_die')) {
/**
* Alias for catch_exit
*/
function catch_die(...$args)
{
return catch_exit(...$args);
}
}
@imliam
Copy link
Author

imliam commented Feb 23, 2018

Example usage:

$var = catch_exit(function() {
    return "It's all okay.";
}, "This is a custom exit message.");

echo $var; // "It's all okay."
$var = catch_exit(function() {
    exit;
    return "It's all okay.";
}, "This is a custom exit message.");

// The script exits before this point, displaying the vanilla 'exit' page
// with a white background and black text saying:
// "This is a custom exit message." 

echo $var;
$var = catch_exit(function() {
    return "It's all okay.";
}, function($message) {
    return "This is the original exit message: '{$message}'";
});

echo $var; // "It's all okay."
$var = catch_exit(function() {
    exit('Uh-oh, something went wrong!');
    return "It's all okay.";
}, function($message) {
    // Using Laravel 5's helper functions
    return back()->withInput()->with('error', "An error occurred: '{$message}'");
});

// The script exits before this point, however the redirect is ran and an error is
// flashed to the session, ready to be displayed to the user:
// "An error occurred: 'Uh-oh, something went wrong!'"

echo $var;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment