alef-backend-php 0.13.1

PHP (ext-php-rs) backend for alef
Documentation
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! PHP (ext-php-rs) specific trait bridge code generation.
//!
//! Generates Rust wrapper structs that implement Rust traits by delegating
//! to PHP objects via ext-php-rs Zval method calls.

use alef_codegen::generators::trait_bridge::{
    BridgeOutput, TraitBridgeGenerator, TraitBridgeSpec, bridge_param_type as param_type, gen_bridge_all,
    to_camel_case, visitor_param_type,
};
use alef_core::config::TraitBridgeConfig;
use alef_core::ir::{ApiSurface, MethodDef, TypeDef, TypeRef};
use std::collections::HashMap;
use std::fmt::Write;

/// Find the first parameter index and bridge config where the parameter's named type
/// matches a trait bridge's `type_alias`.
///
/// Returns `None` when no bridge applies.
pub use alef_codegen::generators::trait_bridge::find_bridge_param;

/// PHP-specific trait bridge generator.
/// Implements code generation for bridging PHP objects to Rust traits.
pub struct PhpBridgeGenerator {
    /// Core crate import path (e.g., `"kreuzberg"`).
    pub core_import: String,
    /// Map of type name → fully-qualified Rust path for type references.
    pub type_paths: HashMap<String, String>,
    /// Error type name (e.g., `"KreuzbergError"`).
    pub error_type: String,
}

impl TraitBridgeGenerator for PhpBridgeGenerator {
    fn foreign_object_type(&self) -> &str {
        "*mut ext_php_rs::types::ZendObject"
    }

    fn bridge_imports(&self) -> Vec<String> {
        vec!["std::sync::Arc".to_string()]
    }

