laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
use crate::current;
use crate::params::{IntoParams, Params};
use crate::pattern;
use crate::registry::{Entry, Registry};

/// The URL of a localized route, as PHP's `route()` builds it.
///
/// `route("es.dashboard")` is the Spanish route. `route("dashboard")` is the route of the current
/// locale: laralocale's `locale()`.
///
/// ```ignore
/// laralang::route("posts.show", [("slug", "hola")])?;   // https://example.com/es/articulos/hola
/// laralang::route("dashboard", ())?;
/// ```
///
/// Parameters that the URI does not name become the query string. Use [`route_with`] for a relative
/// URL.
///
/// # Errors
///
/// Fails with a `500` when no route has the name, or a required parameter is missing.
///
/// # Panics
///
/// Panics outside the application.
#[track_caller]
pub fn route(name: &str, params: impl IntoParams) -> laravel::Result<String> {
    route_with(name, params, true)
}

/// [`route`] with its third parameter: whether the URL is absolute.
///
/// # Errors
///
/// As [`route`].
///
/// # Panics
///
/// Panics outside the application.
#[track_caller]
pub fn route_with(name: &str, params: impl IntoParams, absolute: bool) -> laravel::Result<String> {
    let registry = Registry::current();

    url_in(&registry, name, params.into_params(), absolute)
}

/// Whether a localized route has this name. `has("dashboard")` looks at the current locale's.
///
/// # Panics
///
/// Panics outside the application.
pub fn has(name: &str) -> bool {
    let registry = Registry::current();

    find(&registry, name).is_some()
}

pub(crate) fn find(registry: &Registry, name: &str) -> Option<std::sync::Arc<Entry>> {
    let settings = registry.settings();
    let already_localized = name
        .split_once('.')
        .is_some_and(|(prefix, _)| settings.has_locale(prefix));

    if !already_localized && let Some(entry) = registry.get(&format!("{}.{name}", laralocale::locale())) {
        return Some(entry);
    }

    registry.get(name)
}

pub(crate) fn url_in(registry: &Registry, name: &str, params: Params, absolute: bool) -> laravel::Result<String> {
    let entry =
        find(registry, name).ok_or_else(|| laravel::Error::msg(format!("the route `{name}` is not defined")))?;

    url_of(&entry, params, absolute)
}

pub(crate) fn url_of(entry: &Entry, mut params: Params, absolute: bool) -> laravel::Result<String> {
    let mut path = pattern::fill(&entry.uri, &mut params).map_err(laravel::Error::msg)?;

    if !params.named.is_empty() {
        let query: Vec<String> = params
            .named
            .iter()
            .map(|(key, value)| format!("{}={}", pattern::encode_query(key), pattern::encode_query(value)))
            .collect();

        path = format!("{path}?{}", query.join("&"));
    }

    Ok(if absolute { laravel::url::to(&path) } else { path })
}

/// Whether the current route is one of these, whatever its locale, as PHP's `routeIs()` does for
/// localized routes.
///
/// A plain pattern such as `services` matches `en.services`, `es.services` and the rest. A
/// pattern that starts with a locale, such as `es.services`, only matches while that is the
/// current locale. `*` matches anything, so `services*` matches `es.services.show`.
///
/// ```ignore
/// laralang::route_is(&["services"]);       // true on /servicios and on /services
/// laralang::route_is(&["es.services"]);    // true only on /servicios
/// laralang::route_is(&["services*"]);      // true on es.services.show too
/// ```
///
/// Returns `false` outside a localized route, and for a route that has no name.
pub fn route_is(patterns: &[&str]) -> bool {
    let Some(registry) = Registry::try_current() else {
        return false;
    };
    let Some(name) = current::get()
        .and_then(|current| current.route)
        .and_then(|route| route.name)
    else {
        return false;
    };
    let settings = registry.settings();
    let locale = laralocale::locale();

    patterns.iter().any(|pattern| {
        let prefix = pattern.split('.').next().unwrap_or_default();
        let has_locale_prefix = prefix != *pattern && settings.has_locale(prefix);

        if has_locale_prefix {
            return prefix == locale && wildcard(pattern, &name);
        }

        wildcard(pattern, &name)
            || settings
                .locales
                .iter()
                .any(|locale| wildcard(&format!("{locale}.{pattern}"), &name))
    })
}

/// `Str::is`: `*` matches any run of characters.
fn wildcard(pattern: &str, value: &str) -> bool {
    let parts: Vec<&str> = pattern.split('*').collect();

    if parts.len() == 1 {
        return pattern == value;
    }

    let mut rest = value;

    for (index, part) in parts.iter().enumerate() {
        if index == 0 {
            let Some(after) = rest.strip_prefix(part) else {
                return false;
            };

            rest = after;
        } else if index == parts.len() - 1 {
            return rest.ends_with(part);
        } else if let Some(found) = rest.find(part) {
            rest = &rest[found + part.len()..];
        } else {
            return false;
        }
    }

    true
}

#[cfg(test)]
mod tests {
    use super::wildcard;

    #[test]
    fn wildcards_match_like_str_is() {
        assert!(wildcard("es.services", "es.services"));
        assert!(wildcard("*.services", "es.services"));
        assert!(wildcard("es.services*", "es.services.show"));
        assert!(wildcard("*services*", "fr.services.create"));
        assert!(!wildcard("services", "es.services"));
        assert!(!wildcard("fr.services*", "es.services.show"));
        assert!(wildcard("*", "anything"));
    }
}