larakiln 0.4.2

Port Laravel PHP apps to a new Laravel runtime (Laravel Rust today) and check nothing was lost: audit, plan, codegen, route parity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Read-only inventory of a Laravel PHP app. Routes come from `artisan route:list --json`;
//! everything else from a static scan of app/, routes/, resources/views/, tests/ and composer files.

use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use std::process::Command;

use regex::Regex;
use serde_json::{Value, json};
use walkdir::WalkDir;

pub fn run(app: &Path, out: &Path, php: &str) -> Result<(), String> {
    let app = app.canonicalize().map_err(|e| format!("{}: {e}", app.display()))?;
    if !app.join("artisan").exists() {
        return Err(format!("{} has no artisan file; not a Laravel app", app.display()));
    }
    let out_abs = std::path::absolute(out).map_err(|e| e.to_string())?;
    if out_abs.starts_with(&app) {
        return Err("--out points inside the PHP app; the PHP app is read-only".into());
    }

    let mut notes = Vec::new();
    let routes = routes(&app, php).unwrap_or_else(|e| {
        notes.push(format!("routes: {e}. Re-run with a working --php to list routes."));
        vec![]
    });

    let mut bg = background(&app);
    let inventory = json!({
        "larakiln": env!("CARGO_PKG_VERSION"),
        "app": app_info(&app),
        "routes": routes,
        "models": models(&app),
        "requests": requests(&app),
        "views": views(&app),
        "jobs": bg.remove("job").unwrap_or_default(),
        "mail": bg.remove("mail").unwrap_or_default(),
        "notifications": bg.remove("notification").unwrap_or_default(),
        "events": bg.remove("event").unwrap_or_default(),
        "listeners": bg.remove("listener").unwrap_or_default(),
        "observers": bg.remove("observer").unwrap_or_default(),
        "commands": bg.remove("command").unwrap_or_default(),
        "policies": classes(&app, "app/Policies", "policy"),
        "middleware": classes(&app, "app/Http/Middleware", "middleware"),
        "schedule": schedule(&app),
        "packages": packages(&app),
        "data_risks": data_risks(&app),
        "tests": tests(&app),
        "notes": notes,
    });

    fs::write(out, serde_json::to_string_pretty(&inventory).unwrap()).map_err(|e| e.to_string())?;
    let count = |k: &str| inventory[k].as_array().map_or(0, Vec::len);
    eprintln!(
        "larakiln audit: {} routes, {} models, {} requests, {} views, {} packages, {} data risks -> {}",
        count("routes"),
        count("models"),
        count("requests"),
        count("views"),
        count("packages"),
        count("data_risks"),
        out.display()
    );
    Ok(())
}

fn routes(app: &Path, php: &str) -> Result<Vec<Value>, String> {
    let mut parts = php.split_whitespace();
    let bin = parts.next().ok_or("empty --php")?;
    let output = Command::new(bin)
        .args(parts)
        .args(["artisan", "route:list", "--json"])
        .current_dir(app)
        .output()
        .map_err(|e| format!("could not run `{php} artisan`: {e}"))?;
    if !output.status.success() {
        let err = String::from_utf8_lossy(&output.stderr);
        return Err(format!("`{php} artisan route:list --json` failed: {}", err.lines().last().unwrap_or("")));
    }
    // PHP may print deprecation notices on stdout before the JSON (PHP 8.5 with older Laravel configs).
    let stdout = String::from_utf8_lossy(&output.stdout);
    let json = stdout.find("\n[").map_or(stdout.as_ref(), |i| &stdout[i + 1..]);
    let list: Vec<Value> = serde_json::from_str(json.trim()).map_err(|e| format!("route:list JSON: {e}"))?;

    Ok(list
        .into_iter()
        .map(|r| {
            let methods: Vec<&str> = r["method"].as_str().unwrap_or("").split('|').filter(|m| !m.is_empty() && *m != "HEAD").collect();
            let method = methods.first().unwrap_or(&"GET").to_string();
            let uri = format!("/{}", r["uri"].as_str().unwrap_or("").trim_start_matches('/'));
            json!({
                "id": format!("route:{method}:{uri}"),
                "method": method,
                "methods": methods,
                "uri": uri,
                "name": r["name"],
                "action": r["action"],
                "middleware": r["middleware"],
            })
        })
        .collect())
}