    fn gen_sync_method_body(&self, method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
        let name = &method.name;
        let mut out = String::with_capacity(512);

        // PHP is single-threaded; just call the method directly.
        writeln!(
            out,
            "// SAFETY: PHP objects are single-threaded; method calls are safe within a request."
        )
        .ok();

        let has_args = !method.params.is_empty();
        let args_expr = if has_args {
            let mut args_parts = Vec::new();
            for p in &method.params {
                let arg_expr = match &p.ty {
                    TypeRef::String => format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name),
                    TypeRef::Path => format!(
                        "ext_php_rs::types::Zval::try_from({}.to_string_lossy().to_string()).unwrap_or_default()",
                        p.name
                    ),
                    TypeRef::Bytes => format!(
                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
                        p.name
                    ),
                    TypeRef::Named(_) => {
                        format!(
                            "ext_php_rs::types::Zval::try_from(serde_json::to_string(&{}).unwrap_or_default()).unwrap_or_default()",
                            p.name
                        )
                    }
                    TypeRef::Primitive(_) => {
                        format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name)
                    }
                    _ => format!(
                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
                        p.name
                    ),
                };
                args_parts.push(arg_expr);
            }
            let args_array = format!("[{}]", args_parts.join(", "));
            format!(
                "{}.iter().map(|z| z as &dyn ext_php_rs::convert::IntoZvalDyn).collect()",
                args_array
            )
        } else {
            "vec![]".to_string()
        };

        writeln!(
            out,
            "let result = unsafe {{ (*self.inner).try_call_method(\"{name}\", {args_expr}) }};"
        )
        .ok();

        // Check if method returns a Result type
        if method.error_type.is_some() {
            writeln!(out, "match result {{").ok();
            // Check if return type is unit ()
            if matches!(method.return_type, TypeRef::Unit) {
                writeln!(out, "    Ok(_) => Ok(()),").ok();
            } else {
                // For Result-returning methods, the PHP value should be deserialized from JSON
                writeln!(out, "    Ok(val) => {{").ok();
                writeln!(out, "        let json_str = val.string().unwrap_or_default();").ok();
                writeln!(out, "        serde_json::from_str(&json_str).map_err(|e| {}::KreuzbergError::Other(format!(\"Deserialize error: {{}}\", e)))", self.core_import).ok();
                writeln!(out, "    }}").ok();
            }
            // Error conversion: ext-php-rs::error::Error → KreuzbergError
            // Use string conversion since there's no direct From impl
            writeln!(
                out,
                "    Err(e) => Err({}::KreuzbergError::Other(e.to_string())),",
                self.core_import
            )
            .ok();
            writeln!(out, "}}").ok();
        } else {
            writeln!(out, "match result {{").ok();
            // Check if return type is unit ()
            if matches!(method.return_type, TypeRef::Unit) {
                writeln!(out, "    Ok(_) => (),").ok();
            } else {
                // For non-Result methods, try to deserialize from JSON
                // (safer than trying to parse arbitrary types)
                writeln!(out, "    Ok(val) => {{").ok();
                writeln!(out, "        let json_str = val.string().unwrap_or_default();").ok();
                writeln!(out, "        serde_json::from_str(&json_str).unwrap_or_default()").ok();
                writeln!(out, "    }}").ok();
            }
            writeln!(out, "    Err(_) => Default::default(),").ok();
            writeln!(out, "}}").ok();
        }

        out
    }

    fn gen_async_method_body(&self, method: &MethodDef, spec: &TraitBridgeSpec) -> String {
        let name = &method.name;
        let mut out = String::with_capacity(1024);

        writeln!(out, "let inner_obj = self.inner;").ok();
        writeln!(out, "let cached_name = self.cached_name.clone();").ok();

        // Clone params for the blocking closure (String types need explicit clone)
        for p in &method.params {
            if matches!(&p.ty, TypeRef::String) {
                writeln!(out, "let {} = {}.clone();", p.name, p.name).ok();
            }
        }

        writeln!(out).ok();
        writeln!(out, "// SAFETY: PHP objects are single-threaded within a request.").ok();
        writeln!(out, "// The block_on executes within the async runtime.").ok();
        writeln!(out, "WORKER_RUNTIME.block_on(async {{").ok();

        let has_args = !method.params.is_empty();
        let args_expr = if has_args {
            let mut args_parts = Vec::new();
            for p in &method.params {
                let arg_expr = match &p.ty {
                    TypeRef::String => format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name),
                    TypeRef::Path => format!(
                        "ext_php_rs::types::Zval::try_from({}.to_string_lossy().to_string()).unwrap_or_default()",
                        p.name
                    ),
                    TypeRef::Bytes => format!(
                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
                        p.name
                    ),
                    TypeRef::Named(_) => {
                        format!(
                            "ext_php_rs::types::Zval::try_from(serde_json::to_string(&{}).unwrap_or_default()).unwrap_or_default()",
                            p.name
                        )
                    }
                    TypeRef::Primitive(_) => {
                        format!("ext_php_rs::types::Zval::try_from({}).unwrap_or_default()", p.name)
                    }
                    _ => format!(
                        "ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default()",
                        p.name
                    ),
                };
                args_parts.push(arg_expr);
            }
            let args_array = format!("[{}]", args_parts.join(", "));
            format!(
                "{}.iter().map(|z| z as &dyn ext_php_rs::convert::IntoZvalDyn).collect()",
                args_array
            )
        } else {
            "vec![]".to_string()
        };

        // inner_obj is *mut ZendObject, so we need to dereference and call the method.
        // SAFETY: the raw pointer is valid within the async block.
        writeln!(
            out,
            "    match unsafe {{ (*inner_obj).try_call_method(\"{name}\", {args_expr}) }} {{"
        )
        .ok();

        // For Result-returning methods, deserialize JSON. For non-Result, parse directly.
        if method.error_type.is_some() {
            writeln!(out, "        Ok(val) => {{").ok();
            writeln!(out, "            let json_str = val.string().unwrap_or_default();").ok();
            writeln!(
                out,
                "            serde_json::from_str(&json_str).map_err(|e| {}::KreuzbergError::Other(format!(\"Deserialize error: {{}}\", e)))",
                spec.core_import
            )
            .ok();
            writeln!(out, "        }}").ok();
        } else {
            writeln!(
                out,
                "        Ok(val) => val.string().unwrap_or_default().parse().unwrap_or_default(),"
            )
            .ok();
        }

        writeln!(
            out,
            "        Err(e) => Err({}::KreuzbergError::Plugin {{",
            spec.core_import
        )
        .ok();
        writeln!(
            out,
            "            message: format!(\"Plugin '{{}}' method '{name}' failed: {{}}\", cached_name, e),"
        )
        .ok();
        writeln!(out, "            plugin_name: cached_name.clone(),").ok();
        writeln!(out, "        }}),").ok();
        writeln!(out, "    }}").ok();
        writeln!(out, "}})",).ok();

        out
    }

    fn gen_constructor(&self, spec: &TraitBridgeSpec) -> String {
        let wrapper = spec.wrapper_name();
        let mut out = String::with_capacity(512);

        writeln!(out, "impl {wrapper} {{").ok();
        writeln!(out, "    /// Create a new bridge wrapping a PHP object.").ok();
        writeln!(out, "    ///").ok();
        writeln!(
            out,
            "    /// Validates that the PHP object provides all required methods."
        )
        .ok();
        writeln!(
            out,
            "    pub fn new(php_obj: &mut ext_php_rs::types::ZendObject) -> Self {{"
        )
        .ok();

        // Validation of required methods is done in the registration function below.
        // Skipping debug_assert in constructor to avoid type issues with get_property.

        // Extract and cache name
        writeln!(out, "        let cached_name = php_obj").ok();
        writeln!(out, "            .try_call_method(\"name\", vec![])").ok();
        writeln!(out, "            .ok()").ok();
        writeln!(out, "            .and_then(|v| v.string())").ok();
        writeln!(out, "            .unwrap_or(\"unknown\".into())").ok();
        writeln!(out, "            .to_string();").ok();

        writeln!(out).ok();
        writeln!(out, "        Self {{").ok();
        writeln!(out, "            inner: php_obj as *mut _,").ok();
        writeln!(out, "            cached_name,").ok();
        writeln!(out, "        }}").ok();
        writeln!(out, "    }}").ok();
        writeln!(out, "}}").ok();

        // SAFETY: PHP objects are single-threaded within a request.
        // The raw pointer is only valid for the duration of the PHP call stack,
        // and is never accessed concurrently or from multiple threads.
        writeln!(out).ok();
        writeln!(out, "// SAFETY: PHP is single-threaded within a request context.").ok();
        writeln!(
            out,
            "// The raw pointer to ZendObject is only used within a single PHP request"
        )
        .ok();
        writeln!(out, "// and is never accessed concurrently from multiple threads.").ok();
        writeln!(out, "unsafe impl Send for {wrapper} {{}}").ok();
        writeln!(out, "unsafe impl Sync for {wrapper} {{}}").ok();

        out
    }

    fn gen_registration_fn(&self, spec: &TraitBridgeSpec) -> String {
        let Some(register_fn) = spec.bridge_config.register_fn.as_deref() else {
            return String::new();
        };
        let Some(registry_getter) = spec.bridge_config.registry_getter.as_deref() else {
            return String::new();
        };
        let wrapper = spec.wrapper_name();
        let trait_path = spec.trait_path();

        let mut out = String::with_capacity(1024);

        writeln!(out, "#[php_function]").ok();
        writeln!(
            out,
            "pub fn {register_fn}(backend: &mut ext_php_rs::types::ZendObject) -> ext_php_rs::prelude::PhpResult<()> {{"
        )
        .ok();

        // Validate required methods
        let req_methods: Vec<&MethodDef> = spec.required_methods();
        if !req_methods.is_empty() {
            for method in &req_methods {
                // Check if required method exists by attempting to call it with empty args.
                writeln!(
                    out,
                    r#"    if backend.try_call_method("{}", vec![]).is_err() {{"#,
                    method.name
                )
                .ok();
                writeln!(out, "        return Err(ext_php_rs::exception::PhpException::default(").ok();
                writeln!(
                    out,
                    "            format!(\"Backend missing required method: {{}}\", \"{}\")",
                    method.name
                )
                .ok();
                writeln!(out, "        ));").ok();
                writeln!(out, "    }}").ok();
            }
        }

        writeln!(out).ok();
        writeln!(out, "    let wrapper = {wrapper}::new(backend);").ok();
        writeln!(
            out,
            "    let arc: std::sync::Arc<dyn {trait_path}> = std::sync::Arc::new(wrapper);"
        )
        .ok();
        writeln!(out).ok();

        let extra = spec
            .bridge_config
            .register_extra_args
            .as_deref()
            .map(|a| format!(", {a}"))
            .unwrap_or_default();
        writeln!(out, "    let registry = {registry_getter}();").ok();
        writeln!(out, "    let mut registry = registry.write();").ok();
        writeln!(
            out,
            "    registry.register(arc{extra}).map_err(|e| ext_php_rs::exception::PhpException::default("
        )
        .ok();
        writeln!(out, "        format!(\"Failed to register backend: {{}}\", e)").ok();
        writeln!(out, "    ))?;").ok();
        writeln!(out, "    Ok(())").ok();
        writeln!(out, "}}").ok();

        out
    }
}

