Skip to main content

saola_kit/context/
mod.rs

1pub mod hosts;
2pub(crate) mod perm;
3pub mod route_index;
4pub mod router;
5
6pub use hosts::{ContextError, ContextHosts};
7pub use route_index::{
8    ClientContextMeta, ClientLinkEntry, ClientLinks, ContextLinksRule, ContextSpec, ContextTarget,
9    HrefOptions, RouteEntry, RouteIndex,
10};
11pub use router::{
12    ContextRoute, ContextRoutes, SetCurrentContext, SharedRouteIndex, join_uri,
13};
14
15const CONTEXT_KEY: &str = "saola.current_context";
16
17/// Registry of declared Saola contexts and routes, used to build a [`RouteIndex`].
18#[derive(Debug, Clone, Default)]
19pub struct ContextRegistry {
20    contexts: Vec<ContextSpec>,
21    routes: Vec<RouteEntry>,
22    #[cfg(feature = "permission")]
23    permissions: saola_permission::RoutePermissionRegistry,
24}
25
26impl ContextRegistry {
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    pub fn add_context(&mut self, spec: ContextSpec) -> &mut Self {
32        self.contexts.push(spec);
33        self
34    }
35
36    pub fn add_route(&mut self, entry: RouteEntry) -> &mut Self {
37        self.routes.push(entry);
38        self
39    }
40
41    /// Permission matrix filled in as routes are named under `permission`-aware scopes; hand it to
42    /// `saola_permission::RouteAccess` for `can_route` and the permission catalog.
43    #[cfg(feature = "permission")]
44    pub fn permissions(&self) -> &saola_permission::RoutePermissionRegistry {
45        &self.permissions
46    }
47
48    #[cfg(feature = "permission")]
49    pub(crate) fn permissions_mut(&mut self) -> &mut saola_permission::RoutePermissionRegistry {
50        &mut self.permissions
51    }
52
53    pub fn contexts(&self) -> &[ContextSpec] {
54        &self.contexts
55    }
56
57    pub fn routes(&self) -> &[RouteEntry] {
58        &self.routes
59    }
60
61    pub fn build_index(&self, primary_url: &str) -> Result<RouteIndex, ContextError> {
62        let mut sorted_contexts = self.contexts.clone();
63        sorted_contexts.sort_by(|a, b| b.priority.cmp(&a.priority).then_with(|| a.slug.cmp(&b.slug)));
64        RouteIndex::new(sorted_contexts, self.routes.clone(), primary_url)
65    }
66}
67
68/// Records the active Saola context slug in the current Laravel request context.
69pub fn set_current_context(slug: &str) {
70    laravel::context::add_hidden(CONTEXT_KEY, slug);
71}
72
73/// Returns the active Saola context slug stored in the current Laravel request context, if any.
74pub fn current_context() -> Option<String> {
75    laravel::context::get_hidden::<String>(CONTEXT_KEY)
76}