use super::expr;
use super::ConvertContext;
use crate::php;
use std::path::{Path, PathBuf};
const SUPPORTED_DIRECTIVES: &[&str] = &[
"extends",
"section",
"endsection",
"yield",
"if",
"elseif",
"else",
"endif",
"foreach",
"endforeach",
"push",
"endpush",
"stack",
"csrf",
"php",
"vite",
"js",
"script",
"livewireStyles",
"livewireScripts",
];
const LEAF_UNSUPPORTED_DIRECTIVES: &[&str] = &["include", "method", "each", "livewire"];
const PAIRED_UNSUPPORTED_DIRECTIVES: &[&str] = &[
"auth",
"guest",
"can",
"isset",
"empty",
"component",
"while",
"for",
"error",
"switch",
];
const KNOWN_UNSUPPORTED_DIRECTIVES: &[&str] = &[
"endauth",
"endguest",
"cannot",
"endcan",
"endisset",
"endempty",
"endcomponent",
"endwhile",
"endfor",
"enderror",
"case",
"break",
"endswitch",
];
pub fn convert(
source: &str,
ctx: &ConvertContext,
is_top_level: bool,
) -> Result<(String, Vec<String>), String> {
if is_top_level && (source.contains("<?php") || source.contains("<?=")) {
return Err(
"contains a raw `<?php`/`<?=` tag (not Blade's own `@php ... @endphp` directive) - \
most often a Livewire Volt single-file component (a PHP class defined inline in \
the same file as its Blade markup); this needs a manual port, not just its Blade \
portion"
.to_string(),
);
}
let mut out = String::with_capacity(source.len());
let mut notes = Vec::new();
let mut pos = 0usize;
while pos < source.len() {
let rest = &source[pos..];
match find_next_marker(rest) {
None => {
out.push_str(rest);
break;
}
Some(NextMarker::Directive(offset)) => {
let at_pos = pos + offset;
out.push_str(&source[pos..at_pos]);
match scan_directive(source, at_pos, ctx, is_top_level)? {
Some((rendered, new_pos, block_notes)) => {
out.push_str(&rendered);
notes.extend(block_notes);
pos = new_pos;
}
None => {
out.push('@');
pos = at_pos + 1;
}
}
}
Some(NextMarker::Interpolation(offset, marker)) => {
let brace_pos = pos + offset;
out.push_str(&source[pos..brace_pos]);
let (rendered, new_pos, note) = scan_interpolation(source, brace_pos, marker, ctx)?;
out.push_str(&rendered);
notes.extend(note);
pos = new_pos;
}
Some(NextMarker::LivewireTag(offset)) => {
let tag_pos = pos + offset;
out.push_str(&source[pos..tag_pos]);
let (rendered, new_pos, note) = scan_livewire_tag(source, tag_pos, ctx)?;
out.push_str(&rendered);
notes.extend(note);
pos = new_pos;
}
}
}
Ok((out, notes))
}
enum NextMarker {
Directive(usize),
Interpolation(usize, Marker),
LivewireTag(usize),
}
fn find_next_marker(rest: &str) -> Option<NextMarker> {
let at = rest.find('@').map(NextMarker::Directive);
let brace = find_interpolation_start(rest)
.map(|(offset, marker)| NextMarker::Interpolation(offset, marker));
let livewire_tag = rest.find("<livewire:").map(NextMarker::LivewireTag);
[at, brace, livewire_tag]
.into_iter()
.flatten()
.min_by_key(|marker| match marker {
NextMarker::Directive(offset)
| NextMarker::Interpolation(offset, _)
| NextMarker::LivewireTag(offset) => *offset,
})
}
const DEGRADED_PLACEHOLDER: &str = "xr convert: manual port required here";
fn degraded_placeholder(ctx: &ConvertContext) -> (String, usize) {
let spot = ctx.degraded_spot_count.get() + 1;
ctx.degraded_spot_count.set(spot);
(
format!("<!-- {DEGRADED_PLACEHOLDER} (spot #{spot}) - see CONVERSION_REPORT.md -->"),
spot,
)
}
fn flatten_for_report(snippet: &str) -> String {
snippet.split_whitespace().collect::<Vec<_>>().join(" ")
}
#[derive(Clone, Copy)]
enum Marker {
DoubleBrace,
RawBrace,
BladeComment,
}
fn find_interpolation_start(s: &str) -> Option<(usize, Marker)> {
let double = s.find("{{");
let raw = s.find("{!!");
let comment = s.find("{{--");
[
(comment, Marker::BladeComment),
(raw, Marker::RawBrace),
(double, Marker::DoubleBrace),
]
.into_iter()
.filter_map(|(offset, marker)| offset.map(|offset| (offset, marker)))
.min_by_key(|(offset, _)| *offset)
}
fn scan_interpolation(
source: &str,
start: usize,
marker: Marker,
ctx: &ConvertContext,
) -> Result<(String, usize, Option<String>), String> {
let (open_len, closer) = match marker {
Marker::DoubleBrace => (2, "}}"),
Marker::RawBrace => (3, "!!}"),
Marker::BladeComment => (4, "--}}"),
};
let content_start = start + open_len;
let close_offset = source[content_start..]
.find(closer)
.ok_or_else(|| "unterminated `{{ }}`/`{!! !!}` interpolation".to_string())?;
let inner = source[content_start..content_start + close_offset].trim();
let end = content_start + close_offset + closer.len();
if matches!(marker, Marker::BladeComment) {
return Ok((format!("{{{{-- {inner} --}}}}"), end, None));
}
let Some(translated) = expr::translate_expression(inner, ctx) else {
let (placeholder, spot) = degraded_placeholder(ctx);
let note = format!(
"spot #{spot}: {{{{ }}}}/{{!! !!}} expression not supported, left for manual \
review: `{inner}`"
);
return Ok((placeholder, end, Some(note)));
};
let force_raw = matches!(marker, Marker::DoubleBrace) && inner == "$slot";
let rendered = match marker {
Marker::DoubleBrace if force_raw => format!("{{!! {translated} !!}}"),
Marker::DoubleBrace => format!("{{{{ {translated} }}}}"),
Marker::RawBrace => format!("{{!! {translated} !!}}"),
Marker::BladeComment => unreachable!("Blade comments return before expression translation"),
};
Ok((rendered, end, None))
}
struct LivewireAttr {
name: String,
dynamic: bool,
raw_value: String,
}
fn interpolation_wraps_entire_value(value: &str) -> Option<&str> {
let inner = value.strip_prefix("{{")?.strip_suffix("}}")?;
if inner.contains("{{") || inner.contains("}}") {
return None;
}
Some(inner.trim())
}
fn scan_livewire_tag(
source: &str,
tag_pos: usize,
ctx: &ConvertContext,
) -> Result<(String, usize, Option<String>), String> {
let (name, attrs, end) = scan_livewire_tag_structure(source, tag_pos)?;
let mut rendered_attrs = String::new();
for attr in &attrs {
let escaped_name = if crate::codegen::is_rust_keyword(&attr.name) {
format!("{}_", attr.name)
} else {
attr.name.clone()
};
let Ok(()) = crate::codegen::validate_identifier(&escaped_name) else {
let (placeholder, spot) = degraded_placeholder(ctx);
let note = format!(
"spot #{spot}: <livewire:{name} {}=\"...\"> attribute name isn't a valid Rust \
identifier, tag left for manual review",
attr.name
);
return Ok((placeholder, end, Some(note)));
};
let whole_value_interpolation = interpolation_wraps_entire_value(attr.raw_value.trim());
let is_dynamic = attr.dynamic || whole_value_interpolation.is_some();
if !is_dynamic {
rendered_attrs.push_str(&format!(" {escaped_name}=\"{}\"", attr.raw_value));
continue;
}
let trimmed = whole_value_interpolation.unwrap_or_else(|| attr.raw_value.trim());
let Some(translated) = expr::translate_expression(trimmed, ctx) else {
let (placeholder, spot) = degraded_placeholder(ctx);
let note = format!(
"spot #{spot}: <livewire:{name} {}=\"...\"> expression not supported, tag left \
for manual review: `{trimmed}`",
attr.name
);
return Ok((placeholder, end, Some(note)));
};
if translated.contains('\'') {
let (placeholder, spot) = degraded_placeholder(ctx);
let note = format!(
"spot #{spot}: <livewire:{name} {}=\"...\"> translated expression contains a \
`'`, which would break the surrounding attribute quoting, tag left for manual \
review: `{translated}`",
attr.name
);
return Ok((placeholder, end, Some(note)));
}
rendered_attrs.push_str(&format!(" :{escaped_name}='{translated}'"));
}
let mut has_query_binding = attrs.iter().any(|attr| attr.name == "query");
for (prop_name, escaped_name, translated_default) in livewire_component_defaults(ctx, &name) {
if attrs.iter().any(|attr| attr.name == prop_name) {
continue;
}
if translated_default.contains('\'') {
continue;
}
if prop_name == "query" {
has_query_binding = true;
}
rendered_attrs.push_str(&format!(" :{escaped_name}='{translated_default}'"));
}
if !has_query_binding {
rendered_attrs.push_str(" :query='query'");
}
Ok((
format!("<resource:livewire.{name}{rendered_attrs} />"),
end,
None,
))
}
fn livewire_component_defaults(
ctx: &ConvertContext,
tag_name: &str,
) -> Vec<(String, String, String)> {
let path = resolve_livewire_component_path(ctx.laravel_root, tag_name);
let Ok(source) = std::fs::read_to_string(&path) else {
return Vec::new();
};
let Ok(tree) = crate::php::parse(&source) else {
return Vec::new();
};
if crate::php::has_syntax_error(&tree) {
return Vec::new();
}
let Some(class_node) = find_first_class_declaration(tree.root_node()) else {
return Vec::new();
};
let Some(body) = class_node.child_by_field_name("body") else {
return Vec::new();
};
let mut defaults = Vec::new();
let bytes = source.as_bytes();
for i in 0..body.named_child_count() {
let Some(decl) = body.named_child(i) else {
continue;
};
if decl.kind() != "property_declaration" || !declaration_is_public(decl, &source) {
continue;
}
for j in 0..decl.named_child_count() {
let Some(element) = decl.named_child(j) else {
continue;
};
if element.kind() != "property_element" {
continue;
}
let Some(prop_name) = element
.child_by_field_name("name")
.and_then(|n| n.named_child(0))
.and_then(|n| n.utf8_text(bytes).ok())
else {
continue;
};
let Some(default_node) = element.child_by_field_name("default_value") else {
continue; };
let Ok(raw) = default_node.utf8_text(bytes) else {
continue;
};
let Some(translated_default) = expr::translate_expression(raw, ctx) else {
continue;
};
let escaped_name = if crate::codegen::is_rust_keyword(prop_name) {
format!("{prop_name}_")
} else {
prop_name.to_string()
};
if crate::codegen::validate_identifier(&escaped_name).is_err() {
continue;
}
defaults.push((prop_name.to_string(), escaped_name, translated_default));
}
}
defaults
}
fn declaration_is_public(decl: tree_sitter::Node, source: &str) -> bool {
for i in 0..decl.child_count() {
let Some(child) = decl.child(i) else {
continue;
};
if child.kind() == "visibility_modifier" {
return child.utf8_text(source.as_bytes()).ok() == Some("public");
}
}
false
}
fn find_first_class_declaration(root: tree_sitter::Node) -> Option<tree_sitter::Node> {
for i in 0..root.named_child_count() {
let child = root.named_child(i)?;
if child.kind() == "class_declaration" {
return Some(child);
}
}
None
}
fn resolve_livewire_component_path(laravel_root: &Path, tag_name: &str) -> PathBuf {
let mut path = laravel_root.join("app").join("Livewire");
for segment in tag_name.split('.') {
path.push(kebab_to_pascal_case(segment));
}
path.set_extension("php");
path
}
fn kebab_to_pascal_case(segment: &str) -> String {
segment
.split('-')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
})
.collect()
}
fn scan_livewire_tag_structure(
source: &str,
tag_pos: usize,
) -> Result<(String, Vec<LivewireAttr>, usize), String> {
let name_start = tag_pos + "<livewire:".len();
let rest = &source[name_start..];
let name_end = rest
.find(|c: char| c.is_whitespace() || c == '/' || c == '>')
.unwrap_or(rest.len());
if name_end == 0 {
return Err("expected a name after `<livewire:`".to_string());
}
let name = rest[..name_end].to_string();
let mut pos = name_start + name_end;
let mut attrs = Vec::new();
loop {
pos = skip_ws(source, pos);
if source[pos..].starts_with("/>") {
return Ok((name, attrs, pos + 2));
}
if source.as_bytes().get(pos) == Some(&b'>') {
let closing_tag = format!("</livewire:{name}>");
if source[pos..].contains(&closing_tag) {
return Err(format!(
"<livewire:{name}> must be self-closing ('/>') - a slot/block form isn't supported"
));
}
return Ok((name, attrs, pos + 1));
}
if pos >= source.len() {
return Err(format!("unterminated <livewire:{name}> tag, expected '/>'"));
}
let dynamic = source.as_bytes().get(pos) == Some(&b':');
if dynamic {
pos += 1;
}
let attr_name_start = pos;
let attr_name_end = source[pos..]
.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-'))
.map(|offset| pos + offset)
.unwrap_or(source.len());
if attr_name_end == attr_name_start {
return Err(format!(
"expected an attribute name in <livewire:{name}> tag"
));
}
let attr_name = source[attr_name_start..attr_name_end].to_string();
pos = skip_ws(source, attr_name_end);
if source.as_bytes().get(pos) != Some(&b'=') {
return Err(format!(
"expected '=' after attribute `{attr_name}` in <livewire:{name}> tag"
));
}
pos = skip_ws(source, pos + 1);
if source.as_bytes().get(pos) != Some(&b'"') {
return Err(format!(
"expected a double-quoted attribute value for `{attr_name}` in <livewire:{name}> tag"
));
}
let value_start = pos + 1;
let value_end = source[value_start..]
.find('"')
.map(|offset| value_start + offset)
.ok_or_else(|| {
format!("unterminated attribute value for `{attr_name}` in <livewire:{name}> tag")
})?;
attrs.push(LivewireAttr {
name: attr_name,
dynamic,
raw_value: source[value_start..value_end].to_string(),
});
pos = value_end + 1;
}
}
fn scan_directive(
source: &str,
at_pos: usize,
ctx: &ConvertContext,
is_top_level: bool,
) -> Result<Option<(String, usize, Vec<String>)>, String> {
let after_at = &source[at_pos + 1..];
let word_len = after_at
.chars()
.take_while(|c| c.is_ascii_alphabetic())
.count();
if word_len == 0 {
return Ok(None);
}
let word = &after_at[..word_len];
let word_end = at_pos + 1 + word_len;
if LEAF_UNSUPPORTED_DIRECTIVES.contains(&word) {
let (raw_args, new_pos) = parse_paren_arg(source, word_end)
.map_err(|reason| format!("@{word}(...): {reason}"))?;
let (placeholder, spot) = degraded_placeholder(ctx);
let note =
format!("spot #{spot}: @{word}({raw_args}) not supported, left for manual review");
return Ok(Some((placeholder, new_pos, vec![note])));
}
if PAIRED_UNSUPPORTED_DIRECTIVES.contains(&word) {
return scan_unsupported_paired_block(source, word, word_end, ctx);
}
if KNOWN_UNSUPPORTED_DIRECTIVES.contains(&word) {
return Err(format!("unsupported directive @{word}"));
}
if !SUPPORTED_DIRECTIVES.contains(&word) {
return Ok(None);
}
match word {
"else" | "endif" | "endsection" | "endforeach" | "endpush" | "csrf" => {
Ok(Some((format!("@{word}"), word_end, Vec::new())))
}
"livewireStyles" => Ok(Some((String::new(), word_end, Vec::new()))),
"livewireScripts" => Ok(Some(("@larustscripts".to_string(), word_end, Vec::new()))),
"script" => {
let rest = &source[word_end..];
let end = rest
.find("@endscript")
.ok_or_else(|| "unterminated @script block, expected @endscript".to_string())?;
let body = rest[..end].to_string();
Ok(Some((
body,
word_end + end + "@endscript".len(),
Vec::new(),
)))
}
"php" => {
let rest = &source[word_end..];
let end = rest
.find("@endphp")
.ok_or_else(|| "unterminated @php block, expected @endphp".to_string())?;
let body = &rest[..end];
let new_pos = word_end + end + "@endphp".len();
match expr::translate_php_block(body, ctx) {
Some(translated) => Ok(Some((
format!("@code {translated} @endcode"),
new_pos,
Vec::new(),
))),
None if is_top_level => {
let names = expr::php_block_assigned_variable_names(body);
let mut tainted = ctx.tainted_vars.borrow_mut();
tainted.extend(names.iter().cloned());
drop(tainted);
let (placeholder, spot) = degraded_placeholder(ctx);
let original = flatten_for_report(body);
let note = if names.is_empty() {
format!(
"spot #{spot}: @php block dropped, left for manual review: \
Laravel @php blocks require a manual Rust @code ... @endcode \
port unless every statement is a plain assignment this phase \
can translate; original code: `{original}`"
)
} else {
let mut sorted: Vec<&String> = names.iter().collect();
sorted.sort();
let list = sorted
.iter()
.map(|n| format!("${n}"))
.collect::<Vec<_>>()
.join(", ");
format!(
"spot #{spot}: @php block dropped, left for manual review: \
Laravel @php blocks require a manual Rust @code ... @endcode \
port unless every statement is a plain assignment this phase \
can translate; every later reference to {list} in this \
template also degrades, since this block would have assigned \
it; original code: `{original}`"
)
};
Ok(Some((placeholder, new_pos, vec![note])))
}
None => {
Err(
"Laravel @php blocks require a manual Rust @code ... @endcode port \
unless every statement is a plain `$var = <expr>;` assignment this \
phase can translate; PHP is never copied into a Larust template"
.to_string(),
)
}
}
}
"extends" | "section" | "yield" | "push" | "stack" => {
let (arg, new_pos) = parse_quoted_arg(source, word_end)
.map_err(|reason| format!("@{word}(...): {reason}"))?;
Ok(Some((format!("@{word}('{arg}')"), new_pos, Vec::new())))
}
"js" => {
let (raw, new_pos) = parse_paren_arg(source, word_end)
.map_err(|reason| format!("@js(...): {reason}"))?;
let trimmed = raw.trim();
let Some(translated) = expr::translate_expression(trimmed, ctx) else {
let (placeholder, spot) = degraded_placeholder(ctx);
let note = format!(
"spot #{spot}: @js(...) expression not supported, left for manual \
review: `{trimmed}`"
);
return Ok(Some((placeholder, new_pos, vec![note])));
};
Ok(Some((format!("@js({translated})"), new_pos, Vec::new())))
}
"vite" => {
let (raw, new_pos) = parse_paren_arg(source, word_end)
.map_err(|reason| format!("@vite(...): {reason}"))?;
let entries = parse_string_array(&raw);
if entries.is_empty() {
return Err(
"@vite(...): expected a non-empty array of asset entry paths".to_string(),
);
}
let entries_literal = entries
.iter()
.map(|entry| format!("'{entry}'"))
.collect::<Vec<_>>()
.join(", ");
Ok(Some((
format!("@vitex([{entries_literal}])"),
new_pos,
Vec::new(),
)))
}
"elseif" => {
let (raw, new_pos) = parse_paren_arg(source, word_end)
.map_err(|reason| format!("@elseif(...): {reason}"))?;
let trimmed = raw.trim();
let translated = expr::translate_expression(trimmed, ctx)
.ok_or_else(|| format!("@elseif(...) expression not supported: `{trimmed}`"))?;
Ok(Some((
format!("@elseif(larust_support::truthy::truthy(&({translated})))"),
new_pos,
Vec::new(),
)))
}
"if" => scan_if_block(source, word_end, ctx),
"foreach" => scan_foreach_block(source, word_end, ctx),
_ => unreachable!("every SUPPORTED_DIRECTIVES entry is handled above"),
}
}
fn scan_unsupported_paired_block(
source: &str,
word: &str,
word_end: usize,
ctx: &ConvertContext,
) -> Result<Option<(String, usize, Vec<String>)>, String> {
let after_head = match parse_paren_arg(source, word_end) {
Ok((_, pos)) => pos,
Err(_) => word_end,
};
let open = format!("@{word}");
let close = format!("@end{word}");
let block_end = find_matching_marker(source, after_head, &open, &close)
.ok_or_else(|| format!("unterminated @{word}, expected @end{word}"))?;
let body = &source[after_head..block_end - close.len()];
let (placeholder, spot) = degraded_placeholder(ctx);
let original = flatten_for_report(body);
let note = format!(
"spot #{spot}: @{word} ... @end{word} block dropped, left for manual review: no \
Larust equivalent for this directive; original content: `{original}`"
);
Ok(Some((placeholder, block_end, vec![note])))
}
fn scan_if_block(
source: &str,
word_end: usize,
ctx: &ConvertContext,
) -> Result<Option<(String, usize, Vec<String>)>, String> {
let (raw, after_head) =
parse_paren_arg(source, word_end).map_err(|reason| format!("@if(...): {reason}"))?;
let block_end = find_matching_marker(source, after_head, "@if", "@endif")
.ok_or_else(|| "unterminated @if, expected @endif".to_string())?;
let body = &source[after_head..block_end - "@endif".len()];
let trimmed = raw.trim();
let Some(translated) = expr::translate_expression(trimmed, ctx) else {
let (placeholder, spot) = degraded_placeholder(ctx);
let original = flatten_for_report(body);
let note = format!(
"spot #{spot}: @if(...) block dropped, left for manual review: condition not \
supported: `{trimmed}`; original body: `{original}`"
);
return Ok(Some((placeholder, block_end, vec![note])));
};
match convert(body, ctx, false) {
Ok((rendered_body, notes)) => {
let head = format!("@if(larust_support::truthy::truthy(&({translated})))");
Ok(Some((
format!("{head}{rendered_body}@endif"),
block_end,
notes,
)))
}
Err(reason) => {
let (placeholder, spot) = degraded_placeholder(ctx);
let original = flatten_for_report(body);
let note = format!(
"spot #{spot}: @if(...) block dropped, left for manual review: {reason}; \
original body: `{original}`"
);
Ok(Some((placeholder, block_end, vec![note])))
}
}
}
fn scan_foreach_block(
source: &str,
word_end: usize,
ctx: &ConvertContext,
) -> Result<Option<(String, usize, Vec<String>)>, String> {
let (raw, after_head) =
parse_paren_arg(source, word_end).map_err(|reason| format!("@foreach(...): {reason}"))?;
let block_end = find_matching_marker(source, after_head, "@foreach", "@endforeach")
.ok_or_else(|| "unterminated @foreach, expected @endforeach".to_string())?;
let body = &source[after_head..block_end - "@endforeach".len()];
let head = (|| -> Result<(String, String), String> {
let Some(as_index) = raw.find(" as ") else {
return Err(format!("@foreach(...) missing ` as `: `{}`", raw.trim()));
};
let iterable_raw = raw[..as_index].trim();
let binding_raw = raw[as_index + 4..].trim();
let mut iterable = expr::translate_expression(iterable_raw, ctx)
.ok_or_else(|| format!("@foreach(...) iterable not supported: `{iterable_raw}`"))?;
let mut binding = expr::translate_binding(binding_raw)
.ok_or_else(|| format!("@foreach(...) binding not supported: `{binding_raw}`"))?;
if expr::is_keyed_binding(binding_raw) {
iterable = format!("({iterable}).iter().enumerate()");
}
if body_references_loop_variable(source, after_head) {
iterable = format!("larust_support::WithLoop::with_loop({iterable})");
binding = format!("({binding}, loop_)");
}
Ok((binding, iterable))
})();
let (binding, iterable) = match head {
Ok(pair) => pair,
Err(reason) => {
let (placeholder, spot) = degraded_placeholder(ctx);
let original = flatten_for_report(body);
let note = format!(
"spot #{spot}: @foreach(...) block dropped, left for manual review: {reason}; \
original body: `{original}`"
);
return Ok(Some((placeholder, block_end, vec![note])));
}
};
match convert(body, ctx, false) {
Ok((rendered_body, notes)) => {
let head = format!("@foreach({binding} in {iterable})");
Ok(Some((
format!("{head}{rendered_body}@endforeach"),
block_end,
notes,
)))
}
Err(reason) => {
let (placeholder, spot) = degraded_placeholder(ctx);
let original = flatten_for_report(body);
let note = format!(
"spot #{spot}: @foreach(...) block dropped, left for manual review: {reason}; \
original body: `{original}`"
);
Ok(Some((placeholder, block_end, vec![note])))
}
}
}
fn find_matching_marker(source: &str, body_start: usize, open: &str, close: &str) -> Option<usize> {
let rest = &source[body_start..];
let mut depth: i32 = 1;
let mut pos = 0;
while depth > 0 {
let next_open = find_marker(&rest[pos..], open);
let next_close = find_marker(&rest[pos..], close);
let (marker_offset, opens) = match (next_open, next_close) {
(Some(o), Some(c)) => (o.min(c), o < c),
(Some(o), None) => (o, true),
(None, Some(c)) => (c, false),
(None, None) => return None,
};
let marker_pos = pos + marker_offset;
if opens {
depth += 1;
pos = marker_pos + open.len();
} else {
depth -= 1;
pos = marker_pos + close.len();
}
}
Some(body_start + pos)
}
fn find_marker(haystack: &str, marker: &str) -> Option<usize> {
let mut offset = 0;
loop {
let found = haystack[offset..].find(marker)?;
let match_start = offset + found;
let after = match_start + marker.len();
let is_word_boundary = haystack
.as_bytes()
.get(after)
.is_none_or(|b| !b.is_ascii_alphabetic());
if is_word_boundary {
return Some(match_start);
}
offset = match_start + 1;
}
}
fn body_references_loop_variable(source: &str, body_start: usize) -> bool {
match find_matching_marker(source, body_start, "@foreach", "@endforeach") {
Some(end) => source[body_start..end].contains("$loop->"),
None => source[body_start..].contains("$loop->"),
}
}
fn parse_string_array(text: &str) -> Vec<String> {
let inner = text.trim().trim_start_matches('[').trim_end_matches(']');
inner
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(php::unquote)
.collect()
}
fn parse_quoted_arg(source: &str, pos: usize) -> Result<(String, usize), String> {
let bytes = source.as_bytes();
let mut i = skip_ws(source, pos);
if bytes.get(i) != Some(&b'(') {
return Err("expected `(` after the directive name".to_string());
}
i += 1;
i = skip_ws(source, i);
let quote = *bytes.get(i).ok_or("unterminated directive argument")?;
if quote != b'\'' && quote != b'"' {
return Err("expected a quoted string argument".to_string());
}
i += 1;
let content_start = i;
while i < bytes.len() && bytes[i] != quote {
if bytes[i] == b'\\' {
i += 2;
} else {
i += 1;
}
}
if i >= bytes.len() {
return Err("unterminated quoted string argument".to_string());
}
let content = source[content_start..i].to_string();
i += 1;
i = skip_ws(source, i);
if bytes.get(i) != Some(&b')') {
return Err("expected a single quoted-string argument".to_string());
}
Ok((content, i + 1))
}
fn parse_paren_arg(source: &str, pos: usize) -> Result<(String, usize), String> {
let bytes = source.as_bytes();
let i = skip_ws(source, pos);
if bytes.get(i) != Some(&b'(') {
return Err("expected `(` after the directive name".to_string());
}
let content_start = i + 1;
let mut depth = 1i32;
let mut j = content_start;
let mut in_quote: Option<u8> = None;
while j < bytes.len() {
let b = bytes[j];
if let Some(quote) = in_quote {
if b == b'\\' {
j += 2;
continue;
}
if b == quote {
in_quote = None;
}
j += 1;
continue;
}
match b {
b'\'' | b'"' => in_quote = Some(b),
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
j += 1;
}
if depth != 0 {
return Err("unterminated `(...)` directive argument".to_string());
}
Ok((source[content_start..j].to_string(), j + 1))
}
fn skip_ws(source: &str, pos: usize) -> usize {
let bytes = source.as_bytes();
let mut i = pos;
while i < bytes.len() && (bytes[i] as char).is_whitespace() {
i += 1;
}
i
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_ctx {
($root:expr) => {
&ConvertContext {
laravel_root: $root,
resolved_config_keys: &std::collections::HashSet::new(),
tainted_vars: std::cell::RefCell::new(std::collections::HashSet::new()),
degraded_spot_count: std::cell::Cell::new(0),
}
};
}
#[test]
fn translates_extends_and_section() {
let source = "@extends('layouts.app')\n@section('content')\nHello\n@endsection\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@extends('layouts.app')"));
assert!(out.contains("@section('content')"));
assert!(out.contains("@endsection"));
assert!(out.contains("Hello"));
}
#[test]
fn translates_an_if_condition() {
let source = "@if($post->is_published)\nPublished\n@endif\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@if(larust_support::truthy::truthy(&(post.is_published)))"));
assert!(out.contains("@endif"));
}
#[test]
fn translates_elseif_and_else() {
let source = "@if($x == 1)\nA\n@elseif($y == 2)\nB\n@else\nC\n@endif\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@if(larust_support::truthy::truthy(&((x) == (1))))"));
assert!(out.contains("@elseif(larust_support::truthy::truthy(&((y) == (2))))"));
assert!(out.contains("@else"));
}
#[test]
fn translates_an_if_with_a_bare_variable_condition_via_the_truthy_helper() {
let source = "@if($q)\nA\n@endif\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@if(larust_support::truthy::truthy(&(q)))"));
}
#[test]
fn translates_foreach_swapping_connector_and_order() {
let source = "@foreach($posts as $post)\n{{ $post->title }}\n@endforeach\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@foreach(post in posts)"));
assert!(out.contains("{{ post.title }}"));
assert!(out.contains("@endforeach"));
}
#[test]
fn translates_a_keyed_foreach_into_a_tuple_binding_over_an_enumerated_iterator() {
let source = "@foreach($items as $key => $item)\n{{ $key }}\n@endforeach\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@foreach((key, item) in (items).iter().enumerate())"));
assert!(out.contains("{{ key }}"));
}
#[test]
fn translates_foreach_with_loop_last_into_a_with_loop_iterator_and_extra_binding() {
let source =
"@foreach($items as $key => $item)\n{{ !$loop->last ? ',' : '' }}\n@endforeach\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains(
"@foreach(((key, item), loop_) in larust_support::WithLoop::with_loop((items).iter().enumerate()))"
));
assert!(out.contains("loop_.last"));
}
#[test]
fn plain_foreach_without_a_loop_reference_is_not_wrapped_in_with_loop() {
let source = "@foreach($posts as $post)\n{{ $post->title }}\n@endforeach\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(!out.contains("with_loop"));
}
#[test]
fn a_loop_reference_in_a_sibling_foreach_does_not_affect_an_unrelated_one() {
let source = "@foreach($posts as $post)\n{{ $post->title }}\n@endforeach\n\
@foreach($tags as $tag)\n{{ !$loop->last ? ',' : '' }}\n@endforeach\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
let first_foreach_end = out.find("@endforeach").unwrap();
assert!(!out[..first_foreach_end].contains("with_loop"));
assert!(out[first_foreach_end..].contains("with_loop"));
}
#[test]
fn translates_a_keyed_foreach_using_arbitrary_variable_names_on_either_side() {
let source = "@foreach($posts as $key => $post)\n{{ $post->title }}\n@endforeach\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@foreach((key, post) in (posts).iter().enumerate())"));
assert!(out.contains("{{ post.title }}"));
}
#[test]
fn translates_double_and_raw_brace_interpolation() {
let source = "{{ $x }} and {!! $y !!}";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert_eq!(out, "{{ x }} and {!! y !!}");
}
#[test]
fn a_bare_slot_interpolation_is_forced_raw_not_escaped() {
let source = "<body>{{ $slot }}</body>";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert_eq!(out, "<body>{!! slot !!}</body>");
}
#[test]
fn a_slot_reference_inside_a_larger_expression_stays_escaped() {
let source = "{{ $slot['x'] }}";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert_eq!(out, "{{ slot[\"x\"] }}");
}
#[test]
fn livewire_styles_is_dropped_and_livewire_scripts_becomes_larustscripts() {
let source = "<head>@livewireStyles</head><body>@livewireScripts</body>";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert_eq!(out, "<head></head><body>@larustscripts</body>");
}
#[test]
fn script_directive_is_stripped_leaving_its_plain_script_tag() {
let source = "@script\n<script>console.log('hi');</script>\n@endscript";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert_eq!(out, "\n<script>console.log('hi');</script>\n");
}
#[test]
fn rejects_an_unterminated_script_block() {
let source = "@script\n<script>console.log('hi');</script>";
assert!(convert(source, test_ctx!(Path::new("/nonexistent")), true).is_err());
}
#[test]
fn blade_comments_carry_through_verbatim_as_dot_blade_xr_comments() {
let source = "{{-- {{ $not_a_value }} --}}\n{{ $value }}";
assert_eq!(
convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0,
"{{-- {{ $not_a_value }} --}}\n{{ value }}"
);
}
#[test]
fn a_blade_comment_containing_its_own_interpolation_markers_survives_verbatim() {
let source = r#"{{-- <a href="/{{config('routes.seo')}}">SEO Services</a> --}}"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert_eq!(
out,
r#"{{-- <a href="/{{config('routes.seo')}}">SEO Services</a> --}}"#
);
assert!(notes.is_empty());
}
#[test]
fn translates_csrf_push_and_stack() {
let source = "@csrf\n@push('scripts')\nx\n@endpush\n@stack('scripts')\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@csrf"));
assert!(out.contains("@push('scripts')"));
assert!(out.contains("@stack('scripts')"));
}
#[test]
fn translates_vite_into_the_equivalent_vitex_directive() {
let source = "@vite(['resources/css/app.min.css', 'resources/js/app.min.js'])";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(
out,
"@vitex(['resources/css/app.min.css', 'resources/js/app.min.js'])"
);
}
#[test]
fn a_vite_call_with_a_single_entry_and_double_quotes_still_translates() {
let source = "@vite([\"resources/js/app.js\"])";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(out, "@vitex(['resources/js/app.js'])");
}
#[test]
fn translates_js_directive_expression() {
let source = "<script>const post = @js($post);</script>";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(out, "<script>const post = @js(post);</script>");
}
#[test]
fn an_unsupported_js_expression_degrades_in_place_leaving_the_rest_of_the_file_intact() {
let source = "before @js($post->getExcerpt()) after";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("before"));
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("@js(...) expression not supported"));
}
#[test]
fn preserves_plain_text_and_html_unchanged() {
let source = "<div class=\"card\">\n <h1>Hello</h1>\n</div>\n";
assert_eq!(
convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0,
source
);
}
#[test]
fn does_not_misread_an_email_address_as_a_directive() {
let source = "<p>Contact user@example.com for help.</p>";
assert_eq!(
convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0,
source
);
}
#[test]
fn rejects_unsupported_directive_whole_file() {
let source = "@extends('layouts.app')\n@endauth\n";
let err = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap_err();
assert!(err.contains("unsupported directive @endauth"));
}
#[test]
fn a_paired_unsupported_directive_degrades_the_whole_span_in_place() {
let source = "before @auth\nsecret content\n@endauth after";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("before"));
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert!(!out.contains("secret content"));
assert!(!out.contains("@auth"));
assert!(!out.contains("@endauth"));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("@auth ... @endauth block dropped"));
}
#[test]
fn find_marker_does_not_match_a_word_that_merely_starts_with_the_marker() {
let can_source = "@can('edit', $post)\nx\n@cannot\ny\n@endcan\nafter";
let (out, _) = convert(can_source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("after"));
let for_source = "@for($i = 0; $i < 3; $i++)\n@foreach($xs as $x)\n{{ $x }}\n@endforeach\n@endfor\nafter";
let (out, _) = convert(for_source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("after"));
}
#[test]
fn a_bare_paired_directive_with_no_parens_still_finds_its_closing_marker() {
let source = "@auth\ncontent\n@endauth";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert_eq!(
out,
format!("<!-- {DEGRADED_PLACEHOLDER} (spot #1) - see CONVERSION_REPORT.md -->")
);
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("original content: `content`"));
}
#[test]
fn every_paired_unsupported_directive_degrades_the_whole_span() {
for source in [
"@auth\nx\n@endauth",
"@guest\nx\n@endguest",
"@can('edit', $post)\nx\n@endcan",
"@can('edit', $post)\nx\n@cannot\ny\n@endcan",
"@isset($x)\nx\n@endisset",
"@empty($x)\nx\n@endempty",
"@component('alert')\nx\n@endcomponent",
"@while($x)\nx\n@endwhile",
"@for($i = 0; $i < 10; $i++)\nx\n@endfor",
"@error('field')\nx\n@enderror",
"@switch($x)\n@case(1)\na\n@break\n@default\nb\n@endswitch",
] {
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap_or_else(|e| panic!("expected {source:?} to degrade, got Err: {e}"));
assert_eq!(
out,
format!("<!-- {DEGRADED_PLACEHOLDER} (spot #1) - see CONVERSION_REPORT.md -->"),
"expected {source:?} to collapse to a single placeholder"
);
assert_eq!(notes.len(), 1, "expected exactly one note for {source:?}");
}
}
#[test]
fn a_leaf_unsupported_directive_degrades_in_place_instead_of_rejecting_the_file() {
let source = "before @include('partials.nav', ['x' => 1]) after";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("before"));
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert!(!out.contains("partials.nav"));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("spot #1"));
assert!(notes[0].contains("@include('partials.nav', ['x' => 1]) not supported"));
}
#[test]
fn every_leaf_unsupported_directive_degrades_in_place() {
for source in [
"@include('partials.nav')",
"@method('PUT')",
"@each('item', $items, 'item')",
"@livewire('dashboard')",
] {
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(
out.contains(DEGRADED_PLACEHOLDER),
"expected {source:?} to degrade in place"
);
assert_eq!(notes.len(), 1, "expected exactly one note for {source:?}");
}
}
#[test]
fn translates_a_simple_php_block_into_a_code_block() {
let source =
"@php\n $keywords = explode(\",\", $item['keywords']);\n@endphp\n{{ $keywords }}\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@code"));
assert!(out.contains("let mut keywords ="));
assert!(out.contains("@endcode"));
assert!(!out.contains("@php"));
assert!(out.contains("{{ keywords }}"));
}
#[test]
fn a_top_level_php_block_with_a_superglobal_degrades_and_taints_its_variable() {
let source = "@php\n $q = str_replace('_', ' ', $_POST['q']);\n@endphp\n{{ $q }}\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(!out.contains("@code"));
assert!(!out.contains("@endcode"));
assert_eq!(out.matches(DEGRADED_PLACEHOLDER).count(), 2);
assert_eq!(notes.len(), 2);
assert!(notes[0].contains("@php block dropped"));
assert!(notes[0].contains("$q"));
assert!(notes[1].contains("expression not supported"));
}
#[test]
fn translates_a_php_block_referencing_get_into_a_query_context_reference() {
let source =
"@php\n $q = str_replace('_', ' ', isset($_GET['q']) ? $_GET['q'] : \"\");\n@endphp\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("(query).get(\"q\")"));
}
#[test]
fn rejects_an_unterminated_php_block() {
let source = "@php\n $q = $x;\n";
let err = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap_err();
assert!(err.contains("unterminated @php"));
}
#[test]
fn rejects_a_raw_php_tag_whole_file_instead_of_copying_it_through_as_literal_text() {
let source = "<?php\n\nnew class extends Component {\n public string $password = '';\n};\n?>\n\n<div>{{ __('hi') }}</div>\n";
let err = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap_err();
assert!(err.contains("<?php"));
assert!(err.contains("Volt"));
}
#[test]
fn rejects_a_raw_php_short_echo_tag_too() {
let source = "<?= $x ?>\n";
assert!(convert(source, test_ctx!(Path::new("/nonexistent")), true).is_err());
}
#[test]
fn an_ordinary_php_block_directive_is_unaffected_by_the_raw_tag_check() {
let source =
"@php\n $keywords = explode(\",\", $item['keywords']);\n@endphp\n{{ $keywords }}\n";
let out = convert(source, test_ctx!(Path::new("/nonexistent")), true)
.unwrap()
.0;
assert!(out.contains("@code"));
}
#[test]
fn degrades_an_if_block_with_an_unsupported_condition_instead_of_rejecting_the_whole_file() {
let source = "before\n@if($post->getExcerpt())\nx\n@endif\nafter\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("before"));
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert!(!out.contains("@if"));
assert!(!out.contains("getExcerpt"));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("not supported"));
}
#[test]
fn degrades_a_foreach_block_with_an_unsupported_iterable() {
let source = "@foreach($post->getExcerpt() as $x)\n{{ $x }}\n@endforeach\nafter\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert!(!out.contains("@foreach"));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("iterable not supported"));
}
#[test]
fn a_paired_unsupported_directive_nested_inside_a_foreach_degrades_only_that_spot() {
let source = "@foreach($posts as $post)\n@auth\nsecret\n@endauth\n@endforeach\nafter\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("after"));
assert!(out.contains("@foreach("));
assert!(out.contains("@endforeach"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert!(!out.contains("secret"));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("@auth ... @endauth block dropped"));
}
#[test]
fn an_unsupported_interpolation_degrades_in_place_leaving_the_rest_of_the_file_intact() {
let source = "before {{ $post->getExcerpt() }} after";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("before"));
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("expression not supported"));
}
#[test]
fn a_nested_if_inside_a_healthy_outer_if_translates_normally() {
let source = "@if($x)\n@if($y)\ninner\n@endif\n@endif\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(out.matches("@if(").count(), 2);
assert_eq!(out.matches("@endif").count(), 2);
assert!(out.contains("inner"));
}
#[test]
fn a_php_failure_nested_inside_a_foreach_still_drops_the_whole_loop() {
let source =
"@foreach($posts as $post)\n@php\n $q = $_POST['q'];\n@endphp\n@endforeach\nafter\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("after"));
assert!(!out.contains("@foreach"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("@php blocks require a manual"));
}
#[test]
fn taint_from_one_dropped_php_block_does_not_spread_to_an_unrelated_variable() {
let source = "@php\n $q = $_POST['q'];\n@endphp\n{{ $q }} {{ $title }}\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("{{ title }}"));
assert_eq!(notes.len(), 2);
}
#[test]
fn a_php_block_reassigning_the_same_variable_inside_a_nested_if_taints_it_once() {
let source = "@php\n $brandName = 'Default';\n if ($isEnterpriseEdition) {\n $brandName = $custom;\n }\n@endphp\n{{ $brandName }}\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert_eq!(out.matches(DEGRADED_PLACEHOLDER).count(), 2);
assert_eq!(notes.len(), 2);
assert!(notes[0].contains("$brandName"));
}
#[test]
fn a_layout_like_file_with_a_php_block_and_a_leaf_directive_converts_with_multiple_degraded_spots(
) {
let source = "<!doctype html>\n<html>\n<head>\n@php\n $brandName = (string) config('app.name', 'Git Web Manager');\n@endphp\n<title>{{ $brandName }}</title>\n</head>\n<body>\n{{ $slot }}\n@include('partials.language-selector')\n</body>\n</html>\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("<!doctype html>"));
assert!(out.contains("<title>"));
assert!(out.contains("{!! slot !!}"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert_eq!(notes.len(), 3);
for spot in 1..=3 {
assert!(
out.contains(&format!("(spot #{spot})")),
"expected spot #{spot} to appear in the output"
);
assert!(
notes
.iter()
.any(|n| n.starts_with(&format!("spot #{spot}: "))),
"expected a report note for spot #{spot}"
);
}
assert!(notes
.iter()
.any(|n| n.contains("original code:") && n.contains("Git Web Manager")));
assert!(notes
.iter()
.any(|n| n.contains("partials.language-selector")));
}
#[test]
fn a_dropped_foreach_bodys_actual_markup_is_preserved_in_the_report() {
let source =
"@foreach((array) $messages as $message)\n <p>{{ $message }}</p>\n@endforeach\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("iterable not supported"));
assert!(notes[0].contains("original body:"));
assert!(notes[0].contains("<p>{{ $message }}</p>"));
}
#[test]
fn rejects_section_with_inline_content_shorthand() {
let source = "@section('title', 'My Title')\n";
assert!(convert(source, test_ctx!(Path::new("/nonexistent")), true).is_err());
}
#[test]
fn translates_a_livewire_tag_to_a_resource_tag_with_translated_dynamic_attrs() {
let source =
r#"<livewire:components.navbar :url="$url" :current="$current" lazy="on-load"/>"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(
out,
"<resource:livewire.components.navbar :url='url' :current='current' lazy=\"on-load\" :query='query' />"
);
}
#[test]
fn a_non_colon_attribute_whose_value_is_a_whole_interpolation_is_still_translated() {
let source = r#"<livewire:elements.package selected="{{$selected}}" color="{{$color}}" title="Lump Sum" />"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(
out,
"<resource:livewire.elements.package :selected='selected' :color='color' title=\"Lump Sum\" :query='query' />"
);
}
#[test]
fn a_non_colon_attribute_mixing_literal_text_with_an_interpolation_stays_literal() {
let source = r#"<livewire:elements.package price="Cost: {{$price}}" />"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert!(out.contains(r#"price="Cost: {{$price}}""#));
}
#[test]
fn translates_a_multi_line_livewire_tag() {
let source = "<livewire:components.head\n :title=\"$title\"\n :url=\"$url\"\n/>";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(
out,
"<resource:livewire.components.head :title='title' :url='url' :query='query' />"
);
}
#[test]
fn a_livewire_tag_with_no_attributes_translates_cleanly() {
let source = "<livewire:elements.sunrise />";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(out, "<resource:livewire.elements.sunrise :query='query' />");
}
#[test]
fn a_livewire_tag_attribute_named_after_a_rust_keyword_is_escaped() {
let source = r#"<livewire:elements.dividers type="arrow" :position="$pos" />"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(
out,
"<resource:livewire.elements.dividers type_=\"arrow\" :position='pos' :query='query' />"
);
}
#[test]
fn a_livewire_tag_with_an_unsupported_dynamic_attr_degrades_in_place() {
let source = "before <livewire:elements.package :subject=\"$post->getExcerpt()\" /> after";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(out.contains("before"));
assert!(out.contains("after"));
assert!(out.contains(DEGRADED_PLACEHOLDER));
assert_eq!(notes.len(), 1);
assert!(notes[0].contains("expression not supported"));
}
#[test]
fn rejects_a_non_self_closing_livewire_tag_as_a_structural_error() {
let source = "<livewire:components.head>content</livewire:components.head>";
let err = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap_err();
assert!(err.contains("must be self-closing"));
}
#[test]
fn a_bare_closing_bracket_with_no_matching_closer_is_treated_as_self_closing() {
let source = "<livewire:elements.checkitem top=\"A\" bottom=\"B\">\nafter\n";
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert!(out.contains(
"<resource:livewire.elements.checkitem top=\"A\" bottom=\"B\" :query='query' />"
));
assert!(out.contains("after"));
}
#[test]
fn rejects_an_unterminated_livewire_tag() {
let source = "<livewire:components.head :title=\"$title\"";
assert!(convert(source, test_ctx!(Path::new("/nonexistent")), true).is_err());
}
fn write_component(laravel_root: &std::path::Path, pascal_path: &str, php_body: &str) {
let path = laravel_root
.join("app/Livewire")
.join(format!("{pascal_path}.php"));
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, php_body).unwrap();
}
#[test]
fn a_tag_with_no_attributes_pulls_in_only_defaults_with_a_real_literal() {
let dir = tempfile::tempdir().unwrap();
write_component(
dir.path(),
"Elements/Questions",
"<?php\nclass Questions extends Component {\n public $padding;\n public $ribbon = \"\";\n}\n",
);
let source = "<livewire:elements.questions/>";
let (out, notes) = convert(source, test_ctx!(dir.path()), true).unwrap();
assert!(notes.is_empty());
assert!(!out.contains(":padding="));
assert!(out.contains(":ribbon='\"\"'"));
}
#[test]
fn a_tags_own_explicit_binding_wins_over_the_components_declared_default() {
let dir = tempfile::tempdir().unwrap();
write_component(
dir.path(),
"Elements/Questions",
"<?php\nclass Questions extends Component {\n public $padding;\n}\n",
);
let source = "<livewire:elements.questions padding=\"70px\"/>";
let (out, notes) = convert(source, test_ctx!(dir.path()), true).unwrap();
assert!(notes.is_empty());
assert!(out.contains("padding=\"70px\""));
assert_eq!(out.matches("padding").count(), 1);
}
#[test]
fn a_missing_component_file_leaves_the_tag_translating_exactly_as_without_enrichment() {
let dir = tempfile::tempdir().unwrap();
let source = "<livewire:elements.questions/>";
let (out, notes) = convert(source, test_ctx!(dir.path()), true).unwrap();
assert!(notes.is_empty());
assert_eq!(
out,
"<resource:livewire.elements.questions :query='query' />"
);
}
#[test]
fn a_component_property_named_after_a_rust_keyword_is_escaped_when_auto_supplied() {
let dir = tempfile::tempdir().unwrap();
write_component(
dir.path(),
"Elements/Dividers",
"<?php\nclass Dividers extends Component {\n public $type = \"arrow\";\n}\n",
);
let source = "<livewire:elements.dividers/>";
let (out, notes) = convert(source, test_ctx!(dir.path()), true).unwrap();
assert!(notes.is_empty());
assert!(out.contains(":type_='\"arrow\"'"));
}
#[test]
fn every_livewire_tag_unconditionally_receives_the_ambient_query_binding() {
let source = r#"<livewire:elements.package :subject="$post" />"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert!(out.contains(":query='query'"));
}
#[test]
fn a_tags_own_explicit_query_binding_is_not_duplicated() {
let source = r#"<livewire:elements.package :query="$customQuery" />"#;
let (out, notes) = convert(source, test_ctx!(Path::new("/nonexistent")), true).unwrap();
assert!(notes.is_empty());
assert_eq!(out.matches(":query=").count(), 1);
assert!(out.contains(":query='customQuery'"));
}
#[test]
fn a_components_own_unrelated_query_prop_default_is_not_duplicated_by_the_ambient_binding() {
let dir = tempfile::tempdir().unwrap();
write_component(
dir.path(),
"Elements/Subscribe",
"<?php\nclass Subscribe extends Component {\n public $query = '';\n}\n",
);
let source = "<livewire:elements.subscribe/>";
let (out, notes) = convert(source, test_ctx!(dir.path()), true).unwrap();
assert!(notes.is_empty());
assert_eq!(out.matches(":query=").count(), 1);
assert!(out.contains(":query='\"\"'"));
}
}