/// Generate all trait bridge code for a given trait type and bridge config.
pub fn gen_trait_bridge(
    trait_type: &TypeDef,
    bridge_cfg: &TraitBridgeConfig,
    core_import: &str,
    error_type: &str,
    error_constructor: &str,
    api: &ApiSurface,
) -> BridgeOutput {
    // Build type name → rust_path lookup as owned HashMap
    let type_paths: HashMap<String, String> = api
        .types
        .iter()
        .map(|t| (t.name.clone(), t.rust_path.replace('-', "_")))
        .chain(
            api.enums
                .iter()
                .map(|e| (e.name.clone(), e.rust_path.replace('-', "_"))),
        )
        .collect();

    // Visitor-style bridge: all methods have defaults, no registry, no super-trait.
    let is_visitor_bridge = bridge_cfg.type_alias.is_some()
        && bridge_cfg.register_fn.is_none()
        && bridge_cfg.super_trait.is_none()
        && trait_type.methods.iter().all(|m| m.has_default_impl);

    if is_visitor_bridge {
        let struct_name = format!("Php{}Bridge", bridge_cfg.trait_name);
        let trait_path = trait_type.rust_path.replace('-', "_");
        let code = gen_visitor_bridge(trait_type, bridge_cfg, &struct_name, &trait_path, &type_paths);
        BridgeOutput { imports: vec![], code }
    } else {
        // Use the IR-driven TraitBridgeGenerator infrastructure
        let generator = PhpBridgeGenerator {
            core_import: core_import.to_string(),
            type_paths: type_paths.clone(),
            error_type: error_type.to_string(),
        };
        let spec = TraitBridgeSpec {
            trait_def: trait_type,
            bridge_config: bridge_cfg,
            core_import,
            wrapper_prefix: "Php",
            type_paths,
            error_type: error_type.to_string(),
            error_constructor: error_constructor.to_string(),
        };
        gen_bridge_all(&spec, &generator)
    }
}

