PHP kills

PHP provides developers with the exit function to “output a message and terminate the current script”.
While testing the code below

/**
 * Redirects not logged-in visitors to a custom login page
 * @return none
 */
public function redirect_to_member_login()
{
    // logged-in users go their usual way
    if ($this->functions->is_user_logged_in()) 
    return;
    // only attempt redirection if visiting the login page
    $pagenow = $this->globals->pagenow();
    if ( null !== $pagenow && $pagenow == 'wp-login.php') {

        return;
    }
    // do not attempt redirection if the redirect points to the default login page
    $custom_login_page_url = $this->get_custom_login_page_url();
    if ($custom_login_page_url == '') {

        return;
    }
    if ($this->should_redirect()) {
        $this->functions->wp_redirect($custom_login_page_url);
        exit();
    }
}

PHPUnit silently died many times before I could find the problem: the exit function the WordPress codex suggests using right after the wp_redirect function killed the PHP process the tests where running into: if only there was a way to avoid exiting during tests…
[caption id=“attachment_242” align=“aligncenter” width=“1024”]PHPUnit black screen of death PHPUnit black screen of death[/caption]

My first bad idea

Like the title states my first solution to the problem was born out of ignorance of a better solution and consisted in conditionally exiting if a constant is not defined or it’s set to false

/**
 * Redirects not logged-in visitors to a custom login page
 * @return none
 */
public function redirect_to_member_login()
{
    // logged-in users go their usual way
    if ($this->functions->is_user_logged_in()) 
    return;
    // only attempt redirection if visiting the login page
    $pagenow = $this->globals->pagenow();
    if ( null !== $pagenow && $pagenow == 'wp-login.php') {

        return;
    }
    // do not attempt redirection if the redirect points to the default login page
    $custom_login_page_url = $this->get_custom_login_page_url();
    if ($custom_login_page_url == '') {

        return;
    }
    if ($this->should_redirect()) {
        $this->functions->wp_redirect($custom_login_page_url);
        if (!defined('OVERRIDE_EXITS') || 'OVERRIDE_EXITS' == false) {
            exit();
        }
    }
}

This is a bad idea because I am presuming I will remember to set the constant, and the ones that will follow, each time. And also modifying my code adding a constant value smells bad.

Someone else’s better idea

Turns out the creator of PHPUnit, Sebastian Bergmann, run into the same problem and created some handy test helpers that will solve the problem just by using the function set_exit_overload in my test functions. Brilliant.