How do I access "current' draft $page object from Error Page Controller?

I have a multi-language setup. When a non-Panel user tries to access a draft page, such as example.com/test-page or example.com/es/pagina-de-prueba the user gets an Error page (as expected).

What I’m trying to do is figure out how to get the actual $page object for the draft—if it exists. The $page object given to the controller is the Error Page itself.

The easy part seems like it would be calling:

$site->draft($pageID); // e.g.: `test-page`

But I’m not sure of the most reliable way to get the “uri” of the current URL, particularly with handling the nuances of the non-default languages.

I’m hoping there’s an easy way to ask the Kirby router for what it thinks the id/uri would be (accounting for the current site language).

Good question. I’m not sure there is a better way then to test if the first part of the request path is in the array of language codes or not.

Thanks for the suggestion.

Ended up being a bit easier/straightforward than I was expecting, because the Router will have already detected the expected language and the $site object will reflect that, so I just ask for its URL and strip that away.

return function($site)
{
    $siteUrl = $site->url() . '/';
    $currentUrl = Url::stripFragment(Url::stripQuery(Url::current()));
    
    $draft = null;
    if (strpos($currentUrl, $siteUrl) === 0) {
        $uri = substr($currentUrl, strlen($siteUrl));
        $draft = $site->draft($uri);
    }
    
/// ...