/// Generate a visitor-style bridge wrapping a PHP `Zval` object reference.
///
/// Every trait method checks if the PHP object has a matching camelCase method,
/// then calls it and maps the PHP return value to `VisitResult`.
fn gen_visitor_bridge(
    trait_type: &TypeDef,
    _bridge_cfg: &TraitBridgeConfig,
    struct_name: &str,
    trait_path: &str,
    type_paths: &HashMap<String, String>,
) -> String {
    let mut out = String::with_capacity(4096);
    let core_crate = trait_path
        .split("::")
        .next()
        .unwrap_or("html_to_markdown_rs")
        .to_string();
    // Helper: convert NodeContext to a PHP array (Zval)
    writeln!(out, "fn nodecontext_to_php_array(").unwrap();
    writeln!(out, "    ctx: &{core_crate}::visitor::NodeContext,").unwrap();
    writeln!(out, ") -> ext_php_rs::boxed::ZBox<ext_php_rs::types::ZendHashTable> {{").unwrap();
    writeln!(out, "    let mut arr = ext_php_rs::types::ZendHashTable::new();").unwrap();
    writeln!(
        out,
        "    arr.insert(\"nodeType\", ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", ctx.node_type)).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(
        out,
        "    arr.insert(\"tagName\", ext_php_rs::types::Zval::try_from(ctx.tag_name.clone()).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(
        out,
        "    arr.insert(\"depth\", ext_php_rs::types::Zval::try_from(ctx.depth as i64).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(
        out,
        "    arr.insert(\"indexInParent\", ext_php_rs::types::Zval::try_from(ctx.index_in_parent as i64).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(
        out,
        "    arr.insert(\"isInline\", ext_php_rs::types::Zval::try_from(ctx.is_inline).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(out, "    if let Some(ref pt) = ctx.parent_tag {{").unwrap();
    writeln!(
        out,
        "        arr.insert(\"parentTag\", ext_php_rs::types::Zval::try_from(pt.clone()).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(out, "    }}").unwrap();
    writeln!(out, "    let mut attrs = ext_php_rs::types::ZendHashTable::new();").unwrap();
    writeln!(out, "    for (k, v) in &ctx.attributes {{").unwrap();
    writeln!(
        out,
        "        attrs.insert(k.as_str(), ext_php_rs::types::Zval::try_from(v.clone()).unwrap_or_default()).ok();"
    )
    .unwrap();
    writeln!(out, "    }}").unwrap();
    writeln!(out, "    let mut attrs_zval = ext_php_rs::types::Zval::new();").unwrap();
    writeln!(out, "    attrs_zval.set_hashtable(attrs);").unwrap();
    writeln!(out, "    arr.insert(\"attributes\", attrs_zval).ok();").unwrap();
    writeln!(out, "    arr").unwrap();
    writeln!(out, "}}").unwrap();
    writeln!(out).unwrap();

    // Bridge struct — stores a reference to the PHP object.
    // The reference is valid for the duration of the PHP function call that
    // created the bridge, which spans the entire Rust trait method dispatch.
    writeln!(out, "pub struct {struct_name} {{").unwrap();
    writeln!(out, "    php_obj: *mut ext_php_rs::types::ZendObject,").unwrap();
    writeln!(out, "    cached_name: String,").unwrap();
    writeln!(out, "}}").unwrap();
    writeln!(out).unwrap();

    // SAFETY: The raw pointer is only used while the PHP call stack frame is
    // alive. The bridge is consumed before the PHP function returns.
    writeln!(out, "// SAFETY: PHP objects are single-threaded; the bridge is used").unwrap();
    writeln!(out, "// only within a single PHP request, never across threads.").unwrap();
    writeln!(out, "unsafe impl Send for {struct_name} {{}}").unwrap();
    writeln!(out, "unsafe impl Sync for {struct_name} {{}}").unwrap();
    writeln!(out).unwrap();

    writeln!(out, "impl Clone for {struct_name} {{").unwrap();
    writeln!(out, "    fn clone(&self) -> Self {{").unwrap();
    writeln!(out, "        Self {{").unwrap();
    writeln!(out, "            php_obj: self.php_obj,").unwrap();
    writeln!(out, "            cached_name: self.cached_name.clone(),").unwrap();
    writeln!(out, "        }}").unwrap();
    writeln!(out, "    }}").unwrap();
    writeln!(out, "}}").unwrap();
    writeln!(out).unwrap();

    // Manual Debug impl
    writeln!(out, "impl std::fmt::Debug for {struct_name} {{").unwrap();
    writeln!(
        out,
        "    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{"
    )
    .unwrap();
    writeln!(out, "        write!(f, \"{struct_name}\")").unwrap();
    writeln!(out, "    }}").unwrap();
    writeln!(out, "}}").unwrap();
    writeln!(out).unwrap();

    // Constructor takes &mut ZendObject, which is what ext-php-rs exposes via
    // FromZvalMut. We store the raw pointer; the caller guarantees the object
    // outlives this bridge.
    writeln!(out, "impl {struct_name} {{").unwrap();
    writeln!(
        out,
        "    pub fn new(php_obj: &mut ext_php_rs::types::ZendObject) -> Self {{"
    )
    .unwrap();
    writeln!(out, "        let cached_name = php_obj").unwrap();
    writeln!(out, "            .try_call_method(\"name\", vec![])").unwrap();
    writeln!(out, "            .ok()").unwrap();
    writeln!(out, "            .and_then(|v| v.string())").unwrap();
    writeln!(out, "            .unwrap_or(\"unknown\".into())").unwrap();
    writeln!(out, "            .to_string();").unwrap();
    writeln!(out, "        Self {{ php_obj: php_obj as *mut _, cached_name }}").unwrap();
    writeln!(out, "    }}").unwrap();
    writeln!(out, "}}").unwrap();
    writeln!(out).unwrap();

    // Trait impl
    writeln!(out, "impl {trait_path} for {struct_name} {{").unwrap();
    for method in &trait_type.methods {
        if method.trait_source.is_some() {
            continue;
        }
        gen_visitor_method_php(&mut out, method, type_paths);
    }
    writeln!(out, "}}").unwrap();
    writeln!(out).unwrap();

    out
}

/// Generate a single visitor method that checks for a camelCase PHP method and calls it.
fn gen_visitor_method_php(out: &mut String, method: &MethodDef, type_paths: &HashMap<String, String>) {
    let name = &method.name;
    let php_name = to_camel_case(name);

    let mut sig_parts = vec!["&mut self".to_string()];
    for p in &method.params {
        let ty_str = visitor_param_type(&p.ty, p.is_ref, p.optional, type_paths);
        sig_parts.push(format!("{}: {}", p.name, ty_str));
    }
    let sig = sig_parts.join(", ");

    let ret_ty = match &method.return_type {
        TypeRef::Named(n) => type_paths.get(n).cloned().unwrap_or_else(|| n.clone()),
        other => param_type(other, "", false, type_paths),
    };

    writeln!(out, "    fn {name}({sig}) -> {ret_ty} {{").unwrap();

    // SAFETY: php_obj pointer is valid for the lifetime of the PHP call frame.
    writeln!(
        out,
        "        // SAFETY: php_obj is a valid ZendObject pointer for the duration of this call."
    )
    .unwrap();
    writeln!(out, "        let php_obj_ref = unsafe {{ &mut *self.php_obj }};").unwrap();

    // Build args array
    let has_args = !method.params.is_empty();
    if has_args {
        writeln!(out, "        let mut args: Vec<ext_php_rs::types::Zval> = Vec::new();").unwrap();
        for p in &method.params {
            if let TypeRef::Named(n) = &p.ty {
                if n == "NodeContext" {
                    writeln!(
                        out,
                        "        let ctx_arr = nodecontext_to_php_array({}{});",
                        if p.is_ref { "" } else { "&" },
                        p.name
                    )
                    .unwrap();
                    writeln!(
                        out,
                        "        args.push(ext_php_rs::convert::IntoZval::into_zval(ctx_arr, false).unwrap_or_default());"
                    )
                    .unwrap();
                    continue;
                }
            }
            // Check optional string ref BEFORE non-optional string, since visitor_param_type
            // returns Option<&str> for optional string ref params.
            if p.optional && matches!(&p.ty, TypeRef::String) && p.is_ref {
                writeln!(
                    out,
                    "        args.push(match {0} {{ Some(s) => ext_php_rs::types::Zval::try_from(s.to_string()).unwrap_or_default(), None => ext_php_rs::types::Zval::new() }});",
                    p.name
                )
                .unwrap();
                continue;
            }
            if matches!(&p.ty, TypeRef::String) {
                if p.is_ref {
                    writeln!(
                        out,
                        "        args.push(ext_php_rs::types::Zval::try_from({}.to_string()).unwrap_or_default());",
                        p.name
                    )
                    .unwrap();
                } else {
                    writeln!(
                        out,
                        "        args.push(ext_php_rs::types::Zval::try_from({}.clone()).unwrap_or_default());",
                        p.name
                    )
                    .unwrap();
                }
                continue;
            }
            if matches!(&p.ty, TypeRef::Primitive(alef_core::ir::PrimitiveType::Bool)) {
                writeln!(
                    out,
                    "        {{ let mut _zv = ext_php_rs::types::Zval::new(); _zv.set_bool({}); args.push(_zv); }}",
                    p.name
                )
                .unwrap();
                continue;
            }
            // Default: format as string
            writeln!(
                out,
                "        args.push(ext_php_rs::types::Zval::try_from(format!(\"{{:?}}\", {})).unwrap_or_default());",
                p.name
            )
            .unwrap();
        }
    }

    // Call the PHP method via try_call_method which takes Vec<&dyn IntoZvalDyn>.
    // If the method does not exist, try_call_method returns Err(Error::Callable),
    // which we treat as a "no-op, return Continue" (same as the default impl).
    if has_args {
        writeln!(
            out,
            "        let dyn_args: Vec<&dyn ext_php_rs::convert::IntoZvalDyn> = args.iter().map(|z| z as &dyn ext_php_rs::convert::IntoZvalDyn).collect();"
        )
        .unwrap();
    }
    let args_expr = if has_args { "dyn_args" } else { "vec![]" };
    writeln!(
        out,
        "        let result = php_obj_ref.try_call_method(\"{php_name}\", {args_expr});"
    )
    .unwrap();

    // Parse result — try_call_method returns Result<Zval> (not Result<Option<Zval>>)
    writeln!(out, "        match result {{").unwrap();
    writeln!(out, "            Err(_) => {ret_ty}::Continue,").unwrap();
    writeln!(out, "            Ok(val) => {{").unwrap();
    writeln!(
        out,
        "                let s = val.string().unwrap_or_default().to_lowercase();"
    )
    .unwrap();
    writeln!(out, "                match s.as_str() {{").unwrap();
    writeln!(out, "                    \"continue\" => {ret_ty}::Continue,").unwrap();
    writeln!(out, "                    \"skip\" => {ret_ty}::Skip,").unwrap();
    writeln!(
        out,
        "                    \"preserve_html\" | \"preservehtml\" => {ret_ty}::PreserveHtml,"
    )
    .unwrap();
    writeln!(out, "                    other => {ret_ty}::Custom(other.to_string()),").unwrap();
    writeln!(out, "                }}").unwrap();
    writeln!(out, "            }}").unwrap();
    writeln!(out, "        }}").unwrap();
    writeln!(out, "    }}").unwrap();
    writeln!(out).unwrap();
}

/// Generate a PHP static method that has one parameter replaced by
/// `Option<ext_php_rs::boxed::ZBox<ext_php_rs::types::ZendObject>>` (a trait bridge).
#[allow(clippy::too_many_arguments)]
pub fn gen_bridge_function(
    func: &alef_core::ir::FunctionDef,
    bridge_param_idx: usize,
    bridge_cfg: &TraitBridgeConfig,
    mapper: &dyn alef_codegen::type_mapper::TypeMapper,
    opaque_types: &ahash::AHashSet<String>,
    core_import: &str,
) -> String {
    use alef_core::ir::TypeRef;

    let struct_name = format!("Php{}Bridge", bridge_cfg.trait_name);
    let handle_path = format!("{core_import}::visitor::VisitorHandle");
    let param_name = &func.params[bridge_param_idx].name;
    let bridge_param = &func.params[bridge_param_idx];
    let is_optional = bridge_param.optional || matches!(&bridge_param.ty, TypeRef::Optional(_));

    // Build parameter list, hiding bridge params from signature
    let mut sig_parts = Vec::new();
    for (idx, p) in func.params.iter().enumerate() {
        if idx == bridge_param_idx {
            // Bridge param: &mut ZendObject implements FromZvalMut in ext-php-rs 0.15,
            // allowing PHP to pass any object. ZBox<ZendObject> does NOT implement
            // FromZvalMut, so we must use the reference form here.
            let php_obj_ty = "&mut ext_php_rs::types::ZendObject";
            if is_optional {
                sig_parts.push(format!("{}: Option<{php_obj_ty}>", p.name));
            } else {
                sig_parts.push(format!("{}: {php_obj_ty}", p.name));
            }
        } else {
            let promoted = idx > bridge_param_idx || func.params[..idx].iter().any(|pp| pp.optional);
            let base = mapper.map_type(&p.ty);
            // #[php_class] types (non-opaque Named) only implement FromZvalMut for &mut T,
            // not for owned T — so we must use &mut T in the function signature.
            let ty = match &p.ty {
                TypeRef::Named(n) if !opaque_types.contains(n.as_str()) => {
                    if p.optional || promoted {
                        format!("Option<&mut {base}>")
                    } else {
                        format!("&mut {base}")
                    }
                }
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(n) = inner.as_ref() {
                        if !opaque_types.contains(n.as_str()) {
                            format!("Option<&mut {base}>")
                        } else if p.optional || promoted {
                            format!("Option<{base}>")
                        } else {
                            base
                        }
                    } else if p.optional || promoted {
                        format!("Option<{base}>")
                    } else {
                        base
                    }
                }
                _ => {
                    if p.optional || promoted {
                        format!("Option<{base}>")
                    } else {
                        base
                    }
                }
            };
            sig_parts.push(format!("{}: {}", p.name, ty));
        }
    }

    let params_str = sig_parts.join(", ");
    let return_type = mapper.map_type(&func.return_type);
    let ret = mapper.wrap_return(&return_type, func.error_type.is_some());

    let err_conv = ".map_err(|e| ext_php_rs::exception::PhpException::default(e.to_string()))";

    // Bridge wrapping code
    let bridge_wrap = if is_optional {
        format!(
            "let {param_name} = {param_name}.map(|v| {{\n        \
             let bridge = {struct_name}::new(v);\n        \
             std::rc::Rc::new(std::cell::RefCell::new(bridge)) as {handle_path}\n    \
             }});"
        )
    } else {
        format!(
            "let {param_name} = {{\n        \
             let bridge = {struct_name}::new({param_name});\n        \
             std::rc::Rc::new(std::cell::RefCell::new(bridge)) as {handle_path}\n    \
             }};"
        )
    };

    // Serde let bindings for non-bridge Named params
    let serde_bindings: String = func
        .params
        .iter()
        .enumerate()
        .filter(|(idx, p)| {
            if *idx == bridge_param_idx {
                return false;
            }
            let named = match &p.ty {
                TypeRef::Named(n) => Some(n.as_str()),
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(n) = inner.as_ref() {
                        Some(n.as_str())
                    } else {
                        None
                    }
                }
                _ => None,
            };
            named.is_some_and(|n| !opaque_types.contains(n))
        })
        .map(|(_, p)| {
            let name = &p.name;
            let core_path = format!(
                "{core_import}::{}",
                match &p.ty {
                    TypeRef::Named(n) => n.clone(),
                    TypeRef::Optional(inner) =>
                        if let TypeRef::Named(n) = inner.as_ref() {
                            n.clone()
                        } else {
                            String::new()
                        },
                    _ => String::new(),
                }
            );
            if p.optional || matches!(&p.ty, TypeRef::Optional(_)) {
                format!(
                    "let {name}_core: Option<{core_path}> = {name}.map(|v| {{\n        \
                     let json = serde_json::to_string(&v){err_conv}?;\n        \
                     serde_json::from_str(&json){err_conv}\n    \
                     }}).transpose()?;\n    "
                )
            } else {
                format!(
                    "let {name}_json = serde_json::to_string(&{name}){err_conv}?;\n    \
                     let {name}_core: {core_path} = serde_json::from_str(&{name}_json){err_conv}?;\n    "
                )
            }
        })
        .collect();

    // Build call args
    let call_args: Vec<String> = func
        .params
        .iter()
        .enumerate()
        .map(|(idx, p)| {
            if idx == bridge_param_idx {
                return p.name.clone();
            }
            match &p.ty {
                TypeRef::Named(n) if opaque_types.contains(n.as_str()) => {
                    if p.optional {
                        format!("{}.as_ref().map(|v| &v.inner)", p.name)
                    } else {
                        format!("&{}.inner", p.name)
                    }
                }
                TypeRef::Named(_) => format!("{}_core", p.name),
                TypeRef::Optional(inner) => {
                    if let TypeRef::Named(n) = inner.as_ref() {
                        if opaque_types.contains(n.as_str()) {
                            format!("{}.as_ref().map(|v| &v.inner)", p.name)
                        } else {
                            format!("{}_core", p.name)
                        }
                    } else {
                        p.name.clone()
                    }
                }
                TypeRef::String | TypeRef::Char => {
                    if p.is_ref {
                        format!("&{}", p.name)
                    } else {
                        p.name.clone()
                    }
                }
                _ => p.name.clone(),
            }
        })
        .collect();
    let call_args_str = call_args.join(", ");

    let core_fn_path = {
        let path = func.rust_path.replace('-', "_");
        if path.starts_with(core_import) {
            path
        } else {
            format!("{core_import}::{}", func.name)
        }
    };
    let core_call = format!("{core_fn_path}({call_args_str})");

    let return_wrap = match &func.return_type {
        TypeRef::Named(name) if opaque_types.contains(name.as_str()) => {
            format!("{name} {{ inner: std::sync::Arc::new(val) }}")
        }
        TypeRef::Named(_) => "val.into()".to_string(),
        TypeRef::String | TypeRef::Bytes => "val.into()".to_string(),
        _ => "val".to_string(),
    };

    let body = if func.error_type.is_some() {
        if return_wrap == "val" {
            format!("{bridge_wrap}\n    {serde_bindings}{core_call}{err_conv}")
        } else {
            format!("{bridge_wrap}\n    {serde_bindings}{core_call}.map(|val| {return_wrap}){err_conv}")
        }
    } else {
        format!("{bridge_wrap}\n    {serde_bindings}{core_call}")
    };

    let func_name = &func.name;
    let mut out = String::with_capacity(1024);
    if func.error_type.is_some() {
        writeln!(out, "#[allow(clippy::missing_errors_doc)]").ok();
    }
    writeln!(out, "pub fn {func_name}({params_str}) -> {ret} {{").ok();
    writeln!(out, "    {body}").ok();
    writeln!(out, "}}").ok();

    out
}