use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use regex::Regex;
use serde_json::Value;
use crate::audit::balanced;
use crate::manifest::controller;
use crate::route_parity::{ignored, php_auth, php_guest};
use crate::feasibility;
const RESERVED: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "gen",
"if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super",
"trait", "true", "try", "type", "unsafe", "use", "where", "while", "abstract", "become", "box", "do", "final", "macro",
"override", "priv", "typeof", "unsized", "virtual", "yield",
];
pub fn run(inventory: &Path, rust: &Path) -> Result<(), String> {
let mut inv = feasibility::load(inventory)?;
feasibility::score_all(&mut inv);
let php = PathBuf::from(inv["app"]["path"].as_str().ok_or("inventory has no app.path")?);
if !rust.join("Cargo.toml").is_file() || !rust.join("src").is_dir() {
return Err(format!("{} isn't a Laravel Rust app (no Cargo.toml + src/); create one with `laravel new <name> --rust`", rust.display()));
}
if let (Ok(p), Ok(r)) = (fs::canonicalize(&php), fs::canonicalize(rust)) {
if r.starts_with(&p) {
return Err("the Rust app is inside the PHP app; put it somewhere else (hard rule 2)".into());
}
}
let models = Models::new(&inv, &php);
let mut files: Vec<(String, String)> = models.files();
let (handler_files, wiring, names) = handlers(&inv, &models);
files.extend(handler_files);
files.extend(views(&inv, &php, &names));
let policy_file = policies(&inv, &php);
files.extend(policy_file.clone());
let (migration_files, migration_notes) = rust_migrations(&php, rust);
files.extend(migration_files);
let (mut written, mut skipped, mut skipped_notes, mut todos) = (Vec::new(), Vec::new(), Vec::new(), 0);
for (rel, text) in &files {
let path = rust.join(rel);
if path.exists() {
skipped_notes.push(match missing_fields(&path, text) {
Some(m) => format!("- `{rel}`: lacks {m}; add them, or the relations to this model won't compile"),
None => format!("- `{rel}`"),
});
skipped.push(rel.clone());
continue;
}
fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?;
fs::write(&path, text).map_err(|e| format!("{rel}: {e}"))?;
let n = text.lines().skip(1).filter(|l| l.contains("PORT-TODO")).count();
todos += n;
written.push(format!("- `{rel}` ({n} PORT-TODO)"));
}
let mut report = format!(
"# larakiln codegen\n\nGenerated from `{}`. {} files written, {} skipped because they already exist, {todos} `PORT-TODO` markers.\n\n\
Nothing here is wired up yet, and nothing existing was changed. Do the wiring below, run `cargo build`, then work through the `PORT-TODO` markers item by item with `/port-next`.\n\n",
php.display(),
written.len(),
skipped.len()
);
let policy_wiring = if policy_file.is_some() { "**`src/lib.rs`**: add `pub mod policies;`, then use the policies from `crate::policies`.\n\n" } else { "" };
report += &format!("## Wiring\n\n{wiring}{policy_wiring}{}\n", models.wiring(&skipped));
report += &format!("## Written ({})\n\n{}\n\n", written.len(), written.join("\n"));
if !migration_notes.is_empty() {
report += &format!("## Tables the Rust app already creates ({})\n\n{}\n\n", migration_notes.len(), migration_notes.join("\n"));
}
if !skipped.is_empty() {
report += &format!(
"## Skipped: already exist ({})\n\nCompare these by hand with what codegen would have written (delete the file and re-run to see it).\n\n{}\n",
skipped.len(),
skipped_notes.join("\n")
);
}
fs::write(rust.join("larakiln-codegen.md"), report).map_err(|e| e.to_string())?;
println!("Wrote {} files ({todos} PORT-TODO), skipped {} existing. Next: follow {}/larakiln-codegen.md", written.len(), skipped.len(), rust.display());
Ok(())
}
fn snake(s: &str) -> String {
let mut out = String::new();
for (i, ch) in s.chars().enumerate() {
if ch.is_uppercase() {
if i > 0 && !out.ends_with('_') {
out.push('_');
}
out.extend(ch.to_lowercase());
} else if ch == '-' || ch == ' ' || ch == '.' {
out.push('_');
} else {
out.push(ch);
}
}
out
}
fn studly(s: &str) -> String {
s.split(['_', '-']).map(|w| {
let mut c = w.chars();
c.next().map(|f| f.to_uppercase().chain(c).collect::<String>()).unwrap_or_default()
}).collect()
}
fn plural(s: &str) -> String {
let consonant_y = s.ends_with('y') && !s.ends_with("ay") && !s.ends_with("ey") && !s.ends_with("oy") && !s.ends_with("uy");
if consonant_y {
format!("{}ies", &s[..s.len() - 1])
} else if ["s", "x", "ch", "sh"].iter().any(|e| s.ends_with(e)) {
format!("{s}es")
} else {
format!("{s}s")
}
}
fn ident(s: &str) -> String {
let s = snake(s);
if RESERVED.contains(&s.as_str()) { format!("{s}_") } else { s }
}
fn missing_fields(existing: &Path, generated: &str) -> Option<String> {
let have = fs::read_to_string(existing).ok()?;
let field = Regex::new(r"(?m)^\s*pub (\w+):").unwrap();
let have: Vec<String> = field.captures_iter(&have).map(|c| c[1].to_string()).collect();
let missing: Vec<String> = field.captures_iter(generated).map(|c| c[1].to_string()).filter(|f| !have.contains(f)).map(|f| format!("`{f}`")).collect();
(!missing.is_empty()).then(|| missing.join(", "))
}
fn class_basename(s: &str) -> &str {
s.rsplit('\\').next().unwrap_or(s)
}
#[derive(Clone)]
struct Column {
name: String,
ty: String,
nullable: bool,
note: Option<String>,
default: bool,
}
struct Models {
list: Vec<(String, Value, String)>,
tables: HashMap<String, Vec<Column>>,
php: PathBuf,
}
impl Models {
fn new(inv: &Value, php: &Path) -> Self {
let list = inv["models"].as_array().into_iter().flatten().map(|m| {
let name = m["id"].as_str().unwrap_or("").trim_start_matches("model:").to_string();
let table = m["table"].as_str().map(String::from).unwrap_or_else(|| plural(&snake(&name)));
(name, m.clone(), table)
}).collect();
let mut models = Models { list, tables: migrations(php), php: php.to_path_buf() };
models.match_key_types();
models
}
fn match_key_types(&mut self) {
let id_ty = |tables: &HashMap<String, Vec<Column>>, table: &str| -> Option<String> {
tables.get(table)?.iter().find(|c| c.name == "id").map(|c| c.ty.clone())
};
let mut fixes = Vec::new(); for (name, m, table) in &self.list {
for r in m["relations"].as_array().into_iter().flatten() {
let related = r["related"].as_str().unwrap_or("");
let Some((_, _, rtable)) = self.list.iter().find(|(n, _, _)| n == related) else { continue };
match r["type"].as_str() {
Some("belongsTo") => {
let fk = r["foreign_key"].as_str().map(String::from).unwrap_or_else(|| format!("{}_id", snake(r["name"].as_str().unwrap_or(""))));
if let Some(t) = id_ty(&self.tables, rtable) {
fixes.push((table.clone(), fk, t));
}
}
Some("hasMany" | "hasOne") => {
if let Some(t) = id_ty(&self.tables, table) {
fixes.push((rtable.clone(), r["foreign_key"].as_str().map(String::from).unwrap_or_else(|| format!("{}_id", snake(name))), t));
}
}
_ => {}
}
}
}
for (table, col, ty) in fixes {
if let Some(c) = self.tables.get_mut(&table).and_then(|cols| cols.iter_mut().find(|c| c.name == col)) {
c.ty = ty;
}
}
}
fn has(&self, name: &str) -> bool {
self.list.iter().any(|(n, _, _)| n == name)
}
fn by_table(&self, table: &str) -> Option<&str> {
self.list.iter().find(|(_, _, t)| t == table).map(|(n, _, _)| n.as_str())
}
fn files(&self) -> Vec<(String, String)> {
self.list.iter().map(|(name, m, table)| (format!("src/models/{}.rs", snake(name)), self.model(name, m, table))).collect()
}
fn wiring(&self, skipped: &[String]) -> String {
let mods: String = self
.list
.iter()
.filter(|(n, _, _)| !skipped.contains(&format!("src/models/{}.rs", snake(n))))
.map(|(n, _, _)| format!("mod {};\npub use {}::{n};\n", snake(n), snake(n)))
.collect();
format!("**`src/models/mod.rs`**: add\n\n```rust\n{mods}```\n\nThe generated `database/migrations/*.rs` build the test database for ported tests. In production the PHP app keeps owning the schema while both apps run; only run them against the shared database once the Rust app takes the schema over.\n\n")
}
fn model(&self, name: &str, m: &Value, table: &str) -> String {
let mut uses: BTreeSet<&str> = ["model"].into();
let mut extra_uses: BTreeSet<String> = BTreeSet::new();
let mut body = String::new();
let casts = &m["casts"];
let columns = self.tables.get(table);
match columns {
None => body += &format!(" pub id: u64,\n // PORT-TODO: no `Schema::create('{table}')` found in database/migrations; add the columns by hand (`php artisan db:table {table} --json`).\n"),
Some(cols) => {
for c in cols {
let mut ty = c.ty.clone();
let mut serde_skip = false;
let mut note = c.note.clone();
let cast = casts[c.name.as_str()].as_str();
match cast.map(|s| s.split(':').next().unwrap_or(s)) {
Some("hashed") => (ty, serde_skip) = ("PasswordHash".into(), true),
Some("encrypted") if cast == Some("encrypted") => ty = "Encrypted<String>".into(),
Some("encrypted") => {
ty = "Encrypted<serde_json::Value>".into();
note = Some(format!("PORT-TODO: `{}` cast; pick the Rust type", cast.unwrap_or("")));
}
Some("boolean" | "bool") => ty = "bool".into(),
Some("integer" | "int") => ty = "i64".into(),
Some("float" | "double") => ty = "f64".into(),
Some("datetime" | "immutable_datetime" | "timestamp") => ty = "Timestamp".into(),
Some("date" | "immutable_date") => ty = "civil::Date".into(),
Some("array" | "json" | "collection" | "object") => ty = "serde_json::Value".into(),
Some(other) if ty == "String" && !["string"].contains(&other) => note = Some(format!("PORT-TODO: `{other}` cast")),
_ => {}
}
if c.name == "password" && ty == "String" {
(ty, serde_skip) = ("PasswordHash".into(), true);
}
if ty == "RememberToken" {
serde_skip = true;
}
for (needle, path) in [
("Timestamp", "laravel::time::Timestamp"),
("civil::", "laravel::time::civil"),
("PasswordHash", "laravel::hash::PasswordHash"),
("Encrypted", "laravel::crypt::Encrypted"),
("RememberToken", "laravel::auth::RememberToken"),
("Decimal", "laravel::numeric::Decimal"),
] {
if ty.contains(needle) {
extra_uses.insert(path.into());
}
}
if let Some(n) = note {
body += &format!(" // {n}\n");
}
if serde_skip {
body += " #[serde(skip)]\n";
}
let field = ident(&c.name);
if field != c.name {
body += &format!(" #[column(\"{}\")]\n", c.name);
}
let ty = if c.nullable { format!("Option<{ty}>") } else { ty };
body += &format!(" pub {field}: {ty},\n");
}
}
}
for r in m["relations"].as_array().into_iter().flatten() {
let (rname, related, kind) = (r["name"].as_str().unwrap_or("?"), r["related"].as_str().unwrap_or("?"), r["type"].as_str().unwrap_or("?"));
let field = ident(rname);
let attr = match kind {
"belongsTo" => Some(("belongs_to", "BelongsTo")),
"hasMany" => Some(("has_many", "HasMany")),
"hasOne" => Some(("has_one", "HasOne")),
_ => None,
};
match attr {
Some((a, w)) if self.has(related) => {
uses.insert(w);
extra_uses.insert(format!("crate::models::{related}"));
let fk_nullable = columns.is_some_and(|cols| cols.iter().any(|c| c.name == format!("{}_id", snake(rname)) && c.nullable));
let target = if (kind == "belongsTo" && fk_nullable) || kind == "hasOne" { format!("Option<{related}>") } else { related.to_string() };
let derived = if kind == "belongsTo" { format!("{}_id", snake(rname)) } else { format!("{}_id", snake(name)) };
let fk = r["foreign_key"].as_str().filter(|fk| *fk != derived).map(|fk| format!("(foreign_key = \"{fk}\")")).unwrap_or_default();
body += &format!(" #[{a}{fk}]\n pub {field}: {w}<{target}>,\n");
}
_ => body += &format!(" // PORT-TODO: `{rname}` is a `{kind}` relation to `{related}`; map it by hand (model-relationships.md).\n"),
}
}
let mut head = format!("// Generated by larakiln codegen from {} and the PHP migrations. Search for PORT-TODO.\n// larakiln: {}\n", m["file"].as_str().unwrap_or("?"), m["id"].as_str().unwrap_or("?"));
head += &format!("use laravel::model::{{{}}};\n", uses.iter().copied().collect::<Vec<_>>().join(", "));
for u in extra_uses.iter().filter(|u| !u.starts_with("crate::")) {
head += &format!("use {u};\n");
}
let crate_uses: Vec<&String> = extra_uses.iter().filter(|u| u.starts_with("crate::")).filter(|u| !u.ends_with(&format!("::{name}"))).collect();
if !crate_uses.is_empty() {
head += "\n";
for u in crate_uses {
head += &format!("use {u};\n");
}
}
let mut table_attr = if *table == plural(&snake(name)) { "#[model]".to_string() } else { format!("#[model(table = \"{table}\")]") };
let php_src = m["file"].as_str().and_then(|f| fs::read_to_string(self.php.join(f)).ok()).unwrap_or_default();
if php_src.contains("extends Authenticatable") {
let (derive, uses) = if Regex::new(r"implements[^{]*\bMustVerifyEmail\b").unwrap().is_match(&php_src) {
("Authenticatable, MustVerifyEmail", "{Authenticatable, MustVerifyEmail}")
} else {
("Authenticatable", "Authenticatable")
};
table_attr += &format!("\n#[derive({derive})]");
head = head.replacen("use laravel::model::", &format!("use laravel::auth::{uses};\nuse laravel::model::"), 1);
}
let factory = self.factory(name, table);
if !factory.is_empty() {
head = head.replacen("use laravel::model::{", "use laravel::model::{Faker, IntoCreate, create, factory, ", 1);
}
format!("{head}\n{table_attr}\npub struct {name} {{\n{body}}}\n{factory}")
}
fn factory(&self, name: &str, table: &str) -> String {
let Ok(src) = fs::read_to_string(self.php.join(format!("database/factories/{name}Factory.php"))) else { return String::new() };
let Some(def) = src.find("function definition").map(|i| &src[i..]) else { return String::new() };
let Some(body) = def.find("return").and_then(|i| def[i..].find('[').map(|j| &def[i + j..])).and_then(|b| balanced(b, '[', ']')) else { return String::new() };
let cols = self.tables.get(table).cloned().unwrap_or_default();
let (mut fields, mut set) = (Vec::new(), BTreeSet::new());
for pair in split_args(&body[1..body.len() - 1]) {
let Some((k, v)) = pair.split_once("=>") else { continue };
let key = unquote(k);
let v = v.trim();
if key == "remember_token" {
continue; }
let rust = faker_value(v);
match rust {
Some(r) if key.ends_with("_id") && r.ends_with("::factory()") => {
fields.push(format!(" {}: {r},", key.trim_end_matches("_id")));
set.insert(key);
}
Some(r) => {
fields.push(format!(" {key}: {r},"));
set.insert(key);
}
None => fields.push(format!(" // PORT-TODO: {key} => {v}")),
}
}
for c in &cols {
let auto = ["id", "created_at", "updated_at"].contains(&c.name.as_str()) || c.nullable || c.default;
if !auto && !set.contains(&c.name) {
let hint = c.name.strip_suffix("_id").map(|r| format!(" (for example `{r}: {}::factory()`)", studly(r))).unwrap_or_default();
fields.push(format!(" // PORT-TODO: `{}` is required but the PHP factory doesn't set it{hint}", c.name));
}
}
let states: Vec<String> = Regex::new(r"public function (\w+)\(").unwrap().captures_iter(&src)
.map(|c| c[1].to_string()).filter(|f| f != "definition" && f != "configure").collect();
let states = if states.is_empty() { String::new() } else { format!("\n// PORT-TODO: PHP factory states not ported: {}\n", states.join(", ")) };
format!(
"\n#[factory({name})]\npub struct {name}Factory;\n\nimpl {name}Factory {{\n fn definition(fake: &mut Faker) -> impl IntoCreate<{name}> {{\n create!({name} {{\n{}\n }})\n }}\n}}\n{states}",
fields.join("\n")
)
}
}
fn faker_value(v: &str) -> Option<String> {
let v = v.trim();
if v.starts_with(['\'', '"']) {
return Some(format!("\"{}\"", unquote(v)));
}
if v == "true" || v == "false" || v.parse::<f64>().is_ok() {
return Some(v.to_string());
}
if v == "now()" {
return Some("laravel::now()".into());
}
if let Some(c) = Regex::new(r"^(\w+)::factory\(\)$").unwrap().captures(v) {
return Some(format!("{}::factory()", &c[1]));
}
if let Some(c) = Regex::new(r"(?:Hash::make|bcrypt)\(\s*'([^']*)'\s*\)").unwrap().captures(v) {
return Some(format!("\"{}\"", &c[1]));
}
if let Some(c) = Regex::new(r"^Str::random\((\d+)\)$").unwrap().captures(v) {
return Some(format!("fake.alphanumeric({})", &c[1]));
}
let c = Regex::new(r"^(?:\$this->faker|fake\(\))->(unique\(\)->)?(\w+)\(([^)]*)\)$").unwrap().captures(v)?;
let (unique, method, args) = (c.get(1).is_some(), &c[2], c[3].trim());
let rust = match method {
"firstName" | "lastName" | "name" | "userName" | "word" | "slug" | "sentence" | "paragraph" | "company" | "streetAddress" | "city" | "state"
| "country" | "countryCode" | "url" | "ipv4" | "ipv6" | "uuid" if args.is_empty() => format!("{}()", snake(method)),
"email" | "safeEmail" | "companyEmail" | "freeEmail" => "email()".into(),
"catchPhrase" | "realText" | "bs" => "sentence()".into(), "postcode" => "postal_code()".into(),
"phoneNumber" | "tollFreePhoneNumber" | "e164PhoneNumber" => "phone_number()".into(),
"text" => "paragraph()".into(),
"words" | "paragraphs" if args.parse::<u32>().is_ok() => format!("{method}({args})"),
"numberBetween" => {
let (a, b) = args.split_once(',')?;
format!("number({}..={})", a.trim(), b.trim())
}
"boolean" => format!("boolean({})", if args.is_empty() { "50" } else { args }),
_ => return None,
};
Some(format!("fake.{}{rust}", if unique { "unique()." } else { "" }))
}
fn migrations(php: &Path) -> HashMap<String, Vec<Column>> {
let mut tables: HashMap<String, Vec<Column>> = HashMap::new();
let Ok(dir) = fs::read_dir(php.join("database/migrations")) else { return tables };
let mut files: Vec<PathBuf> = dir.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|e| e == "php")).collect();
files.sort();
let open = Regex::new(r#"Schema::(create|table)\(\s*['"]([^'"]+)['"]"#).unwrap();
for f in files {
let Ok(src) = fs::read_to_string(&f) else { continue };
let src = src.split("function down").next().unwrap_or(&src);
for c in open.captures_iter(src) {
let rest = &src[c.get(0).unwrap().end()..];
let Some(brace) = rest.find('{') else { continue };
let Some(body) = balanced(&rest[brace..], '{', '}') else { continue };
let cols = tables.entry(c[2].to_string()).or_default();
for stmt in body.trim_start_matches('{').split(';') {
apply(cols, stmt.trim());
}
}
}
tables
}
fn apply(cols: &mut Vec<Column>, stmt: &str) {
let call = Regex::new(r#"^\$table->(\w+)\(([^)]*)\)"#).unwrap();
let Some(c) = call.captures(stmt) else { return };
let (method, args) = (&c[1], &c[2]);
let quoted = Regex::new(r#"['"]([^'"]+)['"]"#).unwrap();
let names: Vec<String> = quoted.captures_iter(args).map(|q| q[1].to_string()).collect();
let nullable = stmt.contains("->nullable(");
let default = stmt.contains("->default(") || stmt.contains("->useCurrent(");
let col = |name: &str, ty: &str, nullable: bool| Column { name: name.into(), ty: ty.into(), nullable, note: None, default };
let first = names.first().cloned();
let ty = match method {
"id" | "bigIncrements" | "foreignId" | "unsignedBigInteger" => "u64",
"bigInteger" => "i64",
"increments" | "integer" | "unsignedInteger" | "mediumInteger" | "smallInteger" | "tinyInteger" | "unsignedSmallInteger" | "unsignedTinyInteger" | "unsignedMediumInteger" | "year" => "i32",
"string" | "char" | "text" | "mediumText" | "longText" | "tinyText" | "uuid" | "ulid" | "enum" | "ipAddress" | "macAddress" | "set" => "String",
"boolean" => "bool",
"decimal" | "unsignedDecimal" => "Decimal",
"float" | "double" => "f64",
"date" => "civil::Date",
"time" | "timeTz" => "civil::Time",
"dateTime" | "dateTimeTz" | "timestamp" | "timestampTz" => "Timestamp",
"json" | "jsonb" => "serde_json::Value",
"binary" => "Vec<u8>",
"foreignIdFor" => {
let class = args.split("::class").next().unwrap_or("").trim();
let name = first.clone().unwrap_or_else(|| format!("{}_id", snake(class_basename(class))));
cols.push(col(&name, "u64", nullable));
return;
}
"timestamps" | "timestampsTz" | "nullableTimestamps" => {
let n = method == "nullableTimestamps";
cols.push(col("created_at", "Timestamp", n));
cols.push(col("updated_at", "Timestamp", n));
return;
}
"softDeletes" | "softDeletesTz" => {
let mut c = col(first.as_deref().unwrap_or("deleted_at"), "Timestamp", true);
c.note = Some("PORT-TODO: soft deletes aren't built in (0.1.4): filter `deleted_at` is null in list queries, delete = set it, restore = clear it (models-eloquent.md)".into());
cols.push(c);
return;
}
"rememberToken" => {
cols.push(col("remember_token", "RememberToken", true));
return;
}
"morphs" | "nullableMorphs" | "uuidMorphs" | "ulidMorphs" => {
let base = first.unwrap_or_default();
let n = method == "nullableMorphs";
cols.push(col(&format!("{base}_type"), "String", n));
cols.push(col(&format!("{base}_id"), if method == "morphs" || n { "u64" } else { "String" }, n));
return;
}
"dropColumn" => {
cols.retain(|c| !names.contains(&c.name));
return;
}
"renameColumn" => {
if let [from, to] = names.as_slice() {
if let Some(c) = cols.iter_mut().find(|c| &c.name == from) {
c.name = to.clone();
}
}
return;
}
"index" | "unique" | "primary" | "foreign" | "dropForeign" | "dropIndex" | "dropUnique" | "dropPrimary" | "engine" | "charset"
| "collation" | "comment" | "fullText" | "spatialIndex" | "dropTimestamps" | "dropSoftDeletes" | "dropRememberToken" | "dropMorphs" => return,
other => {
let mut c = col(first.as_deref().unwrap_or(other), "String", nullable);
c.note = Some(format!("PORT-TODO: unmapped column type `$table->{other}(...)`"));
cols.push(c);
return;
}
};
let name = first.unwrap_or_else(|| "id".into());
let nullable = nullable && method != "id";
if let Some(existing) = cols.iter_mut().find(|c| c.name == name) {
*existing = col(&name, ty, nullable); } else {
cols.push(col(&name, ty, nullable));
}
}
fn authorize_hints(inv: &Value, action: &str) -> String {
let Some((class, method)) = action.split_once('@') else { return String::new() };
let Some(path) = inv["app"]["path"].as_str() else { return String::new() };
let file = Path::new(path).join(class.replacen("App\\", "app\\", 1).replace('\\', "/") + ".php");
let Ok(src) = fs::read_to_string(file) else { return String::new() };
let Some(start) = Regex::new(&format!(r"function\s+{method}\s*\(")).unwrap().find(&src) else { return String::new() };
let rest = &src[start.end()..];
let Some(body) = rest.find('{').and_then(|b| balanced(&rest[b..], '{', '}')) else { return String::new() };
let call = Regex::new(r"(Gate::authorize|\$this->authorize)\(\s*['\x22](\w+)['\x22]\s*,\s*(?:\$(\w+)|(\w+)::class)").unwrap();
call.captures_iter(&body).map(|c| {
let ability = ident(&c[2]);
let (model, target) = match (c.get(3), c.get(4)) {
(Some(v), _) => (studly(v.as_str()), format!(", &{}", ident(v.as_str()))),
(_, Some(m)) => (m.as_str().to_string(), ", ()".into()),
_ => unreachable!(),
};
format!(" // PORT-TODO: PHP calls `{}('{}', ..)`: user.authorize(crate::policies::{model}Policy::{ability}{target}).await?;\n", &c[1], &c[2])
}).collect::<String>() + &resource_hint(&src, method)
}
fn resource_hint(src: &str, method: &str) -> String {
let Some(c) = Regex::new(r"authorizeResource\(\s*(\w+)::class\s*(?:,\s*['\x22](\w+)['\x22])?").unwrap().captures(src) else { return String::new() };
let model = &c[1];
let var = c.get(2).map_or(snake(model), |m| m.as_str().to_string());
let (ability, target) = match method {
"index" => ("view_any", ", ()".into()),
"create" | "store" => ("create", ", ()".into()),
"show" => ("view", format!(", &{var}")),
"edit" | "update" => ("update", format!(", &{var}")),
"destroy" => ("delete", format!(", &{var}")),
_ => return String::new(),
};
format!(" // PORT-TODO: PHP's authorizeResource({model}::class) checks this: user.authorize(crate::policies::{model}Policy::{ability}{target}).await?;\n")
}
fn policies(inv: &Value, php: &Path) -> Option<(String, String)> {
let method = Regex::new(r"public function (\w+)\(\s*(?:(?:\??\w+\s+)?\$(\w+)\s*(?:,\s*(\w+)\s+\$(\w+))?)?[^)]*\)[^{]*").unwrap();
let owns = Regex::new(r"^return\s+(?:\$(\w+)->(\w+)(?:\(\))?->is\(\$(\w+)\)|\$(\w+)->id\s*===?\s*\$(\w+)->(\w+)|\$(\w+)->(\w+)\s*===?\s*\$(\w+)->id)\s*;$").unwrap();
let delegate = Regex::new(r"^return\s+\$this->(\w+)\(\s*\$(\w+)\s*(?:,\s*\$(\w+)\s*)?\)\s*;$").unwrap();
let space = Regex::new(r"\s+").unwrap();
let (mut out, mut models) = (String::new(), BTreeSet::from(["User".to_string()]));
for p in inv["policies"].as_array().into_iter().flatten() {
let Some(file) = p["file"].as_str() else { continue };
let Ok(src) = fs::read_to_string(php.join(file)) else { continue };
let class = class_basename(p["id"].as_str().unwrap_or("").trim_start_matches("policy:")).to_string();
let mut fns = Vec::new();
for c in method.captures_iter(&src) {
let rest = &src[c.get(0).unwrap().end()..];
let Some(body) = balanced(rest, '{', '}') else { continue };
let body = space.replace_all(body.trim_matches(['{', '}']).trim(), " ").into_owned();
let (name, user) = (&c[1], c.get(2).map_or("_user", |m| m.as_str()));
let model = c.get(3).map(|m| (m.as_str().to_string(), c[4].to_string()));
if name == "before" {
fns.push(format!(" // PORT-TODO: the PHP policy has a before() hook: `{body}`; fold it into each ability\n"));
continue;
}
let args = match &model {
Some((ty, var)) => {
models.insert(ty.clone());
format!("{user}: &User, {var}: &{ty}")
}
None => format!("{user}: &User"),
};
let rust = if body == "return true;" || body == "return false;" {
body[7..body.len() - 1].to_string()
} else if let Some(o) = owns.captures(&body) {
if let Some(m) = o.get(1) { format!("{}.id == {}.{}_id", &o[3], m.as_str(), &o[2]) }
else if let Some(u) = o.get(4) { format!("{}.id == {}.{}", u.as_str(), &o[5], &o[6]) }
else { format!("{}.id == {}.{}", &o[9], &o[7], &o[8]) }
} else if let Some(d) = delegate.captures(&body) {
format!("Self::{}({}{})", &d[1], &d[2], d.get(3).map(|m| format!(", {}", m.as_str())).unwrap_or_default())
} else {
format!("todo!(\"PORT-TODO: port `{}`\")", body.replace('\\', "\\\\").replace('"', "\\\""))
};
fns.push(format!(" pub fn {}({args}) -> bool {{\n {rust}\n }}\n", ident(name)));
}
out += &format!("\n/// larakiln: policy:{class}\npub struct {class};\n\n#[policy]\nimpl {class} {{\n{}}}\n", fns.join("\n"));
}
(!out.is_empty()).then(|| {
let uses = models.into_iter().collect::<Vec<_>>().join(", ");
("src/policies/mod.rs".to_string(), format!("// Generated by larakiln codegen from app/Policies. Search for PORT-TODO.\nuse laravel::auth::policy;\n\nuse crate::models::{{{uses}}};\n{out}"))
})
}
fn rust_migrations(php: &Path, rust: &Path) -> (Vec<(String, String)>, Vec<String>) {
let existing: String = fs::read_dir(rust.join("database/migrations")).into_iter().flatten().filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|x| x == "rs"))
.filter_map(|e| fs::read_to_string(e.path()).ok()).collect();
let macros: &[(&str, &[&str])] = &[
("cache::tables!", &["cache", "cache_locks"]),
("queue::tables!", &["jobs", "failed_jobs", "job_batches", "job_batch_jobs"]),
("session::table!", &["sessions"]),
("feature::table!", &["features"]),
];
let created = |t: &str| {
existing.contains(&format!(".create(\"{t}\"")) || macros.iter().any(|(m, ts)| existing.contains(m) && ts.contains(&t))
};
let Ok(dir) = fs::read_dir(php.join("database/migrations")) else { return (vec![], vec![]) };
let mut paths: Vec<PathBuf> = dir.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().is_some_and(|e| e == "php")).collect();
paths.sort();
let call = Regex::new(r#"Schema::(create|table|dropIfExists|drop|rename)\(\s*['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?"#).unwrap();
let (mut files, mut notes) = (Vec::new(), Vec::new());
for path in paths {
let Ok(src) = fs::read_to_string(&path) else { continue };
let up = src.split("function down").next().unwrap_or(&src);
let stem = path.file_stem().unwrap().to_string_lossy().to_string();
let mut steps = Vec::new();
for c in call.captures_iter(up) {
let (kind, table) = (&c[1], &c[2]);
match kind {
"create" if created(table) => {
notes.push(format!("- `{stem}.php`: an existing Rust migration already creates `{table}`; compare its columns with the PHP one"));
}
"create" | "table" => {
let rest = &up[c.get(0).unwrap().end()..];
let Some(body) = rest.find('{').and_then(|b| balanced(&rest[b..], '{', '}')) else { continue };
let lines: Vec<String> = body.trim_start_matches('{').trim_end_matches('}').split(';')
.map(str::trim).filter(|l| !l.is_empty()).map(|l| format!(" {}", framework_time(table, column_stmt(l)))).collect();
let verb = if kind == "create" { "create" } else { "alter" };
steps.push(format!(" tx.schema()\n .{verb}(\"{table}\", |table| {{\n{}\n }})\n .await?;\n", lines.join("\n")));
}
"rename" => steps.push(format!(" tx.schema().rename(\"{table}\", \"{}\").await?;\n", c.get(3).map_or("", |m| m.as_str()))),
_ => steps.push(format!(" tx.schema().drop_if_exists(\"{table}\").await?;\n")),
}
}
if up.contains("DB::") {
steps.push(" // PORT-TODO: this migration runs raw DB:: statements; port them with tx.schema().statement(..)\n".into());
}
if steps.is_empty() {
continue;
}
files.push((
format!("database/migrations/{stem}.rs"),
format!("// Generated by larakiln codegen from database/migrations/{stem}.php. Search for PORT-TODO.\nuse laravel::db::AnyTransaction;\n\npub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {{\n{} Ok(())\n}}\n", steps.concat()),
));
}
(files, notes)
}
fn framework_time(table: &str, stmt: String) -> String {
let cols: &[&str] = match table {
"sessions" => &["last_activity"],
"cache" | "cache_locks" => &["expiration"],
"jobs" => &["reserved_at", "available_at", "created_at"],
"job_batches" => &["created_at", "cancelled_at", "finished_at"],
_ => return stmt,
};
let int = Regex::new(r#"^table\.\w*integer\("(\w+)"\)(\.unsigned\(\))?"#).unwrap();
match int.captures(&stmt) {
Some(c) if cols.contains(&&c[1]) => int.replace(&stmt, "table.timestamp(\"$1\")").into_owned(),
_ => stmt,
}
}
fn column_stmt(php: &str) -> String {
let todo = || format!("// PORT-TODO: {php};");
let Some(chain) = php.strip_prefix("$table->") else { return todo() };
let mut calls: Vec<(String, Vec<String>)> = Vec::new();
let mut rest = chain;
while !rest.is_empty() {
let Some(open) = rest.find('(') else { return todo() };
let Some(args) = balanced(&rest[open..], '(', ')') else { return todo() };
calls.push((rest[..open].to_string(), split_args(&args[1..args.len() - 1])));
rest = rest[open + args.len()..].trim_start().strip_prefix("->").unwrap_or("");
}
let lit = |a: &str| {
let a = a.trim();
if a.starts_with('[') {
format!("[{}]", split_args(&a[1..a.len() - 1]).iter().map(|x| format!("\"{}\"", unquote(x))).collect::<Vec<_>>().join(", "))
} else if a.starts_with(['\'', '"']) {
format!("\"{}\"", unquote(a))
} else {
a.to_string()
}
};
let cols = |a: &str| if a.trim().starts_with('[') { lit(a) } else { format!("[{}]", lit(a)) };
let (first, args) = &calls[0];
let mut extra = String::new();
let mut for_table: Option<String> = None;
let head = match first.as_str() {
"id" | "timestamps" | "timestampsTz" | "nullableTimestamps" | "softDeletes" | "softDeletesTz" | "rememberToken" => {
let n = match first.as_str() { "timestampsTz" | "nullableTimestamps" => "timestamps", "softDeletesTz" => "soft_deletes", f => &snake(f) };
format!("{n}({})", args.iter().map(|a| lit(a)).collect::<Vec<_>>().join(", "))
}
"string" | "char" => {
if let Some(n) = args.get(1) {
extra = format!(".length({n})");
}
format!("{}({})", first, lit(&args[0]))
}
"foreignIdFor" => {
let class = class_basename(args[0].trim_end_matches("::class"));
for_table = Some(plural(&snake(class)));
match args.get(1) {
Some(name) => format!("foreign_id({})", lit(name)),
None => format!("foreign_id(\"{}_id\")", snake(class)),
}
}
"enum" => format!("enumeration({})", args.iter().map(|a| lit(a)).collect::<Vec<_>>().join(", ")),
"index" | "unique" | "primary" | "fullText" | "spatialIndex" | "foreign" if !args.is_empty() => format!("{}({})", snake(first), cols(&args[0])),
"dropColumn" | "dropIndex" | "dropUnique" | "dropForeign" | "renameColumn" | "decimal" | "set" | "morphs" | "nullableMorphs"
| "uuidMorphs" | "ulidMorphs" => format!("{}({})", snake(first), args.iter().map(|a| lit(a)).collect::<Vec<_>>().join(", ")),
f => {
let base = f.strip_prefix("unsigned").map(|b| { extra = ".unsigned()".into(); b.to_string() }).unwrap_or(f.to_string());
let base = snake(&base);
let base = if base == "time_tz" { base } else { base.trim_end_matches("_tz").to_string() };
const COLUMNS: &[&str] = &["increments", "big_increments", "medium_increments", "small_increments", "tiny_increments", "integer",
"big_integer", "medium_integer", "small_integer", "tiny_integer", "float", "double", "boolean", "tiny_text", "text", "medium_text",
"long_text", "json", "jsonb", "date", "time", "time_tz", "date_time", "timestamp", "year", "binary", "uuid", "ulid", "foreign_id",
"foreign_uuid", "foreign_ulid", "ip_address", "mac_address", "geometry", "geography"];
if !COLUMNS.contains(&base.as_str()) || args.len() != 1 {
return todo();
}
format!("{base}({})", lit(&args[0]))
}
};
let mut out = format!("table.{head}{extra}");
let mut i = 1;
while i < calls.len() {
let (m, a) = &calls[i];
let arg = a.first().map(|x| lit(x)).unwrap_or_default();
out += &match m.as_str() {
"constrained" if a.is_empty() && for_table.is_some() => format!(".references(\"{}\")", for_table.as_deref().unwrap_or_default()),
"nullable" | "unique" | "index" | "primary" | "unsigned" | "useCurrent" | "useCurrentOnUpdate" | "first" | "change" | "constrained"
| "cascadeOnDelete" | "cascadeOnUpdate" | "restrictOnDelete" | "restrictOnUpdate" | "nullOnDelete" | "nullOnUpdate" | "noActionOnDelete"
if a.is_empty() => format!(".{}()", snake(m)),
"constrained" => format!(".references({arg})"),
"default" | "after" | "comment" | "charset" | "collation" if !arg.contains("::") => format!(".{m}({arg})"),
"onDelete" | "onUpdate" => {
let on = if m == "onDelete" { "delete" } else { "update" };
match unquote(&arg).as_str() {
"cascade" => format!(".cascade_on_{on}()"),
"set null" => format!(".null_on_{on}()"),
"restrict" => format!(".restrict_on_{on}()"),
_ => return todo(),
}
}
"references" if calls.get(i + 1).is_some_and(|(n, _)| n == "on") => {
let table = lit(&calls[i + 1].1[0]);
i += 1;
let col = if unquote(&arg) == "id" { String::new() } else { format!(".column({arg})") };
if out.starts_with("table.foreign(") { format!(".references({table}, {})", cols(&a[0])) } else { format!(".references({table}){col}") }
}
_ => return todo(),
};
i += 1;
}
if out.starts_with("table.foreign(") && !out.contains(".references(") {
return todo();
}
out + ";"
}
fn input_struct(name: &str, req: &Value, auth: &str, models: &Models) -> String {
let id = req["id"].as_str().unwrap_or("?");
let Some(rules) = req["rules"].as_object() else {
return format!("// PORT-TODO: {id} builds its rules at runtime; write `{name}` by hand (validation.md).\n\n");
};
let mut fields = String::new();
for (field, rs) in rules {
let rs: Vec<&str> = rs.as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if field.contains('.') || field.contains('*') {
fields += &format!(" // PORT-TODO: nested field `{field}`: {}\n", rs.join("|"));
continue;
}
let numeric = rs.iter().any(|r| ["integer", "numeric", "decimal"].contains(&r.split(':').next().unwrap_or(r)));
let mut ty = if rs.contains(&"boolean") || rs.contains(&"accepted") {
"bool"
} else if rs.contains(&"integer") {
"i64"
} else if numeric {
"f64"
} else {
"String"
}
.to_string();
let (mut out, mut todo) = (Vec::new(), Vec::new());
let joined: Vec<String> = rs.iter().enumerate().filter_map(|(i, r)| match (*r, rs.get(i + 1)) {
("unique:", Some(next)) if next.ends_with("::class") => Some(format!("unique:@{}", class_basename(next.trim_end_matches("::class")))),
(r, _) if r.ends_with("::class") && i > 0 && rs[i - 1] == "unique:" => None,
(r, _) => Some(r.to_string()),
}).collect();
let rs: Vec<&str> = joined.iter().map(String::as_str).collect();
for r in &rs {
let (rule, arg) = if r.contains("::") { (*r, "") } else { r.split_once(':').map_or((*r, ""), |(a, b)| (a, b)) };
let args: Vec<&str> = arg.split(',').filter(|a| !a.is_empty()).collect();
let quoted = || args.iter().map(|a| format!("\"{a}\"")).collect::<Vec<_>>().join(", ");
match rule {
"string" | "integer" | "numeric" | "boolean" => {}
"nullable" => ty = format!("Option<{ty}>"),
"sometimes" => ty = format!("Sometimes<{ty}>"),
"required" | "email" | "url" | "uuid" | "ulid" | "ip" | "ipv4" | "ipv6" | "json" | "alpha" | "alpha_num" | "alpha_dash"
| "ascii" | "lowercase" | "uppercase" | "confirmed" | "accepted" | "declined" | "filled" | "present" | "date" | "timezone"
| "mac_address" | "hex_color" | "bail" => out.push(rule.to_string()),
"max" if numeric => out.push(format!("max_value({arg})")),
"min" if numeric => out.push(format!("min_value({arg})")),
"max" => out.push(format!("max_length({arg})")),
"min" => out.push(format!("min_length({arg})")),
"between" if numeric => out.push(format!("between({arg})")),
"between" if args.len() == 2 => out.extend([format!("min_length({})", args[0]), format!("max_length({})", args[1])]),
"in" => out.push(format!("one_of({})", quoted())),
"not_in" => out.push(format!("not_one_of({})", quoted())),
"digits" | "digits_between" | "same" | "different" | "gt" | "gte" | "lt" | "lte" | "decimal" | "multiple_of" => {
out.push(format!("{rule}({arg})"))
}
"starts_with" | "ends_with" | "doesnt_start_with" | "doesnt_end_with" => out.push(format!("{rule}({})", quoted())),
"after" | "before" | "after_or_equal" | "before_or_equal" if arg == "today" => {
out.push(match rule { "after" => "after_today", "before" => "before_today", "after_or_equal" => "today_or_after", _ => "today_or_before" }.into())
}
"after" | "before" | "after_or_equal" | "before_or_equal" => out.push(format!("{rule}({arg})")),
"unique" if args.first().is_some_and(|a| a.starts_with('@')) => out.push(format!("unique({}::{field})", &args[0][1..])),
"Password::defaults" => {
out.push("password".into());
ty = "laravel::hash::Password".into();
}
"current_password" => {
out.push("current_password".into());
ty = "laravel::hash::Password".into();
}
"unique" if !args.is_empty() => match models.by_table(args[0]) {
Some(model) => out.push(format!("unique({model}::{})", args.get(1).copied().unwrap_or(field.as_str()))),
None => todo.push(r.to_string()),
},
_ => todo.push(r.to_string()),
}
}
if !todo.is_empty() {
fields += &format!(" // PORT-TODO: no verified mapping for {}\n", todo.join(", "));
}
if !out.is_empty() {
fields += &format!(" #[validate({})]\n", out.join(", "));
}
fields += &format!(" pub {}: {ty},\n", ident(field));
}
let authorize = match req["authorize"].as_str() {
Some(a) if a != "true" => format!("// PORT-TODO: the FormRequest's authorize() is `{a}`; use #[validate(authorize(Policy::method, route(\"..\")))]\n"),
_ => String::new(),
};
format!("/// larakiln: {id}\n{authorize}#[laravel::input]\n#[validate({auth})]\npub struct {name} {{\n{fields}}}\n\n")
}
type Modules<'a> = BTreeMap<String, (String, Vec<(&'a Value, String)>)>;
struct Handler {
module: String,
func: String,
method: String,
methods: Vec<String>,
uri: String,
auth: bool,
guest: bool,
verified: bool,
api: bool,
}
fn handlers(inv: &Value, models: &Models) -> (Vec<(String, String)>, String, HashMap<String, String>) {
let inertia = inv["app"]["frontend"].as_str().unwrap_or("").starts_with("inertia");
let routes: Vec<&Value> = inv["routes"].as_array().into_iter().flatten().filter(|r| ignored(r, &[]).is_none()).collect();
let mut by_module: Modules = BTreeMap::new();
let mut names = HashMap::new();
let mut table: Vec<Handler> = Vec::new();
for r in &routes {
let class = controller(r);
let action = r["action"].as_str().unwrap_or("Closure");
let method = r["method"].as_str().unwrap_or("GET").to_string();
let uri = r["uri"].as_str().unwrap_or("/").to_string();
let (module, func) = if class == "Closure" {
let slug = uri.trim_matches('/').replace(['/', '-', '.'], "_").replace(['{', '}', '?'], "");
("closures".to_string(), ident(&format!("{}_{}", method.to_lowercase(), if slug.is_empty() { "root".into() } else { slug })))
} else {
let base = class.trim_end_matches("Controller");
let func = action.split_once('@').map_or("handle".to_string(), |(_, m)| if m == "__invoke" { "handle".into() } else { ident(m) });
let module = snake(if base.is_empty() { &class } else { base });
(if module.ends_with('s') { module } else { plural(&module) }, func)
};
if let Some(n) = r["name"].as_str() {
names.insert(n.to_string(), format!("{module}::{func}"));
}
let api = r["middleware"].as_array().into_iter().flatten().any(|m| m == "api");
table.push(Handler { module: module.clone(), func: func.clone(), method, methods: crate::route_parity::php_methods(r), uri, auth: php_auth(r), guest: php_guest(r), verified: crate::route_parity::php_verified(r), api });
let entry = by_module.entry(module).or_insert_with(|| (action.split('@').next().unwrap_or(action).to_string(), Vec::new()));
if !entry.1.iter().any(|(_, f)| *f == func) {
entry.1.push((r, func));
}
}
let requests: Vec<&Value> = inv["requests"].as_array().into_iter().flatten().collect();
let mut files = Vec::new();
let param_re = Regex::new(r"\{(\w+)\??\}").unwrap();
for (module, (class, funcs)) in &by_module {
let controller_file = funcs.first().and_then(|(r, _)| r["action"].as_str()).map(|a| class_basename(a.split('@').next().unwrap_or(a)).to_string());
let mut body = String::new();
let mut uses: BTreeSet<String> = BTreeSet::new();
let any_auth = funcs.iter().all(|(r, _)| php_auth(r));
let mut n = 0;
let mut seen_rules: Vec<((String, bool), String)> = Vec::new();
for req in &requests {
let file = req["file"].as_str().unwrap_or("");
let id = req["id"].as_str().unwrap_or("");
let from_controller = controller_file.as_deref().is_some_and(|c| file.ends_with(&format!("/{c}.php")) && id.contains('#'));
let form_request = !id.contains('#') && controller_uses(inv, class, class_basename(id.trim_start_matches("request:")));
if from_controller || form_request {
let key = (req["rules"].to_string(), form_request);
if let Some(first) = seen_rules.iter().find(|(k, _)| *k == key).map(|(_, first)| first.clone()) {
body = body.replacen(&format!("/// larakiln: {first}\n"), &format!("/// larakiln: {first}\n/// larakiln: {id}\n"), 1);
continue;
}
seen_rules.push((key, id.to_string()));
n += 1;
let name = if form_request {
class_basename(id.trim_start_matches("request:")).trim_end_matches("Request").to_string()
} else {
format!("{}Input{n}", studly(module))
};
body += &input_struct(&name, req, if any_auth { "authenticated" } else { "anyone" }, models);
if req["rules"].as_object().is_some_and(|r| r.values().filter_map(Value::as_array).flatten().any(|v| v.as_str().is_some_and(|s| s.starts_with("unique:")))) {
for (m, _, _) in &models.list {
if body.contains(&format!("unique({m}::")) {
uses.insert(format!("crate::models::{m}"));
}
}
}
if body.contains("Sometimes<") {
uses.insert("laravel::validation::Sometimes".into());
}
}
}
if n > 0 {
body = format!("// PORT-TODO: rename each input struct and take it as the handler's last argument: `Valid(input): Valid<Name>`.\n\n{body}");
}
for (r, func) in funcs {
let method = r["method"].as_str().unwrap_or("GET");
let mut args = Vec::new();
let params: Vec<String> = param_re.captures_iter(r["uri"].as_str().unwrap_or("")).map(|c| c[1].to_string()).collect();
if php_auth(r) {
let me = if params.iter().any(|p| ident(p) == "user") { "_auth_user" } else { "_user" };
args.push(format!("Authenticated({me}): Authenticated<User>"));
uses.insert("crate::models::User".into());
}
let model_params: Vec<(String, String)> = params.iter().map(|p| (p.clone(), studly(p))).collect();
if !params.is_empty() && model_params.iter().all(|(_, m)| models.has(m)) {
for (p, m) in &model_params {
args.push(format!("_{}: {m}", ident(p)));
uses.insert(format!("crate::models::{m}"));
}
} else if params.len() == 1 {
args.push(format!("Params(_{}): Params<String>", ident(¶ms[0])));
} else if !params.is_empty() {
let pats = params.iter().map(|p| format!("_{}", ident(p))).collect::<Vec<_>>().join(", ");
let tys = vec!["String"; params.len()].join(", ");
args.push(format!("Params(({pats})): Params<({tys})>"));
}
let ret = if method != "GET" {
"laravel::Result<Redirect>"
} else if inertia {
uses.insert("laravel::inertia::Page".into());
"laravel::Result<Page>"
} else {
uses.insert("laravel::view::View".into());
"laravel::Result<View>"
};
let action = r["action"].as_str().unwrap_or("Closure");
let checks = authorize_hints(inv, action);
let page = match (method, r["name"].as_str()) {
("GET", Some("login")) => "#[laravel::auth::page(login)]\n",
("GET", Some("password.reset")) => "#[laravel::auth::page(reset_password)]\n",
("GET", Some("verification.notice")) => "#[laravel::auth::page(verification_notice)]\n",
("GET", Some("verification.verify")) => "#[laravel::auth::page(verify_email)]\n",
_ => "",
};
body += &format!(
"/// larakiln: {} ({})\n{page}pub async fn {func}({}) -> {ret} {{\n{checks} todo!(\"PORT-TODO: port {}\")\n}}\n\n",
r["id"].as_str().unwrap_or("?"),
class_basename(action),
args.join(", "),
if action == "Closure" { format!("the closure for {method} {}", r["uri"].as_str().unwrap_or("")) } else { action.replace('\\', "\\\\").replace('"', "\\\"") }
);
}
let source = if class == "Closure" { "the PHP closure routes".to_string() } else { class.clone() };
let mut head = format!("// Generated by larakiln codegen from {source}. Search for PORT-TODO.\n#![allow(unused_imports)] // PORT-TODO: remove once every handler is ported\nuse laravel::prelude::*;\n");
for u in uses.iter().filter(|u| !u.starts_with("crate::")) {
head += &format!("use {u};\n");
}
let crate_uses: Vec<String> = uses.iter().filter_map(|u| u.strip_prefix("crate::models::")).map(String::from).collect();
if !crate_uses.is_empty() {
head += &format!("\nuse crate::models::{{{}}};\n", crate_uses.join(", "));
}
files.push((format!("src/http/handlers/{module}.rs"), format!("{head}\n{}", body.trim_end().to_string() + "\n")));
}
let mut wiring = String::new();
let mods: String = by_module.keys().map(|m| format!("pub mod {m};\n")).collect();
if !mods.is_empty() {
wiring += &format!("**`src/http/handlers/mod.rs`**: add\n\n```rust\n{mods}```\n\n");
}
for (file, api) in [("ported", false), ("ported_api", true)] {
let list: Vec<&Handler> = table.iter().filter(|h| h.api == api).collect();
if list.is_empty() {
continue;
}
let modules: BTreeSet<&str> = list.iter().map(|h| h.module.as_str()).collect();
let line = |h: &Handler| {
let uri = if api { h.uri.strip_prefix("/api").filter(|u| !u.is_empty()).unwrap_or("/").to_string() } else { h.uri.clone() };
let uri = uri.replace('?', "");
if h.methods.len() > 1 {
let on: Vec<String> = h.methods.iter().map(|m| format!("Method::{m}")).collect();
format!("route.on(&[{}], \"{uri}\", {}::{});", on.join(", "), h.module, h.func)
} else {
format!("route.{}(\"{uri}\", {}::{});", h.method.to_lowercase(), h.module, h.func)
}
};
let open: Vec<String> = list.iter().filter(|h| !h.auth && !h.guest).map(|h| format!(" {}", line(h))).collect();
let guests: Vec<String> = list.iter().filter(|h| h.guest && !h.auth).map(|h| format!(" {}", line(h))).collect();
let authed: Vec<String> = list.iter().filter(|h| h.auth && !h.verified).map(|h| format!(" {}", line(h))).collect();
let verified: Vec<String> = list.iter().filter(|h| h.auth && h.verified).map(|h| format!(" {}", line(h))).collect();
let mut text = format!(
"// Generated by larakiln codegen from the PHP route list. Routes behind `auth` in PHP are behind `Authenticate` here.\n{}{}use laravel::prelude::*;\n\nuse crate::http::handlers::{{{}}};\n\npub fn routes(route: &mut Router) {{\n",
{
let mut names = Vec::new();
if !authed.is_empty() || !verified.is_empty() { names.push("Authenticate") }
if !guests.is_empty() { names.push("RedirectIfAuthenticated") }
if !verified.is_empty() { names.push("RequireVerifiedEmail") }
match names.len() {
0 => String::new(),
1 => format!("use laravel::auth::{};\n", names[0]),
_ => format!("use laravel::auth::{{{}}};\n", names.join(", ")),
}
},
if list.iter().any(|h| h.methods.len() > 1) { "use laravel::http::Method;\n" } else { "" },
modules.iter().copied().collect::<Vec<_>>().join(", ")
);
for l in &open {
text += &format!("{l}\n");
}
if !guests.is_empty() {
text += &format!("\n // PHP `guest` middleware: logged-in users are sent to the page marked #[laravel::auth::page(home)].\n route.middleware(RedirectIfAuthenticated).group(|route| {{\n{}\n }});\n", guests.join("\n"));
}
if !authed.is_empty() {
text += &format!("\n route.middleware(Authenticate).group(|route| {{\n{}\n }});\n", authed.join("\n"));
}
if !verified.is_empty() {
text += &format!("\n // PHP `verified` middleware: needs `#[derive(MustVerifyEmail)]` on User and a page marked #[laravel::auth::page(verification_notice)].\n route.middleware(Authenticate).middleware(RequireVerifiedEmail).group(|route| {{\n{}\n }});\n", verified.join("\n"));
}
text += "}\n";
files.push((format!("src/routes/{file}.rs"), text));
let target = if api { "api" } else { "web" };
wiring += &format!(
"**`src/routes/mod.rs`**: add `pub mod {file};`. **`src/routes/{target}.rs`**: call `crate::routes::{file}::routes(route);` at the top of `routes`, before any fallback route, and delete the skeleton's own routes for the same URIs (for example `/` and `/login`), or keep them and remove the generated ones.{}\n\n",
if api { " Laravel Rust already prefixes API routes with `/api`, so the generated URIs don't repeat it." } else { "" }
);
}
(files, wiring, names)
}
fn controller_uses(inv: &Value, class: &str, request: &str) -> bool {
let php = Path::new(inv["app"]["path"].as_str().unwrap_or(""));
let rel = class.trim_start_matches("App\\").replace('\\', "/");
fs::read_to_string(php.join("app").join(format!("{rel}.php"))).is_ok_and(|s| s.contains(request))
}
fn views(inv: &Value, php: &Path, names: &HashMap<String, String>) -> Vec<(String, String)> {
let all: Vec<(String, String, String)> = inv["views"].as_array().into_iter().flatten().filter_map(|v| {
let file = v["file"].as_str()?;
let name = v["id"].as_str()?.trim_start_matches("view:");
Some((file.to_string(), name.to_string(), fs::read_to_string(php.join(file)).ok()?))
}).collect();
let (defs, pages): (Vec<_>, Vec<_>) = all.iter().partition(|(_, name, _)| name.starts_with("components."));
let props: crate::components::Props = defs.iter().map(|(_, name, src)| (name["components.".len()..].to_string(), crate::components::props(src, names))).collect();
let mut files: Vec<(String, String)> = pages.iter().map(|(file, name, src)| {
let (jinja, used) = crate::components::usages(&blade_to_jinja(src, names), &props, names);
let jinja = Regex::new(r"<x-[\w.\-:]+").unwrap().replace_all(&jinja, "{# PORT-TODO: component tag not converted #}$0").into_owned();
let jinja = if !used { jinja } else if let Some(rest) = jinja.strip_prefix('{').filter(|r| r.starts_with("% extends")) {
let end = rest.find("%}").map_or(0, |e| e + 3);
format!("{{{}\n{{% import \"components\" as ui %}}{}", &rest[..end], &rest[end..])
} else {
format!("{{% import \"components\" as ui %}}\n{jinja}")
};
(format!("resources/views/{}.html", name.replace('.', "/")), format!("{{# Generated by larakiln codegen from {file}. Search for PORT-TODO. #}}\n{{# larakiln: view:{name} #}}\n{jinja}"))
}).collect();
if !defs.is_empty() {
let macros: Vec<String> = defs.iter().map(|(_, name, src)| crate::components::definition(&name["components.".len()..], src, names, |b| blade_to_jinja(b, names))).collect();
files.push(("resources/views/components.html".into(), format!("{{# Generated by larakiln codegen from resources/views/components. Import with {{% import \"components\" as ui %}}. Search for PORT-TODO. #}}\n\n{}", macros.join("\n"))));
}
files
}
pub(crate) fn unquote(s: &str) -> String {
s.trim().trim_matches(['\'', '"']).to_string()
}
pub(crate) fn split_args(s: &str) -> Vec<String> {
let (mut out, mut cur, mut depth, mut quote) = (Vec::new(), String::new(), 0, None);
for ch in s.chars() {
match (quote, ch) {
(Some(q), c) if c == q => quote = None,
(Some(_), _) => {}
(None, '\'' | '"') => quote = Some(ch),
(None, '(' | '[') => depth += 1,
(None, ')' | ']') => depth -= 1,
(None, ',') if depth == 0 => {
out.push(cur.trim().to_string());
cur.clear();
continue;
}
_ => {}
}
cur.push(ch);
}
if !cur.trim().is_empty() {
out.push(cur.trim().to_string());
}
out
}
pub(crate) fn expr(e: &str, names: &HashMap<String, String>) -> (String, bool) {
let mut s = e.trim().to_string();
s = Regex::new(r#"(?:__|trans)\(\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")\s*\)"#).unwrap()
.replace_all(&s, |c: ®ex::Captures| format!("{:?}", c.get(1).or(c.get(2)).unwrap().as_str().replace("\\'", "'").replace("\\\"", "\"")))
.into_owned();
s = Regex::new(r"\$errors->(?:(\w+)->)?(?:get|first)\(\s*'([^']+)'\s*\)").unwrap()
.replace_all(&s, |c: ®ex::Captures| match c.get(1) {
Some(bag) => format!("error(\"{}\", form=\"{}\")", &c[2], bag.as_str()),
None => format!("error(\"{}\")", &c[2]),
})
.into_owned();
s = Regex::new(r#"Route::has\(\s*['"]([^'"]+)['"]\s*\)"#).unwrap()
.replace_all(&s, |c: ®ex::Captures| if names.contains_key(&c[1]) { "true" } else { "false" })
.into_owned();
let route = Regex::new(r#"route\(\s*'([^']+)'"#).unwrap();
let mut unknown_route = false;
s = route.replace_all(&s, |c: ®ex::Captures| match names.get(&c[1]) {
Some(h) => format!("route(\"{h}\""),
None => {
unknown_route = true;
format!("route(\"{}\"", &c[1])
}
}).into_owned();
let format = Regex::new(r"->format\(([^)]*)\)").unwrap();
let php_date_format = format.is_match(&s); s = format.replace_all(&s, "|date($1)").into_owned();
s = s.replace("->diffForHumans()", "|for_humans");
s = Regex::new(r"count\(\s*\$(\w+)\s*\)").unwrap().replace_all(&s, "$1|length").into_owned();
let (not, null, var, space) = (Regex::new(r"!([^=])").unwrap(), Regex::new(r"\bnull\b").unwrap(), Regex::new(r"\$(\w+)").unwrap(), Regex::new(r"\s+").unwrap());
s = outside_strings(&s, |code| {
let c = code.replace("->", ".").replace("===", "==").replace("!==", "!=").replace("&&", " and ").replace("||", " or ");
let c = not.replace_all(&c, "not $1");
let c = null.replace_all(&c, "none");
let c = var.replace_all(&c, "$1");
space.replace_all(&c, " ").into_owned()
}).trim().to_string();
let allowed = ["route", "old", "url", "csrf_field", "vite", "session", "error", "asset", "date"];
let code = Regex::new(r#""[^"]*""#).unwrap().replace_all(&s, "\"\"").into_owned(); let calls_ok = Regex::new(r"(\w+)\(").unwrap().captures_iter(&code).all(|c| allowed.contains(&&c[1]));
let php_only = code.contains("??") || Regex::new(r"\((array|int|string|bool|float)\)").unwrap().is_match(&code);
let todo = unknown_route || php_date_format || php_only || code.contains("::") || code.contains("this.") || !calls_ok;
(s, todo)
}
fn outside_strings(s: &str, f: impl Fn(&str) -> String) -> String {
let lit = Regex::new(r#""(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'"#).unwrap();
let (mut out, mut last) = (String::new(), 0);
for m in lit.find_iter(s) {
out += &f(&s[last..m.start()]);
let t = m.as_str();
out += &if t.starts_with('\'') { format!("{:?}", t[1..t.len() - 1].replace("\\'", "'")) } else { t.to_string() };
last = m.end();
}
out + &f(&s[last..])
}
fn blade_to_jinja(src: &str, names: &HashMap<String, String>) -> String {
let mut s = Regex::new(r"(?s)\{\{--(.*?)--\}\}").unwrap().replace_all(src, "{#$1#}").into_owned();
s = Regex::new(r#"(?s)@error\(\s*['"]([^'"]+)['"]\s*\)(.*?)@enderror"#).unwrap().replace_all(&s, |c: ®ex::Captures| {
format!("@error('{}'){}@enderror", &c[1], c[2].replace("$message", &format!("error('{}')", &c[1])))
}).into_owned();
s = Regex::new(r"(?s)(^|[^@])\{\{(.*?)\}\}").unwrap().replace_all(&s, |c: ®ex::Captures| {
let (e, todo) = expr(&c[2], names);
format!("{}{{{{ {e} }}}}{}", &c[1], if todo { " {# PORT-TODO: check expression #}" } else { "" })
}).into_owned();
s = Regex::new(r"(?s)\{!!(.*?)!!\}").unwrap().replace_all(&s, |c: ®ex::Captures| {
let (e, todo) = expr(&c[1], names);
format!("{{{{ {e}|safe }}}}{}", if todo { " {# PORT-TODO: check expression #}" } else { "" })
}).into_owned();
let at = Regex::new(r"(^|[\s>])@(\w+)").unwrap();
let loop_re = Regex::new(r"^(.*)\s+as\s+(?:\$(\w+)\s*=>\s*)?\$(\w+)$").unwrap();
let mut out = String::new();
let mut rest = s.as_str();
let mut stack: Vec<String> = Vec::new();
while let Some(c) = at.captures(rest) {
let m = c.get(0).unwrap();
let name = c[2].to_string();
out += &rest[..m.start()];
out += &c[1];
let mut after = &rest[m.end()..];
const CSS: &[&str] = &["layer", "media", "supports", "keyframes", "font", "import", "apply", "tailwind", "theme", "container",
"property", "charset", "namespace", "page", "plugin", "source", "utility", "variant", "custom", "reference", "config", "starting", "scope"];
if CSS.contains(&name.as_str()) {
out += &format!("@{name}");
rest = after;
continue;
}
let mut arg: Option<String> = None;
let trimmed = after.trim_start_matches([' ', '\t']);
if trimmed.starts_with('(') {
if let Some(b) = balanced(trimmed, '(', ')') {
arg = Some(b[1..b.len() - 1].to_string());
after = &trimmed[b.len()..];
}
}
let a = arg.clone().unwrap_or_default();
let ex = |e: &str| {
let (x, todo) = expr(e, names);
(x, if todo { " {# PORT-TODO: check expression #}" } else { "" })
};
let text: String = match name.as_str() {
"extends" => format!("{{% extends \"{}\" %}}", unquote(&split_args(&a)[0])),
"section" => {
let args = split_args(&a);
if args.len() > 1 {
let (v, t) = ex(&args[1]);
format!("{{% block {} %}}{{{{ {v} }}}}{{% endblock %}}{t}", unquote(&args[0]))
} else {
format!("{{% block {} %}}", unquote(&a))
}
}
"endsection" | "stop" | "show" => "{% endblock %}".into(),
"yield" => {
let args = split_args(&a);
let default = args.get(1).map(|d| unquote(d)).unwrap_or_default();
format!("{{% block {} %}}{default}{{% endblock %}}", unquote(&args[0]))
}
"include" => {
let args = split_args(&a);
format!("{{% include \"{}\" %}}{}", unquote(&args[0]), if args.len() > 1 { " {# PORT-TODO: pass the include's data #}" } else { "" })
}
"foreach" | "forelse" => {
stack.push(name.clone());
match loop_re.captures(a.trim()) {
Some(f) => {
let (list, t) = ex(&f[1]);
match f.get(2) {
Some(k) => format!("{{% for {}, {} in {list}|items %}}{t}", k.as_str(), &f[3]),
None => format!("{{% for {} in {list} %}}{t}", &f[3]),
}
}
None => format!("{{# PORT-TODO: @{name}({a}) #}}"),
}
}
"empty" if stack.last().is_some_and(|t| t == "forelse") && arg.is_none() => "{% else %}".into(),
"endforeach" | "endforelse" => {
stack.pop();
"{% endfor %}".into()
}
"if" => {
let (x, t) = ex(&a);
format!("{{% if {x} %}}{t}")
}
"elseif" => {
let (x, t) = ex(&a);
format!("{{% elif {x} %}}{t}")
}
"else" => "{% else %}".into(),
"unless" => {
let (x, t) = ex(&a);
format!("{{% if not ({x}) %}}{t}")
}
"isset" => {
let (x, t) = ex(&a);
format!("{{% if {x} is defined and {x} is not none %}}{t}")
}
"empty" => {
let (x, t) = ex(&a);
format!("{{% if not {x} %}}{t}")
}
"endif" | "endunless" | "endisset" | "endempty" => "{% endif %}".into(),
"csrf" => "{{ csrf_field() }}".into(),
"method" => format!("<input type=\"hidden\" name=\"_method\" value=\"{}\">", unquote(&a).to_uppercase()),
"error" => format!("{{% if error(\"{}\") %}}", unquote(&split_args(&a)[0])),
"enderror" => "{% endif %}".into(),
"vite" => {
let inner = a.trim().trim_start_matches('[').trim_end_matches(']');
split_args(inner).iter().map(|f| format!("{{{{ vite(\"{}\") }}}}", unquote(f))).collect()
}
"json" => {
let (x, t) = ex(&split_args(&a)[0]);
format!("{{{{ {x}|tojson }}}}{t}")
}
"auth" | "guest" => {
let not = if name == "guest" { "not " } else { "" };
let note = if out.contains("auth_user") { "" } else { "{# PORT-TODO: pass `auth_user` from the handler: take `auth: Auth<User>`, then `auth_user => auth.user().await?` #}" };
format!("{{% if {not}(auth_user is defined and auth_user is not none) %}}{note}")
}
"endauth" | "endguest" => "{% endif %}".into(),
"inertia" => "{{ inertia }}".into(),
"inertiaHead" => "{{ inertia_head }}".into(),
_ if name.chars().next().is_some_and(char::is_lowercase) => {
format!("{{# PORT-TODO: @{name}{} has no verified Jinja mapping #}}", arg.map(|a| format!("({a})")).unwrap_or_default())
}
_ => format!("@{name}"),
};
out += &text;
rest = after;
}
out += rest;
Regex::new(r"<(livewire:[\w.\-]+)").unwrap().replace_all(&out, "{# PORT-TODO: Livewire component <$1> #}<$1").into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn operators_are_not_rewritten_inside_strings() {
let names = HashMap::new();
assert_eq!(expr("__('Thanks for signing up! Before && after, null $5')", &names).0, "\"Thanks for signing up! Before && after, null $5\"");
assert_eq!(expr("! $user->verified && $x === null", &names).0, "not user.verified and x == none");
assert_eq!(expr("old('name', 'it\\'s')", &names).0, "old(\"name\", \"it's\")");
}
#[test]
fn migrations_become_columns() {
let mut cols = Vec::new();
for s in [
"{\n $table->id()".trim_start_matches('{').trim(),
"$table->foreignId('user_id')->constrained()->cascadeOnDelete()",
"$table->string('message')",
"$table->timestamp('seen_at')->nullable()",
"$table->unique('message')",
"$table->timestamps()",
"$table->rememberToken()",
] {
apply(&mut cols, s);
}
let got: Vec<(String, String, bool)> = cols.into_iter().map(|c| (c.name, c.ty, c.nullable)).collect();
let want = [("id", "u64", false), ("user_id", "u64", false), ("message", "String", false), ("seen_at", "Timestamp", true), ("created_at", "Timestamp", false), ("updated_at", "Timestamp", false), ("remember_token", "RememberToken", true)];
assert_eq!(got, want.map(|(a, b, c)| (a.to_string(), b.to_string(), c)));
}
#[test]
fn rules_become_validate_attributes() {
let models = Models { list: vec![("User".into(), json!({}), "users".into())], tables: HashMap::new(), php: PathBuf::new() };
let req = json!({"id": "request:X#1", "rules": {
"message": ["required", "string", "max:255"],
"age": ["nullable", "integer", "min:18"],
"email": ["required", "email", "unique:users,email"],
"role": ["in:admin,editor"],
"photo": ["image"],
"handle": ["required", "unique:", "User::class"],
"password": ["required", "confirmed", "Password::defaults"]
}});
let s = input_struct("NewChirp", &req, "authenticated", &models);
assert!(s.contains("#[validate(authenticated)]\npub struct NewChirp"), "{s}");
assert!(s.contains("#[validate(required, max_length(255))]\n pub message: String,"), "{s}");
assert!(s.contains("#[validate(min_value(18))]\n pub age: Option<i64>,"), "{s}");
assert!(s.contains("#[validate(required, email, unique(User::email))]"), "{s}");
assert!(s.contains("one_of(\"admin\", \"editor\")"), "{s}");
assert!(s.contains("PORT-TODO: no verified mapping for image"), "{s}");
assert!(s.contains("#[validate(required, unique(User::handle))]"), "{s}");
assert!(s.contains("#[validate(required, confirmed, password)]\n pub password: laravel::hash::Password,"), "{s}");
}
#[test]
fn blade_becomes_jinja() {
let names: HashMap<String, String> = [("chirps.store".to_string(), "chirps::store".to_string()), ("chirps.edit".to_string(), "chirps::edit".to_string())].into();
let blade = "@extends('layout')\n@section('content')\n<form action=\"{{ route('chirps.store') }}\">\n@csrf\n@method('delete')\n@error('message')\n<p>{{ $message }}</p>\n@enderror\n@foreach ($chirps as $chirp)\n<a href=\"{{ route('chirps.edit', $chirp) }}\">{{ $chirp->user->name }}</a>\n@if ($chirp->user->is(auth()->user()))\nx\n@endif\n@endforeach\n@endsection\nmail@example.com\n";
let j = blade_to_jinja(blade, &names);
for want in [
"{% extends \"layout\" %}",
"{% block content %}",
"{{ route(\"chirps::store\") }}",
"{{ csrf_field() }}",
"value=\"DELETE\"",
"{% if error(\"message\") %}\n<p>{{ error(\"message\") }}</p>\n{% endif %}",
"{% for chirp in chirps %}",
"{{ route(\"chirps::edit\", chirp) }}",
"{{ chirp.user.name }}",
"{% if chirp.user.is(auth().user()) %} {# PORT-TODO: check expression #}",
"action=\"{{ route(\"chirps::store\") }}\">",
"{% endfor %}\n{% endblock %}",
"mail@example.com",
] {
assert!(j.contains(want), "missing {want:?} in:\n{j}");
}
}
#[test]
fn policies_translate_ownership_and_fail_closed() {
let dir = std::env::temp_dir().join(format!("larakiln-policy-{}", std::process::id()));
fs::create_dir_all(dir.join("app/Policies")).unwrap();
fs::write(dir.join("app/Policies/ChirpPolicy.php"), "<?php\nclass ChirpPolicy {\n public function update(User $user, Chirp $chirp): bool\n {\n return $chirp->user()->is($user);\n }\n public function delete(User $user, Chirp $chirp): bool { return $this->update($user, $chirp); }\n public function viewAny(User $user): bool { return $user->isAdmin(); }\n public function create(): bool\n {\n return true;\n }\n}\n").unwrap();
let inv = serde_json::json!({"policies": [{"file": "app/Policies/ChirpPolicy.php", "id": "policy:ChirpPolicy"}]});
let (_, text) = policies(&inv, &dir).unwrap();
fs::remove_dir_all(&dir).ok();
for want in ["use crate::models::{Chirp, User};", "pub fn update(user: &User, chirp: &Chirp) -> bool {\n user.id == chirp.user_id", "Self::update(user, chirp)", "pub fn view_any(user: &User) -> bool {\n todo!(\"PORT-TODO: port `return $user->isAdmin();`\")", "pub fn create(_user: &User) -> bool {\n true"] {
assert!(text.contains(want), "missing {want:?} in:\n{text}");
}
}
#[test]
fn same_rules_share_a_struct_and_guest_routes_get_their_group() {
let rules = json!({"message": ["required", "max:255"]});
let inv = json!({
"app": {"path": "/nowhere", "frontend": "blade"},
"routes": [
{"id": "route:GET:/login", "method": "GET", "uri": "/login", "name": "login", "action": "App\\Http\\Controllers\\LoginController@create", "middleware": ["web", "guest"]},
{"id": "route:POST:/chirps", "method": "POST", "uri": "/chirps", "action": "App\\Http\\Controllers\\ChirpController@store", "middleware": ["web", "auth"]},
],
"requests": [
{"id": "request:app/Http/Controllers/ChirpController.php#1", "file": "app/Http/Controllers/ChirpController.php", "rules": rules},
{"id": "request:app/Http/Controllers/ChirpController.php#2", "file": "app/Http/Controllers/ChirpController.php", "rules": rules},
],
});
let models = Models { list: vec![], tables: HashMap::new(), php: PathBuf::new() };
let (files, _, _) = handlers(&inv, &models);
let get = |f: &str| files.iter().find(|(p, _)| p == f).map(|(_, t)| t.clone()).unwrap();
let chirps = get("src/http/handlers/chirps.rs");
assert!(chirps.contains("/// larakiln: request:app/Http/Controllers/ChirpController.php#1\n/// larakiln: request:app/Http/Controllers/ChirpController.php#2\n"), "{chirps}");
assert_eq!(chirps.matches("pub struct").count(), 1, "{chirps}");
let routes = get("src/routes/ported.rs");
assert!(routes.contains("route.middleware(RedirectIfAuthenticated).group(|route| {\n route.get(\"/login\""), "{routes}");
assert!(get("src/http/handlers/logins.rs").contains("#[laravel::auth::page(login)]"));
}
#[test]
fn factory_values_map_to_faker() {
for (php, rust) in [
("$this->faker->firstName()", Some("fake.first_name()")),
("fake()->unique()->safeEmail()", Some("fake.unique().email()")),
("$this->faker->tollFreePhoneNumber()", Some("fake.phone_number()")),
("$this->faker->postcode()", Some("fake.postal_code()")),
("$this->faker->numberBetween(1, 5)", Some("fake.number(1..=5)")),
("'US'", Some("\"US\"")),
("now()", Some("laravel::now()")),
("User::factory()", Some("User::factory()")),
("static::$password ??= Hash::make('password')", Some("\"password\"")),
("$this->faker->dateTimeBetween('-1 year')", None),
] {
assert_eq!(faker_value(php).as_deref(), rust, "{php}");
}
}
#[test]
fn php_columns_become_schema_calls() {
for (php, rust) in [
("$table->id()", "table.id();"),
("$table->string('email', 50)->nullable()->unique()", "table.string(\"email\").length(50).nullable().unique();"),
("$table->increments('id')", "table.increments(\"id\");"),
("$table->unsignedInteger('n')->nullable()", "table.integer(\"n\").unsigned().nullable();"),
("$table->timestamp('at')->useCurrent()", "table.timestamp(\"at\").use_current();"),
("$table->foreignId('user_id')->constrained()->cascadeOnDelete()", "table.foreign_id(\"user_id\").constrained().cascade_on_delete();"),
("$table->foreignId('owner_id')->constrained('users')", "table.foreign_id(\"owner_id\").references(\"users\");"),
("$table->integer('account_id')->index()", "table.integer(\"account_id\").index();"),
("$table->index(['a', 'b'])", "table.index([\"a\", \"b\"]);"),
("$table->string('id')->primary()", "table.string(\"id\").primary();"),
("$table->boolean('owner')->default(false)", "table.boolean(\"owner\").default(false);"),
("$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')", "table.foreign([\"user_id\"]).references(\"users\", [\"id\"]).cascade_on_delete();"),
("$table->dateTimeTz('at')", "table.date_time(\"at\");"),
("$table->softDeletes()", "table.soft_deletes();"),
("$table->morphs('tokenable')", "table.morphs(\"tokenable\");"),
] {
assert_eq!(column_stmt(php), rust, "{php}");
}
assert!(column_stmt("$table->point('where')").starts_with("// PORT-TODO"));
assert!(column_stmt("$table->foreign('x_id')").starts_with("// PORT-TODO"));
assert_eq!(column_stmt("$table->foreignIdFor(User::class, 'creator_id')->constrained()"), "table.foreign_id(\"creator_id\").references(\"users\");");
assert_eq!(column_stmt("$table->foreignIdFor(User::class)->constrained()"), "table.foreign_id(\"user_id\").references(\"users\");");
assert_eq!(framework_time("sessions", column_stmt("$table->integer('last_activity')->index()")), "table.timestamp(\"last_activity\").index();");
assert_eq!(framework_time("jobs", column_stmt("$table->unsignedInteger('available_at')")), "table.timestamp(\"available_at\");");
assert_eq!(framework_time("chirps", column_stmt("$table->integer('likes')")), "table.integer(\"likes\");");
}
#[test]
fn auth_route_has_and_css_at_rules() {
let names: HashMap<String, String> = [("login".to_string(), "closures::get_login".to_string())].into();
let blade = "<style>@layer base{a{b:c}} @supports (x:y) {}</style>\n@if (Route::has('login'))\n@auth\nhi\n@else\n@if (Route::has('register'))\nr\n@endif\n@endauth\n@guest\ng\n@endguest\n@endif\n";
let j = blade_to_jinja(blade, &names);
for want in [
"<style>@layer base{a{b:c}} @supports (x:y) {}</style>",
"{% if true %}",
"{% if false %}",
"{% if (auth_user is defined and auth_user is not none) %}{# PORT-TODO: pass `auth_user`",
"{% if not (auth_user is defined and auth_user is not none) %}\ng",
] {
assert!(j.contains(want), "missing {want:?} in:\n{j}");
}
assert_eq!(j.matches("PORT-TODO").count(), 1, "{j}");
}
#[test]
fn foreign_keys_take_their_keys_type() {
let col = |name: &str, ty: &str| Column { name: name.into(), ty: ty.into(), nullable: false, note: None, default: false };
let mut models = Models {
list: vec![
("Account".into(), json!({"relations": [{"name": "contacts", "related": "Contact", "type": "hasMany"}, {"name": "owned", "related": "Organization", "type": "hasMany", "foreign_key": "owner_id"}]}), "accounts".into()),
("Contact".into(), json!({"relations": [{"name": "organization", "related": "Organization", "type": "belongsTo"}]}), "contacts".into()),
("Organization".into(), json!({}), "organizations".into()),
],
tables: HashMap::from([
("accounts".into(), vec![col("id", "i32")]),
("contacts".into(), vec![col("id", "i64"), col("account_id", "i64"), col("organization_id", "i64")]),
("organizations".into(), vec![col("id", "i32"), col("owner_id", "i64")]),
]),
php: PathBuf::new(),
};
models.match_key_types();
let ty = |c: &str| models.tables["contacts"].iter().find(|x| x.name == c).unwrap().ty.clone();
assert_eq!((ty("account_id"), ty("organization_id"), ty("id")), ("i32".into(), "i32".into(), "i64".into()));
assert_eq!(models.tables["organizations"][1].ty, "i32", "hasMany(.., 'owner_id') types owner_id");
}
#[test]
fn authorize_resource_maps_actions_to_abilities() {
let src = "public function __construct() { $this->authorizeResource(Chirp::class, 'chirp'); }";
assert!(resource_hint(src, "update").contains("ChirpPolicy::update, &chirp)"));
assert!(resource_hint(src, "index").contains("ChirpPolicy::view_any, ())"));
assert_eq!(resource_hint(src, "custom"), "");
assert_eq!(resource_hint("class X {}", "update"), "");
}
}