Skip to main content

larust_convert/
config.rs

1//! `config/*.php` → `config/app.rs` (the framework's own typed bootstrap
2//! fields) plus `config/{file}.rs` (everything else). Laravel's config
3//! system takes an arbitrary set of dotted keys across many files;
4//! Larust's `Config` (`crates/larust-core/src/config.rs`) is a **small,
5//! fixed, known struct** - only [`MAPPINGS`]'s keys can become a typed
6//! `Config` field, so [`convert`] (the narrower of this module's two
7//! converters) really does have to name a key "no known Config field"
8//! and leave it out of that struct.
9//!
10//! Every *other* generated `config/*.rs` module ([`render_body`]/
11//! [`convert_body`]) has no such constraint - it's an open
12//! `serde_json::Value` map, so there's no fixed list of "supported" value
13//! shapes to reject against either. Every top-level key [`MAPPINGS`]
14//! doesn't already claim gets written, regardless of whether this phase
15//! has a specific translation for its PHP value: a literal (string/bool/
16//! int/float/null), an `env(...)` call, a nested array, or anything else
17//! (a Laravel path helper like `storage_path(...)`, a `::class`
18//! reference, an expression combining several `env()` calls, ...) -
19//! [`render_config_value`] falls back to embedding that last category's
20//! own raw PHP source text as a plain string ([`render_raw_fallback`]),
21//! flagged for manual review, rather than silently dropping the key. A
22//! generator that maintains its own allowlist of "known-good" value
23//! shapes can never keep up with the unbounded set of PHP expressions a
24//! real Laravel config file might contain - "convert what exists, flag
25//! what wasn't fully understood" is the only approach that scales.
26//!
27//! Only flat, top-level `'key' => value` pairs are read at the outermost
28//! level - a nested array is walked one additional level
29//! ([`render_config_array`]) rather than to arbitrary depth, a
30//! documented Phase 1 limitation.
31//!
32//! [`convert_body`]/[`render_body`] is the second, independent config-file
33//! converter this module holds - Laravel's own file-as-namespace
34//! convention (`config('routes.web')` means "the `web` key of
35//! `config/routes.php`'s own returned array") ported directly, rather
36//! than flattened into more `Config`-struct fields: for every key
37//! [`convert`]'s fixed [`MAPPINGS`] table doesn't already claim, this
38//! generates one `config/{file}.rs` module per Laravel config file, each
39//! exposing `pub fn config() -> serde_json::Value` that rebuilds the
40//! *same* array shape (including nesting) the PHP file returns, with a
41//! Laravel `env('VAR', default)` call translated to a real runtime
42//! `larust_support::config_env::env*` call (not baked in at convert
43//! time) so the same "default, overridable by an env var" behavior
44//! survives the port. See `docs/ARCHITECTURE.md` or this crate's own
45//! history for the fuller design rationale - the short version: a bare
46//! baked-in literal would silently drop every such key's env-override
47//! capability, and a flat `ROUTES_WEB`-style constant would throw away
48//! Laravel's own file-scoped key namespacing (different config files
49//! legitimately reusing a key name like `web`).
50
51use crate::php;
52use anyhow::Result;
53use tree_sitter::Node;
54
55/// One Laravel dotted key this phase knows how to reach, and the
56/// `Config` field it maps to. The TOML value's own kind (string vs. bool)
57/// comes from the *syntax* of the matched PHP expression (a `string` node
58/// vs. a `boolean` node - see [`render_value`]), not from this table; a
59/// field name here is purely a lookup key, not a type declaration.
60struct Mapping {
61    laravel_key: &'static str,
62    larust_field: &'static str,
63}
64
65const MAPPINGS: &[Mapping] = &[
66    Mapping {
67        laravel_key: "app.name",
68        larust_field: "app_name",
69    },
70    Mapping {
71        laravel_key: "app.env",
72        larust_field: "app_env",
73    },
74    Mapping {
75        laravel_key: "app.debug",
76        larust_field: "app_debug",
77    },
78    Mapping {
79        laravel_key: "app.url",
80        larust_field: "app_url",
81    },
82    Mapping {
83        laravel_key: "mail.default",
84        larust_field: "mail_driver",
85    },
86    Mapping {
87        laravel_key: "session.secure",
88        larust_field: "session_secure_cookie",
89    },
90];
91
92pub struct FoundField {
93    pub larust_field: &'static str,
94    pub toml_value: String,
95}
96
97pub struct ConfigConversion {
98    pub found: Vec<FoundField>,
99    /// Human-readable notes for keys this phase couldn't map - either
100    /// because the key has no known `Config` field, or because its value
101    /// is a nested array this phase doesn't traverse.
102    pub unmapped: Vec<String>,
103}
104
105/// `file_stem` is the config file's name without extension (`"app"` for
106/// `config/app.php`) - combined with each top-level array key to build
107/// the Laravel dotted key (`"app.name"`) looked up against [`MAPPINGS`].
108pub fn convert(file_stem: &str, source: &str) -> Result<ConfigConversion> {
109    let tree = php::parse(source)?;
110    let mut found = Vec::new();
111    let mut unmapped = Vec::new();
112
113    for (key, value_node) in top_level_entries(&tree, source) {
114        let dotted = format!("{file_stem}.{key}");
115        let bytes = source.as_bytes();
116
117        if value_node.kind() == "array_creation_expression" {
118            unmapped.push(format!(
119                "config/{file_stem}.php: {key} - nested array config, not supported in this phase"
120            ));
121            continue;
122        }
123
124        let Some(mapping) = MAPPINGS.iter().find(|m| m.laravel_key == dotted) else {
125            unmapped.push(format!(
126                "config/{file_stem}.php: {key} - not a known Config field, not written to config/app.toml"
127            ));
128            continue;
129        };
130
131        let Some(rendered) = render_value(value_node, bytes) else {
132            unmapped.push(format!(
133                "config/{file_stem}.php: {key} - value shape not recognized"
134            ));
135            continue;
136        };
137
138        found.push(FoundField {
139            larust_field: mapping.larust_field,
140            toml_value: rendered,
141        });
142    }
143
144    Ok(ConfigConversion { found, unmapped })
145}
146
147/// The `return [ 'key' => value, ... ];` array's direct entries - a
148/// [`php::query_nodes`] match on every `array_element_initializer`
149/// directly inside the top-level `array_creation_expression`. `pub(crate)` -
150/// also used by `routes.rs` to resolve a route path built from
151/// `config('some.key')`, the same flat-array shape this phase already
152/// reads for the `Config` struct mapping above.
153pub(crate) fn top_level_entries<'a>(
154    tree: &'a tree_sitter::Tree,
155    source: &str,
156) -> Vec<(String, tree_sitter::Node<'a>)> {
157    // Deliberately doesn't try to bind the key/value inside the query
158    // itself (e.g. `(array_element_initializer (string) @key)`) - both an
159    // entry's key AND a plain string value (`'timezone' => 'UTC'`) match
160    // `(string)`, so an unanchored inner pattern matches twice per entry.
161    // `named_child(0)`/`named_child(1)` on the whole captured
162    // `array_element_initializer` node is unambiguous.
163    let query = r#"
164        (return_statement
165            (array_creation_expression
166                (array_element_initializer) @entry))
167    "#;
168    let Ok(entries) = php::query_nodes(tree, source, query, "entry") else {
169        return Vec::new();
170    };
171
172    entries
173        .into_iter()
174        .filter_map(|entry| {
175            let key_node = entry.named_child(0)?;
176            let value_node = entry.named_child(1)?;
177            let key = php::unquote(key_node.utf8_text(source.as_bytes()).ok()?);
178            Some((key, value_node))
179        })
180        .collect()
181}
182
183/// Renders `node` (a config value expression) as TOML-compatible text -
184/// unwraps `env('VAR', default)` to `default` (the fallback a fresh
185/// deployment actually gets) and `(bool) env(...)` the same way, since
186/// Larust's config has no environment-driven layer over `config/app.toml`
187/// itself the way `env()` does. Returns `None` for a shape this phase
188/// doesn't recognize (an arbitrary expression, a function call other than
189/// `env`).
190fn render_value(node: tree_sitter::Node, bytes: &[u8]) -> Option<String> {
191    match node.kind() {
192        "string" => {
193            let text = php::unquote(node.utf8_text(bytes).ok()?);
194            Some(format!("{:?}", text)) // Rust's Debug-format for &str is valid TOML string escaping for the plain cases this phase handles
195        }
196        "boolean" => Some(node.utf8_text(bytes).ok()?.to_string()),
197        "cast_expression" => {
198            let value = node.child_by_field_name("value")?;
199            render_value(value, bytes)
200        }
201        "function_call_expression" => {
202            let name = node
203                .child_by_field_name("function")?
204                .utf8_text(bytes)
205                .ok()?;
206            if name != "env" {
207                return None;
208            }
209            let default_arg = php::argument_node(node, 1)?;
210            render_value(default_arg, bytes)
211        }
212        _ => None,
213    }
214}
215
216/// One generated `config/{file_stem}.rs` module - `code` is the full
217/// file content, `resolved_keys` names every top-level `"{file}.{key}"`
218/// pair it successfully resolved (for `blade::expr::translate`'s own
219/// `"config"` arm to check membership against - nested keys translate
220/// through the same recursive value-walk but aren't individually named
221/// here, since real Blade `config(...)` calls only ever reference a
222/// file+top-level-key pair, never reach deeper). `skipped` names a
223/// top-level key this phase couldn't read as valid PHP at all (rare -
224/// see [`render_config_value`]'s own doc comment for why almost nothing
225/// else lands here anymore); `verify` names a key that *was* written but
226/// via [`render_raw_fallback`] rather than a real typed translation -
227/// both fold into `CONVERSION_REPORT.md`'s manual-review section, under
228/// separate headings, so a reader can tell "missing" apart from
229/// "present but unverified."
230pub struct GeneratedConfigFile {
231    pub code: String,
232    pub resolved_keys: Vec<String>,
233    pub skipped: Vec<String>,
234    pub verify: Vec<String>,
235}
236
237/// One generated config module's *body* - the per-key `config["key"] =
238/// <expr>;` assignment lines (already indented, ready to `.join("\n\n")`
239/// and splice into a `pub fn config() -> Value { ... }` wrapper), plus the
240/// same `resolved_keys`/`skipped` bookkeeping [`GeneratedConfigFile`]
241/// carries. Kept separate from the fully-wrapped [`GeneratedConfigFile`]
242/// so a caller that needs to *merge* several files' worth of keys into one
243/// shared module - `xr convert`'s own `config/app.rs`, built from
244/// `MAPPINGS`-claimed fields found across every `config/*.php` file plus
245/// `app.php`'s own unmapped keys - can reuse this same per-key rendering
246/// without also getting a second, independent `pub fn config()` wrapper it
247/// would have to discard. [`convert_body`] is the thin, single-file
248/// wrapper around this for the common case (a config file with its own
249/// standalone module).
250pub struct GeneratedConfigBody {
251    pub assignments: Vec<String>,
252    pub resolved_keys: Vec<String>,
253    pub skipped: Vec<String>,
254    pub verify: Vec<String>,
255}
256
257/// Renders `file_stem`'s per-key assignment lines - every top-level key
258/// [`convert`]'s `MAPPINGS` table doesn't already claim. Returns `None`
259/// when the file doesn't parse, or its top-level `return` isn't a plain
260/// array at all (a structural rejection - see [`has_top_level_array_return`]).
261/// Unlike [`convert_body`], `Some` here can still carry zero `assignments`
262/// (every key `MAPPINGS`-claimed or unsupported) - the caller decides
263/// whether an empty body is meaningful (`convert_body` treats it as
264/// nothing-to-generate; the `config/app.rs` merge case still wants the
265/// resolved/skipped bookkeeping even when a given file contributed no
266/// lines of its own).
267pub fn render_body(file_stem: &str, source: &str) -> Option<GeneratedConfigBody> {
268    let tree = php::parse(source).ok()?;
269    if php::has_syntax_error(&tree) || !has_top_level_array_return(&tree, source) {
270        return None;
271    }
272
273    let bytes = source.as_bytes();
274    let mut assignments = Vec::new();
275    let mut resolved_keys = Vec::new();
276    let mut skipped = Vec::new();
277    let mut verify = Vec::new();
278
279    for (key, value_node) in top_level_entries(&tree, source) {
280        let dotted = format!("{file_stem}.{key}");
281        if MAPPINGS.iter().any(|m| m.laravel_key == dotted) {
282            // Already has a real `Config`-struct-backed home via
283            // `convert`'s own `MAPPINGS`-driven fields - not duplicated
284            // here.
285            continue;
286        }
287        // `render_config_value` only returns `None` when the node's own
288        // source text can't even be read (not a real-world case for
289        // anything that made it this far through the parser) - every
290        // other shape, understood or not, produces something.
291        let Some((rendered, needs_review)) = render_config_value(value_node, bytes) else {
292            skipped.push(format!(
293                "config/{file_stem}.php: {key} - could not be read as valid PHP, \
294                 left for manual review"
295            ));
296            continue;
297        };
298        assignments.push(format!("    config[{key:?}] = {rendered};"));
299        resolved_keys.push(dotted.clone());
300        if needs_review {
301            verify.push(format!(
302                "config/{file_stem}.php: {key} - converted verbatim from its raw PHP \
303                 source (no typed translation for this expression shape); verify by hand"
304            ));
305        }
306    }
307
308    Some(GeneratedConfigBody {
309        assignments,
310        resolved_keys,
311        skipped,
312        verify,
313    })
314}
315
316/// The second half of Laravel's config translation (see this module's own
317/// doc comment) - generates `config/{file_stem}.rs`'s full content via
318/// [`render_body`]. Returns `None` when there's nothing to generate: the
319/// file doesn't parse (see [`render_body`]), or every key was either
320/// already `MAPPINGS`-claimed or failed to translate (an empty generated
321/// file is pointless, and nothing should `pub mod` it).
322pub fn convert_body(file_stem: &str, source: &str) -> Option<GeneratedConfigFile> {
323    let body = render_body(file_stem, source)?;
324    if body.assignments.is_empty() {
325        return None;
326    }
327
328    // `larust_support::serde_json`, not a bare `serde_json` - a generated
329    // app depends only on `larust_support` directly (see that crate's own
330    // `pub use serde_json;` re-export doc comment), the same "one
331    // dependency surface" convention every other macro-generated code
332    // path in this framework follows.
333    let code = format!(
334        "use larust_support::serde_json::{{json, Value}};\n\npub fn config() -> Value {{\n    let mut config = json!({{}});\n\n{}\n\n    config\n}}\n",
335        body.assignments.join("\n\n")
336    );
337
338    Some(GeneratedConfigFile {
339        code,
340        resolved_keys: body.resolved_keys,
341        skipped: body.skipped,
342        verify: body.verify,
343    })
344}
345
346/// Whether `tree`'s top-level `return` statement is a plain PHP array
347/// literal - every real Laravel config file's own shape. Distinct from
348/// [`top_level_entries`] returning an empty `Vec`, which is ambiguous
349/// between "genuinely empty array" and "no such return at all"; this
350/// checks the array node itself exists, regardless of how many entries
351/// (if any) it has.
352fn has_top_level_array_return(tree: &tree_sitter::Tree, source: &str) -> bool {
353    let query = r#"
354        (return_statement
355            (array_creation_expression) @arr)
356    "#;
357    php::query_nodes(tree, source, query, "arr")
358        .map(|nodes| !nodes.is_empty())
359        .unwrap_or(false)
360}
361
362/// Renders one top-level config value as a Rust expression suitable for
363/// `config["key"] = {rendered};` - always a `serde_json::Value`-producing
364/// expression (a `json!(...)` call, or a recursive nested one for an
365/// array) paired with whether it's a genuine, typed translation (`false`)
366/// or a last-resort raw-source embed (`true`, see [`render_raw_fallback`])
367/// that the caller should flag for manual review. Unlike [`render_value`]
368/// (this module's other, TOML-oriented renderer, used only for
369/// [`MAPPINGS`]'s closed set of typed `Config` fields), this recurses into
370/// nested arrays, keeps `env(...)`'s variable name and default intact as
371/// a genuine runtime call rather than collapsing straight to the default
372/// (see [`render_env_call`]), and - the key difference - practically
373/// never returns `None`: every PHP value shape this phase doesn't have a
374/// specific translation for still gets *something* written, because this
375/// module's own doc comment's whole point is that an open
376/// `serde_json::Value` map has no shape it needs to reject.
377fn render_config_value(node: Node, bytes: &[u8]) -> Option<(String, bool)> {
378    match node.kind() {
379        "string" => {
380            let text = php::unquote(node.utf8_text(bytes).ok()?);
381            Some((format!("json!({text:?})"), false))
382        }
383        "boolean" | "integer" | "float" => {
384            Some((format!("json!({})", node.utf8_text(bytes).ok()?), false))
385        }
386        "null" => Some(("json!(null)".to_string(), false)),
387        // `(int) env(...)` and friends - real source:
388        // `config/responsecache.php`'s `(int) env('RESPONSE_CACHE_LIFETIME', ...)`.
389        // Unwrap the cast and translate the underlying value; the cast
390        // itself carries no information a `serde_json::Value` needs to
391        // preserve (JSON numbers aren't int-vs-float-tagged the way PHP
392        // casts are).
393        "cast_expression" => {
394            let value = node.child_by_field_name("value")?;
395            render_config_value(value, bytes)
396        }
397        "array_creation_expression" => render_config_array(node, bytes),
398        "function_call_expression" => {
399            let is_env = node
400                .child_by_field_name("function")
401                .and_then(|f| f.utf8_text(bytes).ok())
402                .is_some_and(|name| name == "env");
403            if is_env {
404                if let Some(rendered) = render_env_call(node, bytes) {
405                    return Some((rendered, false));
406                }
407                // A real `env(...)` call this phase still can't fully
408                // read (e.g. a computed key expression) - falls through
409                // to the raw-source embed below rather than being
410                // dropped, same as any other unrecognized shape.
411            }
412            render_raw_fallback(node, bytes)
413        }
414        // Anything else - a `::class` reference, a Laravel path helper
415        // like `storage_path(...)`, a boolean/comparison expression
416        // combining multiple `env()` calls, string concatenation, ... -
417        // gets embedded as its own raw PHP source text rather than
418        // dropped. See [`render_raw_fallback`].
419        _ => render_raw_fallback(node, bytes),
420    }
421}
422
423/// Last-resort translation for a config value shape this phase has no
424/// specific, typed understanding of. `Config` (the framework's own
425/// bootstrap struct, see this module's own doc comment) is closed and
426/// typed, so an unrecognized shape really does have to be rejected there -
427/// but every *other* generated config module is an open
428/// `serde_json::Value` map with no such constraint, so "the shape isn't
429/// understood" is never a reason to drop a key outright. The literal PHP
430/// source text is preserved as a plain JSON string instead, so nothing
431/// silently vanishes from the generated config; the caller uses the
432/// `true` half of this function's `(String, bool)` return to flag the
433/// key for manual review rather than presenting it as a faithful
434/// translation it isn't.
435fn render_raw_fallback(node: Node, bytes: &[u8]) -> Option<(String, bool)> {
436    let text = node.utf8_text(bytes).ok()?;
437    Some((format!("json!({text:?})"), true))
438}
439
440/// A nested PHP array literal → a nested `json!({ "key": value, ... })`
441/// object. Only keyed entries with a string-literal key translate - a
442/// keyless sequential entry or a computed/non-string key (Laravel's real
443/// `config/filesystems.php`'s `public_path('storage') => storage_path(...)`)
444/// is silently omitted from the generated object rather than failing the
445/// whole array, the same per-item, not whole-file, granularity
446/// [`convert_body`]'s own top-level loop uses. `needs_review` is the
447/// logical OR of every field's own - one raw-fallback value anywhere in
448/// the array is enough to flag the whole array's key for manual review
449/// (see [`render_config_value`]); tracking it any more precisely than
450/// that isn't worth the bookkeeping for how deep real config nesting
451/// actually goes in practice.
452fn render_config_array(node: Node, bytes: &[u8]) -> Option<(String, bool)> {
453    let mut fields = Vec::new();
454    let mut needs_review = false;
455    for i in 0..node.named_child_count() {
456        let Some(element) = node.named_child(i) else {
457            continue;
458        };
459        if element.kind() != "array_element_initializer" || element.named_child_count() < 2 {
460            continue;
461        }
462        let Some(key_node) = element.named_child(0) else {
463            continue;
464        };
465        let Some(value_node) = element.named_child(1) else {
466            continue;
467        };
468        if key_node.kind() != "string" {
469            continue;
470        }
471        let Ok(key_text) = key_node.utf8_text(bytes) else {
472            continue;
473        };
474        let key = php::unquote(key_text);
475        let Some((rendered, field_needs_review)) = render_config_value(value_node, bytes) else {
476            continue;
477        };
478        needs_review = needs_review || field_needs_review;
479        fields.push(format!("{key:?}: {rendered}"));
480    }
481    Some((format!("json!({{ {} }})", fields.join(", ")), needs_review))
482}
483
484/// `env('VAR')` / `env('VAR', default)` → a runtime
485/// `larust_support::config_env::env*` call - the one function call this
486/// phase translates as a *runtime* reference rather than resolving at
487/// convert time, since the whole point of a Laravel config value wrapped
488/// in `env(...)` is that it stays overridable by a real environment
489/// variable after the app is built. String, boolean, and integer
490/// defaults inline directly (`env_or`/`env_bool`, or `env_or` + a parsed
491/// integer fallback); anything else - a computed default like `Str::
492/// slug(...) . '_cache_'` or `60 * 60 * 24 * 7` - can't be baked in
493/// faithfully at convert time, but the env var name and its override
494/// capability still can be, so it falls back to a bare `env(key)` read
495/// rather than being treated as unsupported. Only returns `None` when
496/// this isn't actually an `env(...)` call, or the key argument itself
497/// isn't a plain string literal (real Laravel config files never compute
498/// a key dynamically) - the caller ([`render_config_value`]) treats
499/// either as "fall through to the raw-source embed", not as "drop the
500/// key".
501fn render_env_call(node: Node, bytes: &[u8]) -> Option<String> {
502    let function = node
503        .child_by_field_name("function")?
504        .utf8_text(bytes)
505        .ok()?;
506    if function != "env" {
507        return None;
508    }
509    let key_arg = php::argument_node(node, 0)?;
510    if key_arg.kind() != "string" {
511        return None;
512    }
513    let key = php::unquote(key_arg.utf8_text(bytes).ok()?);
514    match php::argument_node(node, 1) {
515        None => Some(format!("json!(larust_support::config_env::env({key:?}))")),
516        Some(default_arg) => match default_arg.kind() {
517            "boolean" => {
518                let default_text = default_arg.utf8_text(bytes).ok()?;
519                Some(format!(
520                    "json!(larust_support::config_env::env_bool({key:?}, {default_text}))"
521                ))
522            }
523            "string" => {
524                let default_text = php::unquote(default_arg.utf8_text(bytes).ok()?);
525                Some(format!(
526                    "json!(larust_support::config_env::env_or({key:?}, {default_text:?}))"
527                ))
528            }
529            "integer" => {
530                let default_text = default_arg.utf8_text(bytes).ok()?;
531                Some(format!(
532                    "json!(larust_support::config_env::env_or({key:?}, {default_text:?}).parse::<i64>().unwrap_or({default_text}))"
533                ))
534            }
535            // A computed default this phase can't bake in faithfully -
536            // still preserves the env var name and override capability
537            // via a bare `env(key)` read rather than dropping the key.
538            _ => Some(format!("json!(larust_support::config_env::env({key:?}))")),
539        },
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    #[test]
548    fn extracts_known_app_fields() {
549        let source = r#"<?php
550
551return [
552    'name' => env('APP_NAME', 'Laravel'),
553    'env' => env('APP_ENV', 'production'),
554    'debug' => (bool) env('APP_DEBUG', false),
555    'url' => env('APP_URL', 'http://localhost'),
556];
557"#;
558        let result = convert("app", source).unwrap();
559        assert_eq!(result.found.len(), 4);
560        assert!(result
561            .found
562            .iter()
563            .any(|f| f.larust_field == "app_name" && f.toml_value == "\"Laravel\""));
564        assert!(result
565            .found
566            .iter()
567            .any(|f| f.larust_field == "app_debug" && f.toml_value == "false"));
568        assert!(result.unmapped.is_empty());
569    }
570
571    #[test]
572    fn flags_unknown_keys_instead_of_dropping_them() {
573        let source = r#"<?php
574
575return [
576    'timezone' => 'UTC',
577];
578"#;
579        let result = convert("app", source).unwrap();
580        assert!(result.found.is_empty());
581        assert_eq!(result.unmapped.len(), 1);
582        assert!(result.unmapped[0].contains("timezone"));
583        assert!(result.unmapped[0].contains("not written to config/app.toml"));
584    }
585
586    #[test]
587    fn flags_nested_arrays_as_unsupported_rather_than_traversing() {
588        let source = r#"<?php
589
590return [
591    'from' => [
592        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
593        'name' => env('MAIL_FROM_NAME', 'Example'),
594    ],
595];
596"#;
597        let result = convert("mail", source).unwrap();
598        assert!(result.found.is_empty());
599        assert!(result.unmapped[0].contains("nested array"));
600    }
601
602    #[test]
603    fn mail_default_maps_to_mail_driver() {
604        let source = r#"<?php
605
606return [
607    'default' => env('MAIL_MAILER', 'log'),
608];
609"#;
610        let result = convert("mail", source).unwrap();
611        assert_eq!(result.found.len(), 1);
612        assert_eq!(result.found[0].larust_field, "mail_driver");
613        assert_eq!(result.found[0].toml_value, "\"log\"");
614    }
615
616    #[test]
617    fn generates_a_config_module_for_plain_string_literals() {
618        // Real source: `config/routes.php` - no `env()`, no known
619        // `MAPPINGS` key, three plain string values.
620        let source = r#"<?php
621
622return [
623    'web' => 'web-services',
624    'seo' => 'search-engine-optimization',
625    'design' => 'graphic-design',
626];
627"#;
628        let generated = convert_body("routes", source).unwrap();
629        assert!(generated.skipped.is_empty());
630        assert_eq!(
631            generated.resolved_keys,
632            vec!["routes.web", "routes.seo", "routes.design"]
633        );
634        assert!(generated.code.contains("pub fn config() -> Value"));
635        assert!(generated
636            .code
637            .contains(r#"config["web"] = json!("web-services");"#));
638        assert!(generated
639            .code
640            .contains(r#"config["seo"] = json!("search-engine-optimization");"#));
641        assert!(generated
642            .code
643            .contains(r#"config["design"] = json!("graphic-design");"#));
644        // Self-check discipline matching this crate's other translators -
645        // the generated body (already carrying its own `use` line) must
646        // be genuine, valid Rust on its own.
647        assert!(syn::parse_str::<syn::File>(&generated.code).is_ok());
648    }
649
650    #[test]
651    fn generates_a_config_module_only_for_keys_mappings_does_not_already_claim() {
652        // Real source: `config/app.php` - `name`/`env`/`debug`/`url`
653        // already have a `Config`-struct-backed home via `MAPPINGS`;
654        // `apiurl` doesn't, and is the only key that should appear here.
655        let source = r#"<?php
656
657return [
658    'name' => env('APP_NAME', 'Laravel'),
659    'env' => env('APP_ENV', 'production'),
660    'debug' => (bool) env('APP_DEBUG', false),
661    'url' => env('APP_URL', 'http://localhost'),
662    'apiurl' => env('APP_API', 'https://wallabypanel.com/items'),
663];
664"#;
665        let generated = convert_body("app", source).unwrap();
666        assert_eq!(generated.resolved_keys, vec!["app.apiurl"]);
667        assert!(generated.skipped.is_empty());
668        assert!(generated.code.contains(
669            r#"config["apiurl"] = json!(larust_support::config_env::env_or("APP_API", "https://wallabypanel.com/items"));"#
670        ));
671        assert!(!generated.code.contains("\"name\""));
672    }
673
674    #[test]
675    fn a_bare_env_call_with_no_default_becomes_a_runtime_env_read() {
676        let source = r#"<?php
677
678return [
679    'key' => env('AWS_ACCESS_KEY_ID'),
680];
681"#;
682        let generated = convert_body("services", source).unwrap();
683        assert!(generated.code.contains(
684            r#"config["key"] = json!(larust_support::config_env::env("AWS_ACCESS_KEY_ID"));"#
685        ));
686    }
687
688    #[test]
689    fn a_bool_default_env_call_uses_env_bool() {
690        let source = r#"<?php
691
692return [
693    'use_path_style' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
694];
695"#;
696        let generated = convert_body("services", source).unwrap();
697        assert!(generated.code.contains(
698            r#"config["use_path_style"] = json!(larust_support::config_env::env_bool("AWS_USE_PATH_STYLE_ENDPOINT", false));"#
699        ));
700    }
701
702    #[test]
703    fn a_nested_array_recurses_into_a_nested_json_object() {
704        let source = r#"<?php
705
706return [
707    'disks' => [
708        'local' => [
709            'driver' => 'local',
710            'throw' => false,
711        ],
712    ],
713];
714"#;
715        let generated = convert_body("filesystems", source).unwrap();
716        assert_eq!(generated.resolved_keys, vec!["filesystems.disks"]);
717        assert!(generated
718            .code
719            .contains(r#""local": json!({ "driver": json!("local"), "throw": json!(false) })"#));
720    }
721
722    #[test]
723    fn a_key_with_an_unrecognized_value_shape_is_converted_verbatim_not_dropped() {
724        // Real source: `config/filesystems.php`'s `storage_path(...)` -
725        // a Laravel filesystem-path helper with no Larust equivalent.
726        // Still written to the generated file (as its own raw PHP source
727        // text) rather than silently dropped - flagged in `verify`
728        // instead of `skipped`, since the key IS present in the output,
729        // just not via a typed translation.
730        let source = r#"<?php
731
732return [
733    'default' => env('FILESYSTEM_DISK', 'local'),
734    'root' => storage_path('app'),
735];
736"#;
737        let generated = convert_body("filesystems", source).unwrap();
738        assert_eq!(
739            generated.resolved_keys,
740            vec!["filesystems.default", "filesystems.root"]
741        );
742        assert!(generated.skipped.is_empty());
743        assert_eq!(generated.verify.len(), 1);
744        assert!(generated.verify[0].contains("root"));
745        assert!(generated
746            .code
747            .contains(r#"config["root"] = json!("storage_path('app')");"#));
748    }
749
750    #[test]
751    fn an_integer_env_default_parses_at_runtime_instead_of_being_dropped() {
752        // Real source: `config/auth.php`'s `password_timeout`.
753        let source = r#"<?php
754
755return [
756    'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
757];
758"#;
759        let generated = convert_body("auth", source).unwrap();
760        assert!(generated.verify.is_empty());
761        assert!(generated.code.contains(
762            r#"config["password_timeout"] = json!(larust_support::config_env::env_or("AUTH_PASSWORD_TIMEOUT", "10800").parse::<i64>().unwrap_or(10800));"#
763        ));
764    }
765
766    #[test]
767    fn a_null_literal_becomes_json_null() {
768        // Real source: `config/livewire.php`'s `lazy_placeholder`.
769        let source = r#"<?php
770
771return [
772    'lazy_placeholder' => null,
773];
774"#;
775        let generated = convert_body("livewire", source).unwrap();
776        assert!(generated.verify.is_empty());
777        assert!(generated
778            .code
779            .contains(r#"config["lazy_placeholder"] = json!(null);"#));
780    }
781
782    #[test]
783    fn an_env_call_with_a_computed_default_falls_back_to_a_bare_env_read() {
784        // Real source: `config/cache.php`'s `prefix` - the default is a
785        // `Str::slug(...) . '_cache_'` expression, not a literal. The env
786        // var name and override capability still survive even though the
787        // literal default can't be baked in.
788        let source = r#"<?php
789
790return [
791    'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
792];
793"#;
794        let generated = convert_body("cache", source).unwrap();
795        // A degraded-but-faithful env() read, not a raw-source embed -
796        // doesn't need a manual-review flag.
797        assert!(generated.verify.is_empty());
798        assert!(generated.code.contains(
799            r#"config["prefix"] = json!(larust_support::config_env::env("CACHE_PREFIX"));"#
800        ));
801    }
802
803    #[test]
804    fn a_cast_expression_unwraps_to_the_inner_values_translation() {
805        // Real source: `config/responsecache.php`'s
806        // `(int) env('RESPONSE_CACHE_LIFETIME', 60 * 60 * 24 * 7)` - the
807        // cast is discarded (JSON numbers aren't int/float-tagged the way
808        // PHP casts are); the arithmetic default expression inside still
809        // degrades to a bare `env(key)` read via the same path a
810        // computed default always takes.
811        let source = r#"<?php
812
813return [
814    'cache_lifetime_in_seconds' => (int) env('RESPONSE_CACHE_LIFETIME', 60 * 60 * 24 * 7),
815];
816"#;
817        let generated = convert_body("responsecache", source).unwrap();
818        assert!(generated.verify.is_empty());
819        assert!(generated.code.contains(
820            r#"config["cache_lifetime_in_seconds"] = json!(larust_support::config_env::env("RESPONSE_CACHE_LIFETIME"));"#
821        ));
822    }
823
824    #[test]
825    fn a_class_constant_reference_is_converted_verbatim_and_flagged() {
826        // Real source: `config/responsecache.php`'s `cache_profile` -
827        // a `::class` reference to a PHP class with no Larust equivalent.
828        let source = r#"<?php
829
830return [
831    'cache_profile' => Spatie\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests::class,
832];
833"#;
834        let generated = convert_body("responsecache", source).unwrap();
835        assert_eq!(generated.verify.len(), 1);
836        assert!(generated.verify[0].contains("cache_profile"));
837        assert!(generated.code.contains(
838            r#"config["cache_profile"] = json!("Spatie\\ResponseCache\\CacheProfiles\\CacheAllSuccessfulGetRequests::class");"#
839        ));
840    }
841
842    #[test]
843    fn a_complex_boolean_expression_combining_env_calls_is_converted_verbatim() {
844        // Real source: `config/responsecache.php`'s `enabled`.
845        let source = r#"<?php
846
847return [
848    'enabled' => env('APP_ENV') !== 'local' && env('RESPONSE_CACHE_ENABLED', true),
849];
850"#;
851        let generated = convert_body("responsecache", source).unwrap();
852        assert_eq!(generated.resolved_keys, vec!["responsecache.enabled"]);
853        assert_eq!(generated.verify.len(), 1);
854        assert!(generated.verify[0].contains("enabled"));
855    }
856
857    #[test]
858    fn returns_none_when_every_key_is_already_mappings_claimed() {
859        // Nothing left to generate - every key already has a real
860        // `Config`-struct-backed home, so no module (and no `pub mod`
861        // reference to a file that would otherwise be empty) is produced.
862        let source = r#"<?php
863
864return [
865    'default' => env('MAIL_MAILER', 'log'),
866];
867"#;
868        assert!(convert_body("mail", source).is_none());
869    }
870
871    #[test]
872    fn render_body_still_reports_resolved_and_skipped_when_every_key_is_mappings_claimed() {
873        // Unlike `convert_body` (which returns `None` when there's nothing
874        // to generate as a standalone module), `render_body` still hands
875        // back the (empty) bookkeeping - the `config/app.rs` merge case
876        // needs this to know a file contributed nothing, not to treat it
877        // as a parse failure.
878        let source = r#"<?php
879
880return [
881    'default' => env('MAIL_MAILER', 'log'),
882];
883"#;
884        let body = render_body("mail", source).unwrap();
885        assert!(body.assignments.is_empty());
886        assert!(body.resolved_keys.is_empty());
887        assert!(body.skipped.is_empty());
888        assert!(body.verify.is_empty());
889    }
890
891    #[test]
892    fn render_body_produces_the_same_assignment_lines_convert_body_wraps() {
893        let source = r#"<?php
894
895return [
896    'apiurl' => env('APP_API', 'https://wallabypanel.com/items'),
897];
898"#;
899        let body = render_body("app", source).unwrap();
900        assert_eq!(body.resolved_keys, vec!["app.apiurl"]);
901        assert_eq!(body.assignments.len(), 1);
902        assert!(body.assignments[0].contains(
903            r#"config["apiurl"] = json!(larust_support::config_env::env_or("APP_API", "https://wallabypanel.com/items"));"#
904        ));
905    }
906
907    #[test]
908    fn returns_none_for_a_file_that_fails_to_parse() {
909        assert!(convert_body("broken", "<?php this is not valid php {{{").is_none());
910    }
911
912    #[test]
913    fn returns_none_when_the_top_level_return_is_not_a_plain_array() {
914        assert!(convert_body("weird", "<?php\nreturn 'not-an-array';\n").is_none());
915    }
916}