public function beforeDispatch(Event $event)
    {
        parent::beforeDispatch($event);
        $request = Router::getRequest();
        if (empty($request)) {
            throw new InternalErrorException(__d('cms', 'No request object could be found.'));
        }

        $locales = array_keys(quickapps('languages'));
        $localesPattern = '(' . implode('|', array_map('preg_quote', $locales)) . ')';
        $rawUrl = str_replace_once($request->base, '', env('REQUEST_URI'));
        $normalizedURL = str_replace('//', '/', "/{$rawUrl}");

        if (!empty($request->query['locale']) && in_array($request->query['locale'], $locales)) {
            $request->session()->write('locale', $request->query['locale']);
            I18n::locale($request->session()->read('locale'));
        } elseif (option('url_locale_prefix') && preg_match("/\/{$localesPattern}\//", $normalizedURL, $matches)) {
            I18n::locale($matches[1]);
        } elseif ($request->session()->check('locale') && in_array($request->session()->read('locale'), $locales)) {
            I18n::locale($request->session()->read('locale'));
        } elseif ($request->is('userLoggedIn') && in_array(user()->locale, $locales)) {
            I18n::locale(user()->locale);
        } elseif (in_array(option('default_language'), $locales)) {
            I18n::locale(option('default_language'));
        } else {
            I18n::locale(CORE_LOCALE);
        }

        if (option('url_locale_prefix') &&
            !$request->is('home') &&
            !preg_match("/\/{$localesPattern}\//", $normalizedURL)
        ) {
            $url = Router::url('/' . I18n::locale() . $normalizedURL, true);
            http_response_code(303);
            header("Location: {$url}");
            die;
        }
    }