1use crate::php::{self, CallStep};
20use anyhow::Result;
21use std::path::Path;
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct RouteEntry {
25 pub method: &'static str,
26 pub path: String,
27 pub controller: String,
28 pub controller_method: String,
29 pub name: Option<String>,
30 pub livewire_component: Option<String>,
34}
35
36#[derive(Debug, Default)]
37pub struct RoutesConversion {
38 pub entries: Vec<RouteEntry>,
39 pub unrecognized: Vec<String>,
40}
41
42pub fn convert(source: &str, laravel_root: &Path) -> Result<RoutesConversion> {
43 let tree = php::parse(source)?;
44 let mut result = RoutesConversion::default();
45
46 if php::has_syntax_error(&tree) {
47 result
48 .unrecognized
49 .push("file has a syntax error the parser couldn't recover from".to_string());
50 return Ok(result);
51 }
52
53 let livewire_aliases = livewire_aliases(source);
54 for expr in php::statement_expressions(tree.root_node()) {
55 process_statement(expr, source, &livewire_aliases, laravel_root, &mut result);
56 }
57
58 Ok(result)
59}
60
61fn process_statement(
62 expr: tree_sitter::Node,
63 source: &str,
64 livewire_aliases: &std::collections::HashMap<String, String>,
65 laravel_root: &Path,
66 result: &mut RoutesConversion,
67) {
68 let Some(chain) = php::walk_call_chain(expr, source) else {
69 return;
70 };
71 let Some(base) = chain.first() else {
72 return;
73 };
74 if base.scope.as_deref() != Some("Route") {
75 return;
76 }
77
78 match base.method.as_str() {
79 "resource" => expand_resource(base, result),
80 "get" | "post" | "put" | "patch" | "delete" => add_single_route(
81 base.method.as_str(),
82 &chain,
83 livewire_aliases,
84 laravel_root,
85 result,
86 ),
87 "middleware" | "group" => {
88 result.unrecognized.push(
89 "Route::middleware(...)/Route::group(...) block - routes inside a group are not converted automatically; migrate this group and its middleware by hand".to_string(),
90 );
91 }
92 other => {
93 result.unrecognized.push(format!(
94 "Route::{other}(...) - not a route-registration pattern this phase converts"
95 ));
96 }
97 }
98}
99
100fn add_single_route(
101 method: &str,
102 chain: &[CallStep],
103 livewire_aliases: &std::collections::HashMap<String, String>,
104 laravel_root: &Path,
105 result: &mut RoutesConversion,
106) {
107 let base = &chain[0];
108 let Some(path_arg) = base.args.first() else {
109 return;
110 };
111 let path = if is_string_literal(path_arg) {
112 php::unquote(path_arg)
113 } else if let Some(resolved) = resolve_dynamic_path(path_arg, laravel_root) {
114 resolved
115 } else {
116 result.unrecognized.push(format!(
117 "Route::{method}(...): dynamic route paths are not converted automatically"
118 ));
119 return;
120 };
121
122 let Some(action_arg) = base.args.get(1) else {
123 result.unrecognized.push(format!(
124 "Route::{method}('{path}', ...) - no action argument found"
125 ));
126 return;
127 };
128 let action = parse_action_array(action_arg)
129 .map(|(controller, controller_method)| (controller, controller_method, None))
130 .or_else(|| {
131 parse_livewire_class(action_arg, livewire_aliases).map(|component| {
132 let handler = livewire_handler_name(&component);
133 ("LivewirePages".to_string(), handler, Some(component))
134 })
135 });
136 let Some((controller, controller_method, livewire_component)) = action else {
137 result.unrecognized.push(format!(
138 "Route::{method}('{path}', ...) - action is a closure or an unrecognized shape, not `[Controller::class, 'method']`"
139 ));
140 return;
141 };
142
143 let name = chain[1..]
144 .iter()
145 .find(|step| step.method == "name")
146 .and_then(|step| step.args.first())
147 .map(|raw| php::unquote(raw));
148
149 result.entries.push(RouteEntry {
150 method: static_method(method),
151 path,
152 controller,
153 controller_method,
154 name,
155 livewire_component,
156 });
157}
158
159fn expand_resource(base: &CallStep, result: &mut RoutesConversion) {
171 let Some(prefix_arg) = base.args.first() else {
172 return;
173 };
174 let prefix = php::unquote(prefix_arg);
175 let Some(controller_arg) = base.args.get(1) else {
176 result.unrecognized.push(format!(
177 "Route::resource('{prefix}', ...) - no controller argument found"
178 ));
179 return;
180 };
181 let Some(controller) = controller_arg.strip_suffix("::class").map(str::trim) else {
182 result.unrecognized.push(format!(
183 "Route::resource('{prefix}', ...) - controller argument isn't a `Foo::class` reference"
184 ));
185 return;
186 };
187 let param = singularize(&prefix);
188
189 let actions: [(&'static str, &'static str, String, &'static str); 7] = [
190 ("get", "index", format!("/{prefix}"), "index"),
191 ("get", "create", format!("/{prefix}/create"), "create"),
192 ("post", "store", format!("/{prefix}"), "store"),
193 ("get", "show", format!("/{prefix}/{{{param}}}"), "show"),
194 ("get", "edit", format!("/{prefix}/{{{param}}}/edit"), "edit"),
195 ("put", "update", format!("/{prefix}/{{{param}}}"), "update"),
196 (
197 "delete",
198 "destroy",
199 format!("/{prefix}/{{{param}}}"),
200 "destroy",
201 ),
202 ];
203
204 for (method, name_suffix, path, controller_method) in actions {
205 result.entries.push(RouteEntry {
206 method: static_method(method),
207 path,
208 controller: controller.to_string(),
209 controller_method: controller_method.to_string(),
210 name: Some(format!("{prefix}.{name_suffix}")),
211 livewire_component: None,
212 });
213 }
214}
215
216fn resolve_dynamic_path(raw: &str, laravel_root: &Path) -> Option<String> {
230 let wrapped = format!("<?php {raw};");
231 let tree = php::parse(&wrapped).ok()?;
232 if php::has_syntax_error(&tree) {
233 return None;
234 }
235 let expr = php::statement_expressions(tree.root_node())
236 .into_iter()
237 .next()?;
238 resolve_concat(expr, &wrapped, laravel_root)
239}
240
241fn resolve_concat(node: tree_sitter::Node, source: &str, laravel_root: &Path) -> Option<String> {
242 let bytes = source.as_bytes();
243 match node.kind() {
244 "string" => {
245 let raw = node.utf8_text(bytes).ok()?;
246 is_string_literal(raw).then(|| php::unquote(raw))
247 }
248 "encapsed_string" => {
254 let raw = node.utf8_text(bytes).ok()?;
255 let text = php::unquote(raw);
256 (!text.contains('$')).then_some(text)
257 }
258 "parenthesized_expression" => resolve_concat(node.named_child(0)?, source, laravel_root),
259 "binary_expression" => {
260 let left = node.child_by_field_name("left")?;
261 let right = node.child_by_field_name("right")?;
262 let operator = source.get(left.end_byte()..right.start_byte())?.trim();
267 if operator != "." {
268 return None;
269 }
270 let left_text = resolve_concat(left, source, laravel_root)?;
271 let right_text = resolve_concat(right, source, laravel_root)?;
272 Some(format!("{left_text}{right_text}"))
273 }
274 "function_call_expression" => {
275 let function = node.child_by_field_name("function")?;
276 if function.utf8_text(bytes).ok()? != "config" {
277 return None;
278 }
279 let arg = php::argument_node(node, 0)?;
280 let key = php::unquote(arg.utf8_text(bytes).ok()?);
281 resolve_config_string(laravel_root, &key)
282 }
283 _ => None,
284 }
285}
286
287fn resolve_config_string(laravel_root: &Path, dotted_key: &str) -> Option<String> {
296 let (file_stem, key) = dotted_key.split_once('.')?;
297 let path = laravel_root.join(format!("config/{file_stem}.php"));
298 let source = std::fs::read_to_string(path).ok()?;
299 let tree = php::parse(&source).ok()?;
300 if php::has_syntax_error(&tree) {
301 return None;
302 }
303 let (_, value_node) = crate::config::top_level_entries(&tree, &source)
304 .into_iter()
305 .find(|(entry_key, _)| entry_key == key)?;
306 if value_node.kind() != "string" {
307 return None;
308 }
309 Some(php::unquote(value_node.utf8_text(source.as_bytes()).ok()?))
310}
311
312fn is_string_literal(value: &str) -> bool {
313 let value = value.trim();
314 matches!(value.as_bytes().first(), Some(b'\'' | b'\"'))
315 && value.len() >= 2
316 && value.as_bytes().first() == value.as_bytes().last()
317 && !value[1..value.len() - 1].contains(value.as_bytes()[0] as char)
318}
319
320fn livewire_aliases(source: &str) -> std::collections::HashMap<String, String> {
321 let mut aliases = std::collections::HashMap::new();
322 for line in source.lines().map(str::trim) {
323 let Some(rest) = line.strip_prefix("use App\\Livewire\\") else {
324 continue;
325 };
326 let rest = rest.trim_end_matches(';').trim();
327 let (class, alias) = if let Some((class, alias)) = rest.rsplit_once(" as ") {
328 (class.trim(), alias.trim())
329 } else {
330 (rest, rest.rsplit('\\').next().unwrap_or(rest))
331 };
332 aliases.insert(alias.to_string(), format!("App\\Livewire\\{class}"));
333 }
334 aliases
335}
336
337fn parse_livewire_class(
338 text: &str,
339 aliases: &std::collections::HashMap<String, String>,
340) -> Option<String> {
341 let class = text
342 .trim()
343 .strip_suffix("::class")?
344 .trim()
345 .trim_start_matches('\\');
346 if let Some(component) = aliases.get(class) {
347 return Some(component.clone());
348 }
349 class
350 .strip_prefix("App\\Livewire\\")
351 .map(|_| class.to_string())
352}
353
354fn livewire_handler_name(component: &str) -> String {
355 let normalized = component
356 .chars()
357 .map(|ch| {
358 if ch.is_ascii_alphanumeric() {
359 ch.to_ascii_lowercase()
360 } else {
361 '_'
362 }
363 })
364 .collect::<String>();
365 format!("mount_{}", normalized.trim_matches('_'))
366}
367
368fn static_method(method: &str) -> &'static str {
369 match method {
370 "get" => "get",
371 "post" => "post",
372 "put" => "put",
373 "patch" => "patch",
374 "delete" => "delete",
375 _ => "get",
376 }
377}
378
379fn parse_action_array(text: &str) -> Option<(String, String)> {
384 let inner = text.trim().trim_start_matches('[').trim_end_matches(']');
385 let mut parts = inner.splitn(2, ',');
386 let controller = parts
387 .next()?
388 .trim()
389 .strip_suffix("::class")?
390 .trim()
391 .to_string();
392 let method = php::unquote(parts.next()?.trim());
393 if controller.is_empty() || method.is_empty() {
394 return None;
395 }
396 Some((controller, method))
397}
398
399fn singularize(word: &str) -> String {
405 if let Some(stem) = word.strip_suffix("ies") {
406 return format!("{stem}y");
407 }
408 for suffix in ["xes", "zes", "ches", "shes"] {
409 if let Some(stem) = word.strip_suffix(suffix) {
410 return format!("{stem}{}", &suffix[..1]);
411 }
412 }
413 word.strip_suffix('s').unwrap_or(word).to_string()
414}
415
416pub fn render_chain(entries: &[RouteEntry]) -> Option<String> {
422 let (first, rest) = entries.split_first()?;
423 let mut out = format!(
424 "Route::{}(\"{}\", {}::{})",
425 first.method, first.path, first.controller, first.controller_method
426 );
427 if let Some(name) = &first.name {
428 out.push_str(&format!("\n .name(\"{name}\")"));
429 }
430 for entry in rest {
431 out.push_str(&format!(
432 "\n .{}(\"{}\", {}::{})",
433 entry.method, entry.path, entry.controller, entry.controller_method
434 ));
435 if let Some(name) = &entry.name {
436 out.push_str(&format!("\n .name(\"{name}\")"));
437 }
438 }
439 Some(out)
440}
441
442pub fn referenced_controllers(entries: &[RouteEntry]) -> Vec<(String, Vec<String>)> {
450 let mut controllers: Vec<(String, Vec<String>)> = Vec::new();
451 for entry in entries {
452 if entry.livewire_component.is_some() {
453 continue;
454 }
455 if let Some((_, methods)) = controllers
456 .iter_mut()
457 .find(|(name, _)| *name == entry.controller)
458 {
459 if !methods.contains(&entry.controller_method) {
460 methods.push(entry.controller_method.clone());
461 }
462 } else {
463 controllers.push((
464 entry.controller.clone(),
465 vec![entry.controller_method.clone()],
466 ));
467 }
468 }
469 controllers
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475
476 #[test]
477 fn converts_a_named_get_route() {
478 let source = r#"<?php
479use App\Http\Controllers\PostController;
480use Illuminate\Support\Facades\Route;
481
482Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
483"#;
484 let result = convert(source, Path::new("/nonexistent")).unwrap();
485 assert_eq!(result.entries.len(), 1);
486 let entry = &result.entries[0];
487 assert_eq!(entry.method, "get");
488 assert_eq!(entry.path, "/posts");
489 assert_eq!(entry.controller, "PostController");
490 assert_eq!(entry.controller_method, "index");
491 assert_eq!(entry.name.as_deref(), Some("posts.index"));
492 assert!(result.unrecognized.is_empty());
493 }
494
495 #[test]
496 fn flags_a_closure_action_instead_of_guessing() {
497 let source = r#"<?php
498Route::get('/', function () {
499 return view('welcome');
500});
501"#;
502 let result = convert(source, Path::new("/nonexistent")).unwrap();
503 assert!(result.entries.is_empty());
504 assert_eq!(result.unrecognized.len(), 1);
505 assert!(result.unrecognized[0].contains("closure"));
506 }
507
508 #[test]
509 fn converts_an_imported_livewire_component_route_to_a_page_shell() {
510 let source = r#"<?php
511use App\Livewire\Pages\Blog;
512Route::get('/blog/{slug}', Blog::class)->name('blog.show');
513"#;
514 let result = convert(source, Path::new("/nonexistent")).unwrap();
515 assert_eq!(result.entries.len(), 1);
516 let entry = &result.entries[0];
517 assert_eq!(entry.controller, "LivewirePages");
518 assert_eq!(entry.path, "/blog/{slug}");
519 assert_eq!(
520 entry.livewire_component.as_deref(),
521 Some("App\\Livewire\\Pages\\Blog")
522 );
523 }
524
525 #[test]
526 fn resolves_a_config_backed_path_prefix_from_the_project_s_own_config_file() {
527 let tmp = tempfile::tempdir().unwrap();
528 std::fs::create_dir_all(tmp.path().join("config")).unwrap();
529 std::fs::write(
530 tmp.path().join("config/routes.php"),
531 "<?php\nreturn [\n 'web' => 'web-services',\n];\n",
532 )
533 .unwrap();
534 let source = r#"<?php
535use App\Livewire\Home;
536Route::get('/'.config('routes.web'), Home::class);
537Route::get("/". config('routes.web') . '/seo', Home::class);
538"#;
539 let result = convert(source, tmp.path()).unwrap();
540 assert!(result.unrecognized.is_empty());
541 assert_eq!(result.entries.len(), 2);
542 assert_eq!(result.entries[0].path, "/web-services");
543 assert_eq!(result.entries[1].path, "/web-services/seo");
544 }
545
546 #[test]
547 fn flags_dynamic_paths_instead_of_guessing_when_the_config_value_cant_be_read() {
548 let source = r#"<?php
549use App\Livewire\Home;
550Route::get('/'.config('routes.web'), Home::class);
551Route::get('/'.$prefix, Home::class);
552"#;
553 let result = convert(source, Path::new("/nonexistent")).unwrap();
557 assert!(result.entries.is_empty());
558 assert_eq!(result.unrecognized.len(), 2);
559 assert!(result.unrecognized[0].contains("dynamic route paths"));
560 assert!(result.unrecognized[1].contains("dynamic route paths"));
561 }
562
563 #[test]
564 fn flags_middleware_groups_instead_of_dropping_protection() {
565 let source = r#"<?php
566Route::middleware('auth')->group(function () {
567 Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create');
568});
569"#;
570 let result = convert(source, Path::new("/nonexistent")).unwrap();
571 assert!(result.entries.is_empty());
572 assert_eq!(result.unrecognized.len(), 1);
573 assert!(result.unrecognized[0].contains("not converted automatically"));
574 }
575
576 #[test]
577 fn expands_resource_into_seven_entries() {
578 let source = "<?php\nRoute::resource('photos', PhotoController::class);\n";
579 let result = convert(source, Path::new("/nonexistent")).unwrap();
580 assert_eq!(result.entries.len(), 7);
581 assert_eq!(result.entries[0].path, "/photos");
582 assert_eq!(result.entries[0].name.as_deref(), Some("photos.index"));
583 assert_eq!(result.entries[3].path, "/photos/{photo}");
584 assert_eq!(result.entries[3].method, "get");
585 assert_eq!(result.entries[3].controller_method, "show");
586 assert_eq!(result.entries[5].method, "put");
587 assert_eq!(result.entries[6].method, "delete");
588 }
589
590 #[test]
591 fn render_chain_produces_a_fluent_route_chain() {
592 let entries = vec![
593 RouteEntry {
594 method: "get",
595 path: "/posts".to_string(),
596 controller: "PostController".to_string(),
597 controller_method: "index".to_string(),
598 name: Some("posts.index".to_string()),
599 livewire_component: None,
600 },
601 RouteEntry {
602 method: "post",
603 path: "/posts".to_string(),
604 controller: "PostController".to_string(),
605 controller_method: "store".to_string(),
606 name: None,
607 livewire_component: None,
608 },
609 ];
610 let chain = render_chain(&entries).unwrap();
611 assert!(chain.starts_with("Route::get(\"/posts\", PostController::index)"));
612 assert!(chain.contains(".name(\"posts.index\")"));
613 assert!(chain.contains(".post(\"/posts\", PostController::store)"));
614 assert!(!chain.contains("PostController::store)\n .name"));
615 }
616
617 #[test]
618 fn referenced_controllers_deduplicates_methods() {
619 let entries = vec![
620 RouteEntry {
621 method: "get",
622 path: "/posts".to_string(),
623 controller: "PostController".to_string(),
624 controller_method: "index".to_string(),
625 name: None,
626 livewire_component: None,
627 },
628 RouteEntry {
629 method: "get",
630 path: "/posts/{post}".to_string(),
631 controller: "PostController".to_string(),
632 controller_method: "show".to_string(),
633 name: None,
634 livewire_component: None,
635 },
636 ];
637 let controllers = referenced_controllers(&entries);
638 assert_eq!(controllers.len(), 1);
639 assert_eq!(controllers[0].0, "PostController");
640 assert_eq!(
641 controllers[0].1,
642 vec!["index".to_string(), "show".to_string()]
643 );
644 }
645}