debugging wp_cron jobs with XDebug in Eclipse

I just found the answer to my question over on stackoverflow…and thought I’d copy the answer over here for future reference since WP folks are probably more likely to look here.

When WP_Cron fires a scheduled job it does so via a call to wp_remote_post(). The trick in that answer is to hook into cron_request and add the XDEBUG_SESSION_START=idekey query arg, as in

add_action ('cron_request', 'wpse_cron_add_xdebug_session_start', 10, 2) ;

function
wpse_cron_add_xdebug_session_start ($args, $doing_cron)
{
    $args['url'] = add_query_arg (array ('XDEBUG_SESSION_START' => 'ECLIPSE_DBGP'), $args['url']) ;

    return ($args) ;
}

That worked like a charm and I got my cron function debugged.

With my immediate need out of the way, I wanted a more general solution…one in which I didn’t have to hard-code a specific IDE Key and this is what I came up with:

add_action ('cron_request', 'wpse_cron_add_xdebug_cookie', 10, 2) ;

/**
 * Allow debugging of wp_cron jobs
 *
 * @param array $cron_request_array
 * @param string $doing_wp_cron
 *
 * @return array $cron_request_array with the current XDEBUG_SESSION cookie added if set
 */
function
wpse_cron_add_xdebug_cookie ($cron_request_array, $doing_wp_cron)
{
    if (empty ($_COOKIE['XDEBUG_SESSION'])) {
        return ($cron_request_array) ;
        }

    if (empty ($cron_request_array['args']['cookies'])) {
        $cron_request_array['args']['cookies'] = array () ;
        }
    $cron_request_array['args']['cookies']['XDEBUG_SESSION'] = $_COOKIE['XDEBUG_SESSION'] ;

    return ($cron_request_array) ;
}

I hope this helps others who have the same problem.