fn app_info(app: &Path) -> Value {
    let composer = read_json(&app.join("composer.json"));
    let lock = read_json(&app.join("composer.lock"));
    let laravel = lock["packages"]
        .as_array()
        .and_then(|p| p.iter().find(|p| p["name"] == "laravel/framework"))
        .map(|p| p["version"].clone())
        .unwrap_or(composer["require"]["laravel/framework"].clone());
    let env = [".env", ".env.example"].iter().find_map(|f| fs::read_to_string(app.join(f)).ok()).unwrap_or_default();
    let db = Regex::new(r"(?m)^DB_CONNECTION=(\S+)").unwrap().captures(&env).map(|c| c[1].to_string());
    let has = |p: &str| composer["require"].get(p).is_some();
    let npm = fs::read_to_string(app.join("package.json")).unwrap_or_default();
    let frontend = if has("livewire/livewire") {
        "livewire"
    } else if has("inertiajs/inertia-laravel") {
        if npm.contains("@inertiajs/react") {
            "inertia-react"
        } else if npm.contains("@inertiajs/vue3") {
            "inertia-vue"
        } else if npm.contains("@inertiajs/svelte") {
            "inertia-svelte"
        } else {
            "inertia"
        }
    } else {
        "blade"
    };
    json!({ "path": app, "laravel": laravel, "php": composer["require"]["php"], "db": db, "frontend": frontend })
}

