use laravel::config::{Config, Env, Section};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::view::{Engine, Html, Template, TemplateError};
#[derive(Debug, Clone, Section)]
pub struct SwordSettings {
#[env("SWORD_CACHE_CAPACITY", default = 128)]
pub cache_capacity: usize,
#[env("SWORD_DUMP", default = false)]
pub dump: bool,
}
#[derive(Debug, Clone)]
pub struct SwordServiceProvider {
cache: std::sync::Arc<crate::cache::Cache>,
components: std::sync::Arc<crate::component::Components>,
capacity: Option<usize>,
dump: Option<bool>,
}
impl Default for SwordServiceProvider {
fn default() -> Self {
Self::new()
}
}
impl SwordServiceProvider {
pub fn new() -> Self {
let components = std::sync::Arc::new(crate::component::Components::default());
Self {
cache: std::sync::Arc::new(crate::cache::Cache::new(128, components.clone())),
components,
capacity: None,
dump: None,
}
}
#[cfg(feature = "dump")]
pub fn dump(mut self, enabled: bool) -> Self {
self.dump = Some(enabled);
self
}
pub fn with_cache_capacity(mut self, capacity: usize) -> Self {
let capacity = capacity.min(crate::MAX_CACHE_CAPACITY);
self.cache =
std::sync::Arc::new(crate::cache::Cache::new(capacity, self.components.clone()));
self.capacity = Some(capacity);
self
}
pub fn component<T: crate::Component>(
mut self,
name: &str,
) -> Result<Self, crate::ComponentError> {
let mut components = (*self.components).clone();
components.register::<T>(name)?;
self.components = std::sync::Arc::new(components);
self.cache = std::sync::Arc::new(crate::cache::Cache::new(
self.cache.stats().capacity,
self.components.clone(),
));
Ok(self)
}
pub fn cache_stats(&self) -> crate::CacheStats {
self.cache.stats()
}
}
impl SwordServiceProvider {
fn dump_requested(&self, config: &Config) -> bool {
self.dump
.unwrap_or_else(|| config.section::<SwordSettings>().dump)
}
}
impl ServiceProvider for SwordServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
fn register(&self, app: &mut Registrar) {
if self.capacity.is_none() {
let wanted = app.config().section::<SwordSettings>().cache_capacity;
self.cache
.set_capacity(wanted.min(crate::MAX_CACHE_CAPACITY));
}
let dump = self.dump_requested(app.config());
app.views().engine(
"sword.html",
SwordEngine {
cache: self.cache.clone(),
dump,
},
);
}
async fn boot(&self, app: &Container) -> laravel::Result<()> {
#[cfg(feature = "dump")]
{
let config = app.config();
let environment = config.app.env.as_str();
if self.dump_requested(config) && !crate::dump::development(environment) {
return Err(laravel::abort_with(
500,
format!(
"@dump is enabled but the environment is `{environment}`; \
it only runs in `local` or `testing`. Disable it (SWORD_DUMP or \
SwordServiceProvider::dump) outside development."
),
));
}
}
#[cfg(not(feature = "dump"))]
let _ = app;
Ok(())
}
}
struct LaravelHost {
environment: String,
session: Option<laravel::session::Session>,
}
impl crate::host::Host for LaravelHost {
fn environment(&self) -> &str {
&self.environment
}
fn session(&self, key: &str) -> Result<Option<serde_json::Value>, String> {
self.session
.as_ref()
.map(|session| session.get::<serde_json::Value>(key))
.ok_or_else(|| {
"this route has no session; routes in the `web` group start one".to_owned()
})
}
fn context(&self, key: &str) -> Result<Option<serde_json::Value>, String> {
if laravel::context::Context::current().is_none() {
return Err("no context is available outside the application".to_owned());
}
Ok(laravel::context::get::<serde_json::Value>(key))
}
fn vite(&self, entries: &[String]) -> Result<String, String> {
if laravel::context::Context::current().is_none() {
return Err("@vite needs the application, which is not running".to_owned());
}
Ok(laravel::view::vite(entries).into_string())
}
fn vite_react_refresh(&self) -> Result<String, String> {
if laravel::context::Context::current().is_none() {
return Err("@viteReactRefresh needs the application, which is not running".to_owned());
}
Ok(laravel::view::vite_react_refresh().into_string())
}
}
struct SwordEngine {
cache: std::sync::Arc<crate::cache::Cache>,
dump: bool,
}
impl SwordEngine {
fn dump_allowed(&self, environment: &str) -> bool {
#[cfg(feature = "dump")]
{
self.dump && crate::dump::development(environment)
}
#[cfg(not(feature = "dump"))]
{
let _ = (self.dump, environment);
false
}
}
}
impl Engine for SwordEngine {
fn render(&self, template: &Template<'_>) -> laravel::Result<Html> {
let source = template.source()?;
if template.is_plain_text() {
return Err(TemplateError::new(
"Sword does not support plain-text rendering",
template.path(),
)
.into());
}
let mut data = template.data();
data.remove("__sword_csrf");
if let Some(session) = template.session() {
data.insert("__sword_csrf".into(), session.token().into());
}
let finder = template.finder().clone();
let cache = self.cache.clone();
let trusted: Vec<String> = template
.data_layers()
.markup
.iter()
.map(|(name, _)| name.clone())
.collect();
let span = tracing::debug_span!("sword.render", view = template.name(), source = "laravel");
let _entered = span.enter();
let started = std::time::Instant::now();
let job = crate::backend::Job {
name: template.name(),
source: &source,
root_path: Some(template.path().to_path_buf()),
trusted: &trusted,
fragment: template.block(),
dump: self.dump_allowed(template.config().app.env.as_str()),
host: std::sync::Arc::new(LaravelHost {
environment: template.config().app.env.as_str().to_owned(),
session: template.session().cloned(),
}),
};
let rendered = crate::backend::render_with_loader(job, &data, cache, move |name| {
let file = match finder.find_with(name, &["sword.html"]) {
Ok(file) => file,
Err(laravel::view::ViewError::NotFound { .. }) => return Ok(None),
Err(e) => {
return Err(minijinja::Error::new(
minijinja::ErrorKind::TemplateNotFound,
e.to_string(),
));
}
};
let path = file.path.clone();
file.contents()
.map(|source| {
Some(crate::backend::TemplateSource {
text: source.into_owned(),
path: Some(path),
})
})
.map_err(|e| {
minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, e.to_string())
})
})
.inspect(|html| crate::record_success(html, started))
.inspect_err(|error| crate::record_failure(error, started))
.map_err(|error| {
let (failed_name, line) = match &error {
crate::Error::Syntax { template, line, .. }
| crate::Error::Render { template, line, .. } => {
(Some(template.as_str()), Some(*line))
}
crate::Error::RenderUnlocated { template, .. } => (Some(template.as_str()), None),
_ => (None, None),
};
let dependency = failed_name
.filter(|name| *name != template.name())
.and_then(|name| template.finder().find_with(name, &["sword.html"]).ok());
let path = dependency
.as_ref()
.map_or_else(|| template.path().to_path_buf(), |file| file.path.clone());
let contents = dependency
.and_then(|file| file.contents().ok())
.unwrap_or_else(|| source.clone());
let mut mapped = TemplateError::new(error.to_string(), path).contents(contents);
if let Some(line) = line {
mapped = mapped.line(line);
}
mapped.caused_by(error)
})?;
Ok(Html::raw(rendered))
}
}