Skip to main content

larust_convert/
constructor_props.rs

1//! Shared constructor-property extraction for `events.rs`/`jobs.rs` -
2//! both a converted `Event` and a converted `Job` are simple field-only
3//! structs whose fields come from the Laravel class's own constructor.
4//! Real Laravel code uses **two** styles, both detected here: modern
5//! constructor-promoted properties (`public function __construct(public
6//! Order $order) {}`) and the older explicit-property-plus-assignment
7//! style (`public $order; public function __construct(Order $order) {
8//! $this->order = $order; }`) - both produce the same flat field list.
9//!
10//! **Whole-item safety, not per-field**: constructor fields are the
11//! struct's *entire* field list - there's no safe way to emit a
12//! partially-wrong struct the way Phase 2a can emit a form-request field
13//! bare. Any parameter this module can't confidently type rejects the
14//! whole extraction; the caller (`events.rs`/`jobs.rs`) skips that whole
15//! class.
16
17use crate::php;
18use tree_sitter::{Node, Tree};
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ConstructorField {
22    pub name: String,
23    pub rust_type: String,
24}
25
26/// `Ok(vec![])` if the class has no constructor at all (not an error -
27/// some classes genuinely have no properties). `Err` if any parameter
28/// that looks like it's meant to be a field has a type this module
29/// doesn't recognize.
30pub fn extract(
31    tree: &Tree,
32    source: &str,
33    class_name: &str,
34) -> Result<Vec<ConstructorField>, String> {
35    let Some(constructor) = php::find_method(tree, source, class_name, "__construct") else {
36        return Ok(Vec::new());
37    };
38    let Some(parameters) = constructor.child_by_field_name("parameters") else {
39        return Ok(Vec::new());
40    };
41
42    let mut fields = Vec::new();
43
44    for param in php::direct_children_of_kind(parameters, "property_promotion_parameter") {
45        let type_node = param
46            .child_by_field_name("type")
47            .ok_or_else(|| "a constructor-promoted property is missing a type hint".to_string())?;
48        let name = parameter_name(param, source)
49            .ok_or_else(|| "a constructor-promoted property is missing a name".to_string())?;
50        let rust_type = map_type(type_node, source)?;
51        fields.push(ConstructorField {
52            name: crate::codegen::to_snake_case(&name),
53            rust_type,
54        });
55    }
56
57    // Self-assignment matching (`$this->postId = $postId;`) has to use
58    // each parameter's *raw* PHP name - that's what the source actually
59    // wrote on both sides - only the final emitted field name is
60    // snake_cased. No wire-key coupling to worry about here the way
61    // Phase 2a's form-request fields had (nothing reads a Job/Event
62    // field's name back as a runtime string key the source controls);
63    // `#[derive(Serialize, Deserialize)]` round-trips against whatever
64    // name this converter itself picks, so renaming for idiomatic,
65    // clippy-clean Rust is safe.
66    let classic_candidates: Vec<(String, Node)> =
67        php::direct_children_of_kind(parameters, "simple_parameter")
68            .into_iter()
69            .filter_map(|param| {
70                let type_node = param.child_by_field_name("type")?;
71                let name = parameter_name(param, source)?;
72                Some((name, type_node))
73            })
74            .collect();
75
76    if !classic_candidates.is_empty() {
77        let Some(body) = constructor.child_by_field_name("body") else {
78            return Ok(fields);
79        };
80        for (name, type_node) in classic_candidates {
81            if has_self_assignment(body, &name, source) {
82                let rust_type = map_type(type_node, source)?;
83                fields.push(ConstructorField {
84                    name: crate::codegen::to_snake_case(&name),
85                    rust_type,
86                });
87            }
88        }
89    }
90
91    Ok(fields)
92}
93
94fn parameter_name(param: Node, source: &str) -> Option<String> {
95    let name_node = param.child_by_field_name("name")?;
96    let inner = name_node.named_child(0)?;
97    Some(inner.utf8_text(source.as_bytes()).ok()?.to_string())
98}
99
100/// `$this->{param_name} = ${param_name};` anywhere at the top level of
101/// `body` - the common-convention self-assignment classic-style
102/// constructors use. A parameter with no matching assignment isn't
103/// treated as a field at all (not an error - plenty of constructor
104/// parameters are used for something other than storing a property).
105fn has_self_assignment(body: Node, param_name: &str, source: &str) -> bool {
106    let bytes = source.as_bytes();
107    php::statement_expressions(body).into_iter().any(|stmt| {
108        stmt.kind() == "assignment_expression"
109            && is_this_property(stmt.child_by_field_name("left"), param_name, bytes)
110            && is_matching_variable(stmt.child_by_field_name("right"), param_name, bytes)
111    })
112}
113
114fn is_this_property(left: Option<Node>, param_name: &str, bytes: &[u8]) -> bool {
115    let Some(left) = left else { return false };
116    if left.kind() != "member_access_expression" {
117        return false;
118    }
119    let Some(object) = left.child_by_field_name("object") else {
120        return false;
121    };
122    if object.kind() != "variable_name" {
123        return false;
124    }
125    let Some(object_name) = object.named_child(0).and_then(|n| n.utf8_text(bytes).ok()) else {
126        return false;
127    };
128    if object_name != "this" {
129        return false;
130    }
131    left.child_by_field_name("name")
132        .and_then(|n| n.utf8_text(bytes).ok())
133        == Some(param_name)
134}
135
136fn is_matching_variable(right: Option<Node>, param_name: &str, bytes: &[u8]) -> bool {
137    let Some(right) = right else { return false };
138    if right.kind() != "variable_name" {
139        return false;
140    }
141    right.named_child(0).and_then(|n| n.utf8_text(bytes).ok()) == Some(param_name)
142}
143
144/// PHP type hint -> Rust type. Only the 4 scalar primitives map - a class
145/// type hint (e.g. `Post $post`, common for "the model this event/job is
146/// about") is rejected, not guessed at: nothing this phase converts
147/// guarantees the referenced type will satisfy whatever the containing
148/// struct's own derive needs (`Event`s need `Clone`, `Job`s need
149/// `Serialize`/`Deserialize`; `#[derive(Model)]` provides neither - see
150/// `larust-macros::model`). The real, hand-authored `demo/app/Events/
151/// post_created.rs` confirms this is the actual convention: it takes
152/// `post_id: i64`, not the `Post` model itself. `optional_type`
153/// (`?Order`)/`union_type` (`Order|null`) are also rejected - both mean
154/// "this field can be absent," which has no safe, mechanical single-type
155/// mapping here either.
156fn map_type(type_node: Node, source: &str) -> Result<String, String> {
157    let bytes = source.as_bytes();
158    match type_node.kind() {
159        "primitive_type" => {
160            let text = type_node.utf8_text(bytes).map_err(|e| e.to_string())?;
161            match text {
162                "int" => Ok("i64".to_string()),
163                "string" => Ok("String".to_string()),
164                "bool" => Ok("bool".to_string()),
165                "float" => Ok("f64".to_string()),
166                other => Err(format!("unsupported primitive type `{other}`")),
167            }
168        }
169        "named_type" => {
170            let name = type_node
171                .named_child(0)
172                .and_then(|n| n.utf8_text(bytes).ok())
173                .unwrap_or("?");
174            Err(format!(
175                "class type hints aren't supported for event/job fields (`{name}`) - reference the model's id instead (e.g. `int ${{name}}Id`)"
176            ))
177        }
178        "optional_type" | "union_type" => Err(format!(
179            "nullable/union type hints aren't supported: `{}`",
180            type_node.utf8_text(bytes).unwrap_or("")
181        )),
182        other => Err(format!("unsupported type hint shape `{other}`")),
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn extracts_constructor_promoted_properties() {
192        let source = "<?php\nclass OrderShipped {\n    public function __construct(public int $orderId, public string $carrier) {}\n}\n";
193        let tree = php::parse(source).unwrap();
194        let fields = extract(&tree, source, "OrderShipped").unwrap();
195        assert_eq!(
196            fields,
197            vec![
198                ConstructorField {
199                    name: "order_id".to_string(),
200                    rust_type: "i64".to_string(),
201                },
202                ConstructorField {
203                    name: "carrier".to_string(),
204                    rust_type: "String".to_string(),
205                },
206            ]
207        );
208    }
209
210    #[test]
211    fn rejects_a_class_type_hint_on_a_promoted_property() {
212        let source = "<?php\nclass OrderShipped {\n    public function __construct(public Order $order) {}\n}\n";
213        let tree = php::parse(source).unwrap();
214        assert!(extract(&tree, source, "OrderShipped").is_err());
215    }
216
217    #[test]
218    fn extracts_classic_property_plus_assignment_style() {
219        let source = "<?php\nclass InvoicePaid {\n    public $invoiceId;\n    public $amount;\n    public function __construct($invoiceId, $amount)\n    {\n        $this->invoiceId = $invoiceId;\n        $this->amount = $amount;\n    }\n}\n";
220        // Classic-style constructor params here are untyped (`$invoiceId`,
221        // no type hint) - a realistic Laravel class would type them; this
222        // fixture intentionally checks the untyped case is simply not
223        // picked up as a field (no type to map), not a crash.
224        let tree = php::parse(source).unwrap();
225        let fields = extract(&tree, source, "InvoicePaid").unwrap();
226        assert!(fields.is_empty());
227    }
228
229    #[test]
230    fn extracts_classic_style_with_typed_constructor_parameters() {
231        let source = "<?php\nclass X {\n    public $orderId;\n    public function __construct(int $orderId)\n    {\n        $this->orderId = $orderId;\n    }\n}\n";
232        let tree = php::parse(source).unwrap();
233        let fields = extract(&tree, source, "X").unwrap();
234        assert_eq!(
235            fields,
236            vec![ConstructorField {
237                name: "order_id".to_string(),
238                rust_type: "i64".to_string(),
239            }]
240        );
241    }
242
243    #[test]
244    fn rejects_a_class_type_hint_in_classic_style() {
245        let source = "<?php\nclass X {\n    public $order;\n    public function __construct(Order $order)\n    {\n        $this->order = $order;\n    }\n}\n";
246        let tree = php::parse(source).unwrap();
247        assert!(extract(&tree, source, "X").is_err());
248    }
249
250    #[test]
251    fn a_constructor_parameter_with_no_self_assignment_is_not_treated_as_a_field() {
252        let source = "<?php\nclass X {\n    public function __construct(int $retries)\n    {\n        // used locally, never stored\n    }\n}\n";
253        let tree = php::parse(source).unwrap();
254        let fields = extract(&tree, source, "X").unwrap();
255        assert!(fields.is_empty());
256    }
257
258    #[test]
259    fn a_class_with_no_constructor_yields_no_fields() {
260        let source = "<?php\nclass X {}\n";
261        let tree = php::parse(source).unwrap();
262        assert_eq!(extract(&tree, source, "X").unwrap(), vec![]);
263    }
264
265    #[test]
266    fn rejects_a_nullable_type_hint() {
267        let source =
268            "<?php\nclass X {\n    public function __construct(public ?Order $order) {}\n}\n";
269        let tree = php::parse(source).unwrap();
270        assert!(extract(&tree, source, "X").is_err());
271    }
272
273    #[test]
274    fn rejects_a_union_type_hint() {
275        let source =
276            "<?php\nclass X {\n    public function __construct(public Order|string $order) {}\n}\n";
277        let tree = php::parse(source).unwrap();
278        assert!(extract(&tree, source, "X").is_err());
279    }
280
281    #[test]
282    fn maps_every_primitive_type() {
283        let source = "<?php\nclass X {\n    public function __construct(public int $a, public string $b, public bool $c, public float $d) {}\n}\n";
284        let tree = php::parse(source).unwrap();
285        let fields = extract(&tree, source, "X").unwrap();
286        assert_eq!(fields[0].rust_type, "i64");
287        assert_eq!(fields[1].rust_type, "String");
288        assert_eq!(fields[2].rust_type, "bool");
289        assert_eq!(fields[3].rust_type, "f64");
290    }
291}