fn models(app: &Path) -> Vec<Value> {
    let class = Regex::new(r"class\s+(\w+)\s+extends\s+(Model|Authenticatable|Pivot|MorphPivot|User)\b").unwrap();
    let table = Regex::new(r#"\$table\s*=\s*['"](\w+)['"]"#).unwrap();
    let relation = Regex::new(
        r"function\s+(\w+)\s*\([^)]*\)[^{]*\{\s*return\s+\$this->(belongsTo|hasMany|hasOne|belongsToMany|morphTo|morphMany|morphOne|morphToMany|morphedByMany|hasManyThrough|hasOneThrough)\(\s*([\w\\]+)?(?:::class)?\s*(?:,\s*['\x22](\w+)['\x22])?",
    )
    .unwrap();
    let cast = Regex::new(r#"['"](\w+)['"]\s*=>\s*(?:['"]([\w:\\,]+)['"]|([\w\\]+)::class)"#).unwrap();

    php_files(app, "app")
        .filter_map(|(rel, src)| {
            let c = class.captures(&src)?;
            let casts_block = block_after(&src, "$casts").or_else(|| block_after(&src, "function casts()")).unwrap_or_default();
            let casts: serde_json::Map<String, Value> = cast
                .captures_iter(&casts_block)
                .map(|c| (c[1].to_string(), json!(c.get(2).or(c.get(3)).unwrap().as_str())))
                .collect();
            let relations: Vec<Value> = relation
                .captures_iter(&src)
                .map(|r| {
                    let mut rel = json!({ "name": &r[1], "type": &r[2], "related": r.get(3).map(|m| short(m.as_str())) });
                    if let Some(fk) = r.get(4) {
                        rel["foreign_key"] = json!(fk.as_str());
                    }
                    rel
                })
                .collect();
            Some(json!({
                "id": format!("model:{}", &c[1]),
                "file": rel,
                "table": table.captures(&src).map(|t| t[1].to_string()),
                "casts": casts,
                "relations": relations,
            }))
        })
        .collect()
}

fn requests(app: &Path) -> Vec<Value> {
    let form_request = Regex::new(r"class\s+(\w+)\s+extends\s+FormRequest").unwrap();
    let dynamic = Regex::new(r"(?:->|::)validate\(\s*\$\w+\s*,\s*[^\[\s]").unwrap();
    let mut out = Vec::new();
    for (rel, src) in php_files(app, "app") {
        if let Some(c) = form_request.captures(&src) {
            let authorize = block_after(&src, "function authorize").map(|b| {
                if b.contains("return true") { "true" } else if b.contains("can(") || b.contains("Gate::") { "policy" } else { "custom" }
            });
            out.push(json!({
                "id": format!("request:{}", &c[1]),
                "file": rel,
                "rules": rules(&block_after(&src, "function rules").unwrap_or_default()),
                "authorize": authorize,
            }));
        } else {
            for (i, _) in dynamic.find_iter(&src).enumerate() {
                out.push(json!({ "id": format!("request:{rel}#dyn{}", i + 1), "file": rel, "rules": null, "authorize": null }));
            }
            for (i, block) in blocks_after(&src, "validate(").into_iter().enumerate() {
                let rules = rules(&block);
                if !rules.as_object().is_some_and(|r| r.is_empty()) {
                    out.push(json!({ "id": format!("request:{rel}#{}", i + 1), "file": rel, "rules": rules, "authorize": null }));
                }
            }
        }
    }
    out
}

/// `'field' => 'a|b:c'` or `'field' => ['a', 'b:c', Rule::unique(..)]` → { field: [rule names] }.
fn rules(block: &str) -> Value {
    let pair = Regex::new(r#"['"]([\w.*]+)['"]\s*=>\s*(\[|['"])"#).unwrap();
    let mut out = serde_json::Map::new();
    for c in pair.captures_iter(block) {
        let start = c.get(2).unwrap().start();
        let rest = &block[start..];
        let raw = if &c[2] == "[" {
            balanced(rest, '[', ']').unwrap_or_default()
        } else {
            let q = rest.chars().next().unwrap();
            format!("'{}'", rest[1..].split(q).next().unwrap_or(""))
        };
        out.insert(c[1].to_string(), json!(rule_names(&raw)));
    }
    Value::Object(out)
}

fn rule_names(raw: &str) -> Vec<String> {
    let token = Regex::new(r#"['"]([^'"]+)['"]|(Rule::\w+|Password::\w+|new\s+\w+|[A-Z]\w*::\w+)"#).unwrap();
    let chain = Regex::new(r"->\w+").unwrap();
    let raw = chain.replace_all(&strip_parens(raw), "").into_owned();
    let mut names = Vec::new();
    for c in token.captures_iter(&raw) {
        if let Some(s) = c.get(1) {
            names.extend(s.as_str().split('|').filter(|r| !r.is_empty()).map(|r| r.trim().to_string()));
        } else {
            names.push(c[2].split_whitespace().collect::<Vec<_>>().join(" "));
        }
    }
    names
}

fn views(app: &Path) -> Vec<Value> {
    let directive = Regex::new(r"(?:^|[^\w@])@([a-zA-Z]+)").unwrap();
    let comment = Regex::new(r"(?s)\{\{--.*?--\}\}|<style\b.*?</style>|<script\b.*?</script>").unwrap();
    let component = Regex::new(r"<(x-[\w.\-:]+|livewire:[\w.\-]+)").unwrap();
    let root = app.join("resources/views");
    WalkDir::new(&root)
        .into_iter()
        .flatten()
        .filter(|e| e.file_name().to_string_lossy().ends_with(".blade.php"))
        .filter_map(|e| {
            let src = comment.replace_all(&fs::read_to_string(e.path()).ok()?, "").into_owned();
            let rel = e.path().strip_prefix(&root).ok()?.to_string_lossy().replace(".blade.php", "").replace('/', ".");
            let directives: BTreeSet<_> = directive.captures_iter(&src).map(|c| format!("@{}", &c[1])).collect();
            let components: BTreeSet<_> = component.captures_iter(&src).map(|c| c[1].to_string()).collect();
            Some(json!({
                "id": format!("view:{rel}"),
                "file": e.path().strip_prefix(app).ok()?,
                "directives": directives,
                "components": components,
                "raw_echo": src.contains("{!!"),
            }))
        })
        .collect()
}

fn classes(app: &Path, dir: &str, kind: &str) -> Vec<Value> {
    let class = Regex::new(r"(?m)^\s*(?:final\s+|abstract\s+)?class\s+(\w+)").unwrap();
    php_files(app, dir)
        .filter_map(|(rel, src)| class.captures(&src).map(|c| json!({ "id": format!("{kind}:{}", &c[1]), "file": rel })))
        .collect()
}

/// Jobs, mail, notifications, events, listeners, observers and commands anywhere under `app/`,
/// told apart by what they extend or implement, so apps laid out by feature (BookStack's
/// `app/Activity/`) aren't missed. Parents defined in the app are followed (`extends MailNotification`).
fn background(app: &Path) -> std::collections::HashMap<&'static str, Vec<Value>> {
    let class = Regex::new(r"(?m)^\s*(final\s+|abstract\s+)?class\s+(\w+)(?:\s+extends\s+([\w\\]+))?(?:\s+implements\s+([\w\\,\s]+?))?\s*\{").unwrap();
    let files: Vec<(String, String)> = php_files(app, "app").collect();
    let via_list = Regex::new(r"function\s+via\([^)]*\)[^{]*\{[^}]*?return\s*\[([^\]]*)\]").unwrap();
    let mut parent = std::collections::HashMap::new();
    let mut via: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
    for (_, src) in &files {
        if let Some(c) = class.captures(src) {
            if let Some(v) = via_list.captures(src) {
                via.insert(c[2].to_string(), v[1].split(',').map(|x| x.trim().trim_matches(['\'', '"']).to_string()).filter(|x| !x.is_empty()).collect());
            }
            if let Some(p) = c.get(3) {
                parent.insert(c[2].to_string(), p.as_str().rsplit('\\').next().unwrap_or("").to_string());
            }
        }
    }
    let extends = |name: &str, base: &str| {
        let mut n = name.to_string();
        for _ in 0..10 {
            match parent.get(&n) {
                Some(p) if p == base => return true,
                Some(p) => n = p.clone(),
                None => return false,
            }
        }
        false
    };
    let mut out: std::collections::HashMap<&'static str, Vec<Value>> = std::collections::HashMap::new();
    for (rel, src) in &files {
        let Some(c) = class.captures(src) else { continue };
        if c.get(1).is_some_and(|m| m.as_str().trim() == "abstract") {
            continue; // ponytail: base classes aren't work items; their concrete children are
        }
        let name = &c[2];
        let implements = c.get(4).map_or("", |m| m.as_str());
        let queued = implements.contains("ShouldQueue");
        let kind = if extends(name, "Mailable") {
            "mail"
        } else if extends(name, "Notification") {
            "notification"
        } else if extends(name, "Command") {
            "command"
        } else if name.ends_with("Observer") || rel.contains("/Observers/") {
            "observer"
        } else if rel.contains("/Listeners/") {
            "listener"
        } else if rel.contains("/Events/") || src.contains("Illuminate\\Foundation\\Events\\Dispatchable") {
            "event"
        } else if rel.contains("/Jobs/") || (queued && src.contains("function handle(")) {
            "job"
        } else {
            continue;
        };
        let mut item = json!({ "id": format!("{kind}:{name}"), "file": rel });
        if queued {
            item["queued"] = json!(true);
        }
        // `via()` returning ['mail', 'database'], here or in a parent: the channels decide what has a Rust mapping.
        if kind == "notification" {
            let mut n = name.to_string();
            for _ in 0..10 {
                if let Some(ch) = via.get(&n) {
                    item["channels"] = json!(ch);
                    break;
                }
                match parent.get(&n) {
                    Some(p) => n = p.clone(),
                    None => break,
                }
            }
        }
        out.entry(kind).or_default().push(item);
    }
    out
}

fn schedule(app: &Path) -> Vec<Value> {
    let entry = Regex::new(r"(?:Schedule::|\$schedule->)(command|job|call|exec)\(([^;]*)").unwrap();
    ["routes/console.php", "app/Console/Kernel.php", "bootstrap/app.php"]
        .iter()
        .filter_map(|f| Some((f, fs::read_to_string(app.join(f)).ok()?)))
        .flat_map(|(f, src)| {
            entry
                .captures_iter(&src)
                .enumerate()
                .map(|(i, c)| json!({ "id": format!("schedule:{f}#{}", i + 1), "kind": &c[1], "expr": c[2].trim() }))
                .collect::<Vec<_>>()
        })
        .collect()
}

fn packages(app: &Path) -> Vec<Value> {
    let composer = read_json(&app.join("composer.json"));
    let mut out = Vec::new();
    for (section, dev) in [("require", false), ("require-dev", true)] {
        if let Some(map) = composer[section].as_object() {
            for (name, version) in map {
                if name == "php" || name.starts_with("ext-") {
                    continue;
                }
                out.push(json!({ "id": format!("pkg:{name}"), "name": name, "version": version, "dev": dev }));
            }
        }
    }
    out
}

fn data_risks(app: &Path) -> Vec<Value> {
    let serialized = Regex::new(r"(Crypt::encrypt|\bencrypt)\(([^;]*)").unwrap();
    let encrypted_cast = Regex::new(r#"['"](\w+)['"]\s*=>\s*['"](encrypted(?::\w+)?)['"]"#).unwrap();
    let mut out = Vec::new();
    for (rel, src) in php_files(app, "app") {
        for c in serialized.captures_iter(&src) {
            if !c[2].contains("false") {
                out.push(json!({ "id": format!("risk:serialized-encrypt:{rel}"), "kind": "serialized-encrypt", "file": rel }));
                break;
            }
        }
        for c in encrypted_cast.captures_iter(&src) {
            out.push(json!({ "id": format!("risk:encrypted-cast:{rel}:{}", &c[1]), "kind": "encrypted-cast", "cast": &c[2], "file": rel }));
        }
        if src.contains("HasApiTokens") {
            out.push(json!({ "id": format!("risk:sanctum-tokens:{rel}"), "kind": "sanctum-tokens", "file": rel }));
        }
    }
    out
}

fn tests(app: &Path) -> Vec<Value> {
    php_files(app, "tests")
        .filter(|(rel, _)| rel.ends_with("Test.php"))
        .map(|(rel, src)| {
            let framework = if src.contains("extends TestCase") || src.contains("extends \\Tests\\TestCase") { "phpunit" } else { "pest" };
            json!({ "id": format!("test:{rel}"), "file": rel, "framework": framework })
        })
        .collect()
}

// --- helpers ---

fn php_files(app: &Path, dir: &str) -> impl Iterator<Item = (String, String)> {
    let app = app.to_path_buf();
    WalkDir::new(app.join(dir))
        .into_iter()
        .flatten()
        .filter(|e| e.file_type().is_file() && e.path().extension().is_some_and(|x| x == "php"))
        .filter_map(move |e| {
            let src = fs::read_to_string(e.path()).ok()?;
            Some((e.path().strip_prefix(&app).ok()?.to_string_lossy().into_owned(), src))
        })
}

fn read_json(path: &Path) -> Value {
    fs::read_to_string(path).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(Value::Null)
}

fn short(class: &str) -> String {
    class.rsplit('\\').next().unwrap_or(class).to_string()
}

/// Text of the first `[...]` or `{...}` after `marker`.
fn block_after(src: &str, marker: &str) -> Option<String> {
    let rest = &src[src.find(marker)? + marker.len()..];
    let i = rest.find(['[', '{'])?;
    let open = rest[i..].chars().next()?;
    balanced(&rest[i..], open, if open == '[' { ']' } else { '}' })
}

/// Every `[...]` that directly follows `marker`, e.g. `validate([...])`.
fn blocks_after(src: &str, marker: &str) -> Vec<String> {
    src.match_indices(marker)
        .filter_map(|(i, _)| {
            let rest = &src[i + marker.len()..];
            let open = rest.find('[')?;
            (!rest[..open].contains([';', ')'])).then(|| balanced(&rest[open..], '[', ']')).flatten()
        })
        .collect()
}

/// Removes every `(...)` group outside quotes, e.g. `Rule::unique('users')` → `Rule::unique`.
fn strip_parens(s: &str) -> String {
    let (mut out, mut depth, mut quote) = (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,
            _ => {}
        }
        if depth == 0 && ch != ')' {
            out.push(ch);
        }
    }
    out
}

// ponytail: ignores brackets inside strings; fine for rule arrays, upgrade to a PHP parser if corpus apps break it.
pub(crate) fn balanced(s: &str, open: char, close: char) -> Option<String> {
    let mut depth = 0;
    for (i, ch) in s.char_indices() {
        if ch == open {
            depth += 1;
        } else if ch == close {
            depth -= 1;
            if depth == 0 {
                return Some(s[..=i].to_string());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_pipe_and_array_rules() {
        let r = rules(r#"['message' => 'required|string|max:255', 'tags' => ['array', Rule::in(['a', 'b']), new Uppercase]]"#);
        let r2 = rules(r#"['org' => ['nullable', Rule::exists('orgs', 'id')->where(fn ($q) => $q->where('account_id', Auth::user()->account_id))]]"#);
        assert_eq!(r2["org"], json!(["nullable", "Rule::exists"]));
        let found = blocks_after("$this->validate($request, ['name' => 'required']);", "validate(");
        assert_eq!(found.len(), 1);
        assert_eq!(r["message"], json!(["required", "string", "max:255"]));
        assert_eq!(r["tags"], json!(["array", "Rule::in", "new Uppercase"]));
    }

    #[test]
    fn finds_background_classes_outside_their_usual_folders() {
        let dir = std::env::temp_dir().join(format!("larakiln-bg-{}", std::process::id()));
        let files = [
            ("app/App/MailNotification.php", "abstract class MailNotification extends Notification implements ShouldQueue {}"),
            ("app/Activity/PageCreated.php", "class PageCreated extends MailNotification\n{\n    public function via(): array\n    {\n        return ['mail', 'database'];\n    }\n}"),
            ("app/Activity/DispatchWebhookJob.php", "class DispatchWebhookJob implements ShouldQueue\n{\n    public function handle(): void {}\n}"),
            ("app/Observers/ChirpObserver.php", "class ChirpObserver\n{\n}"),
            ("app/Models/Chirp.php", "class Chirp extends Model {}"),
        ];
        for (f, src) in files {
            fs::create_dir_all(dir.join(f).parent().unwrap()).unwrap();
            fs::write(dir.join(f), format!("<?php\n{src}\n")).unwrap();
        }
        let bg = background(&dir);
        fs::remove_dir_all(&dir).ok();
        let ids = |k: &str| bg.get(k).into_iter().flatten().map(|i| i["id"].as_str().unwrap().to_string()).collect::<Vec<_>>();
        assert_eq!(ids("notification"), ["notification:PageCreated"]);
        assert_eq!(bg["notification"][0]["channels"], json!(["mail", "database"]));
        assert_eq!(ids("job"), ["job:DispatchWebhookJob"]);
        assert_eq!(ids("observer"), ["observer:ChirpObserver"]);
        assert_eq!(bg.len(), 3, "models and abstract bases aren't background work");
    }
}