use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use laralocale::LocaleConfig;
use laravel::config::Config;
use laravel::context::Context;
use crate::config::LaralangConfig;
use crate::pattern;
#[derive(Debug, Clone)]
pub struct Settings {
pub locales: Vec<String>,
pub default_locale: String,
pub session_key: String,
prefixes: HashMap<String, String>,
pub fallback: bool,
pub redirect_max_age: u64,
}
impl Settings {
pub fn from_config(config: &Config) -> Self {
let own = config
.get::<LaralangConfig>()
.cloned()
.unwrap_or_else(|| LaralangConfig {
locales: Vec::new(),
prefixes: HashMap::new(),
fallback: false,
redirect_max_age: 86_400,
});
let locale = config.get::<LocaleConfig>().cloned().unwrap_or_default();
let locales = if !own.locales.is_empty() {
own.locales.clone()
} else if !locale.supported.is_empty() {
locale.supported.clone()
} else {
vec![locale.locale.clone()]
};
Self {
locales,
default_locale: locale.locale.clone(),
session_key: locale.detect.session.clone(),
prefixes: own.prefixes,
fallback: own.fallback,
redirect_max_age: own.redirect_max_age,
}
}
pub fn prefix(&self, locale: &str) -> String {
let configured = self.prefixes.get(locale).map_or("", String::as_str).trim_matches('/');
if !configured.is_empty() {
return configured.to_owned();
}
if locale == self.default_locale {
String::new()
} else {
locale.to_owned()
}
}
pub fn prefixes(&self) -> Vec<(String, String)> {
self.locales
.iter()
.map(|locale| (locale.clone(), self.prefix(locale)))
.collect()
}
pub fn has_locale(&self, locale: &str) -> bool {
self.locales.iter().any(|configured| configured == locale)
}
}
#[derive(Debug, Clone)]
pub struct Entry {
pub name: Option<String>,
pub base: Option<String>,
pub locale: String,
pub uri: String,
pub methods: Vec<String>,
}
#[derive(Default)]
struct Routes {
entries: Vec<Arc<Entry>>,
by_name: HashMap<String, Arc<Entry>>,
}
#[derive(Default)]
pub struct Registry {
settings: RwLock<Option<Arc<Settings>>>,
routes: RwLock<Routes>,
}
impl Registry {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn configure(&self, settings: Settings) {
*self.settings.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::new(settings));
}
pub fn settings(&self) -> Arc<Settings> {
self.settings
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
.expect("the LaralangServiceProvider is not registered: add it to the application's providers")
}
pub fn add(&self, entry: Entry) {
let entry = Arc::new(entry);
let mut routes = self.routes.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(name) = &entry.name {
routes.by_name.insert(name.clone(), Arc::clone(&entry));
}
routes.entries.push(entry);
}
pub fn get(&self, name: &str) -> Option<Arc<Entry>> {
self.read().by_name.get(name).cloned()
}
pub fn has(&self, name: &str) -> bool {
self.read().by_name.contains_key(name)
}
pub fn entries(&self) -> Vec<Arc<Entry>> {
self.read().entries.clone()
}
pub fn serves(&self, path: &str) -> bool {
self.read()
.entries
.iter()
.any(|entry| entry.methods.iter().any(|method| method == "GET") && pattern::matches(&entry.uri, path))
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, Routes> {
self.routes.read().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn current() -> Arc<Self> {
Self::try_current()
.expect("the LaralangServiceProvider is not registered: add it to the application's providers")
}
pub fn try_current() -> Option<Arc<Self>> {
Context::current()?;
laravel::config().get::<Handle>().map(|handle| Arc::clone(&handle.0))
}
}
impl std::fmt::Debug for Registry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Registry")
.field("routes", &self.read().entries.len())
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub(crate) struct Handle(pub(crate) Arc<Registry>);
thread_local! {
static REGISTERING: RefCell<Option<Arc<Registry>>> = const { RefCell::new(None) };
}
pub(crate) fn begin_registration(registry: Arc<Registry>) {
REGISTERING.with(|current| *current.borrow_mut() = Some(registry));
}
pub(crate) fn registering() -> Arc<Registry> {
REGISTERING.with(|current| {
current.borrow().clone().expect(
"LocalizedRoute needs the LaralangServiceProvider: add it to the application's providers, \
before the route files that use it",
)
})
}