alef-backend-php 0.13.10

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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
mod functions;
mod helpers;
mod types;

use crate::type_map::PhpMapper;
use ahash::AHashSet;
use alef_codegen::builder::RustFileBuilder;
use alef_codegen::conversions::ConversionConfig;
use alef_codegen::generators::RustBindingConfig;
use alef_codegen::generators::{self, AsyncPattern};
use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
use alef_core::config::{AlefConfig, Language, detect_serde_available, resolve_output_dir};
use alef_core::hash::{self, CommentStyle};
use alef_core::ir::ApiSurface;
use alef_core::ir::{PrimitiveType, TypeRef};
use heck::{ToLowerCamelCase, ToPascalCase};
use std::path::PathBuf;

use functions::{gen_async_function_as_static_method, gen_function_as_static_method};
use helpers::{
    gen_enum_tainted_from_binding_to_core, gen_serde_bridge_from, gen_tokio_runtime, has_enum_named_field,
    references_named_type,
};
use types::{
    gen_enum_constants, gen_flat_data_enum, gen_flat_data_enum_from_impls, gen_flat_data_enum_methods,
    gen_opaque_struct_methods, gen_php_struct, is_tagged_data_enum,
};

pub struct PhpBackend;

impl PhpBackend {
    fn binding_config(core_import: &str, has_serde: bool) -> RustBindingConfig<'_> {
        RustBindingConfig {
            struct_attrs: &["php_class"],
            field_attrs: &[],
            struct_derives: &["Clone"],
            method_block_attr: Some("php_impl"),
            constructor_attr: "",
            static_attr: None,
            function_attr: "#[php_function]",
            enum_attrs: &[],
            enum_derives: &[],
            needs_signature: false,
            signature_prefix: "",
            signature_suffix: "",
            core_import,
            async_pattern: AsyncPattern::TokioBlockOn,
            has_serde,
            type_name_prefix: "",
            option_duration_on_defaults: true,
            opaque_type_names: &[],
        }
    }
}

impl Backend for PhpBackend {
    fn name(&self) -> &str {
        "php"
    }

    fn language(&self) -> Language {
        Language::Php
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities {
            supports_async: true,
            supports_classes: true,
            supports_enums: true,
            supports_option: true,
            supports_result: true,
            ..Capabilities::default()
        }
    }

    fn generate_bindings(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
        // Separate unit-variant enums (→ String) from tagged data enums (→ flat PHP class).
        let data_enum_names: AHashSet<String> = api
            .enums
            .iter()
            .filter(|e| is_tagged_data_enum(e))
            .map(|e| e.name.clone())
            .collect();
        let enum_names: AHashSet<String> = api
            .enums
            .iter()
            .filter(|e| !is_tagged_data_enum(e))
            .map(|e| e.name.clone())
            .collect();
        let mapper = PhpMapper {
            enum_names: enum_names.clone(),
            data_enum_names: data_enum_names.clone(),
        };
        let core_import = config.core_import();

        // Get exclusion lists from PHP config
        let php_config = config.php.as_ref();
        let exclude_functions = php_config.map(|c| c.exclude_functions.clone()).unwrap_or_default();
        let exclude_types = php_config.map(|c| c.exclude_types.clone()).unwrap_or_default();

        let output_dir = resolve_output_dir(
            config.output.php.as_ref(),
            &config.crate_config.name,
            "crates/{name}-php/src/",
        );
        let has_serde = detect_serde_available(&output_dir);
        let cfg = Self::binding_config(&core_import, has_serde);

        // Build the inner module content (types, methods, conversions)
        let mut builder = RustFileBuilder::new().with_generated_header();
        builder.add_inner_attribute("allow(dead_code, unused_imports, unused_variables)");
        builder.add_inner_attribute("allow(clippy::too_many_arguments, clippy::let_unit_value, clippy::needless_borrow, clippy::map_identity, clippy::just_underscores_and_digits, clippy::unnecessary_cast, clippy::unused_unit, clippy::unwrap_or_default, clippy::derivable_impls, clippy::needless_borrows_for_generic_args, clippy::unnecessary_fallible_conversions)");
        builder.add_import("ext_php_rs::prelude::*");

        // Import serde_json when available (needed for serde-based param conversion)
        if has_serde {
            builder.add_import("serde_json");
        }

        // Import traits needed for trait method dispatch
        for trait_path in generators::collect_trait_imports(api) {
            builder.add_import(&trait_path);
        }

        // Only import HashMap when Map-typed fields or returns are present
        let has_maps = api.types.iter().any(|t| {
            t.fields
                .iter()
                .any(|f| matches!(&f.ty, alef_core::ir::TypeRef::Map(_, _)))
        }) || api
            .functions
            .iter()
            .any(|f| matches!(&f.return_type, alef_core::ir::TypeRef::Map(_, _)));
        if has_maps {
            builder.add_import("std::collections::HashMap");
        }

        // Custom module declarations
        let custom_mods = config.custom_modules.for_language(Language::Php);
        for module in custom_mods {
            builder.add_item(&format!("pub mod {module};"));
        }

        // Check if any function or method is async
        let has_async =
            api.functions.iter().any(|f| f.is_async) || api.types.iter().any(|t| t.methods.iter().any(|m| m.is_async));

        if has_async {
            builder.add_item(&gen_tokio_runtime());
        }

        // Check if we have opaque types and add Arc import if needed
        let opaque_types: AHashSet<String> = api
            .types
            .iter()
            .filter(|t| t.is_opaque)
            .map(|t| t.name.clone())
            .collect();
        if !opaque_types.is_empty() {
            builder.add_import("std::sync::Arc");
        }
        // Sorted vec so gen_struct_with_per_field_attrs can emit #[serde(skip)] on
        // fields whose type is an opaque handle (e.g. VisitorHandle), preventing compile
        // errors when the struct derives serde::Serialize/Deserialize.
        let opaque_type_names_vec: Vec<String> = {
            let mut v: Vec<String> = opaque_types.iter().cloned().collect();
            v.sort();
            v
        };

        // Compute the PHP namespace for namespaced class registration.
        // Delegates to config so [php].namespace overrides are respected.
        let extension_name = config.php_extension_name();
        let php_namespace = config.php_autoload_namespace();

        // Build adapter body map before type iteration so bodies are available for method generation.
        let adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Php)?;

        // Emit adapter-generated standalone items (streaming iterators, callback bridges).
        for adapter in &config.adapters {
            match adapter.pattern {
                alef_core::config::AdapterPattern::Streaming => {
                    let key = format!("{}.__stream_struct__", adapter.item_type.as_deref().unwrap_or(""));
                    if let Some(struct_code) = adapter_bodies.get(&key) {
                        builder.add_item(struct_code);
                    }
                }
                alef_core::config::AdapterPattern::CallbackBridge => {
                    let struct_key = format!("{}.__bridge_struct__", adapter.name);
                    let impl_key = format!("{}.__bridge_impl__", adapter.name);
                    if let Some(struct_code) = adapter_bodies.get(&struct_key) {
                        builder.add_item(struct_code);
                    }
                    if let Some(impl_code) = adapter_bodies.get(&impl_key) {
                        builder.add_item(impl_code);
                    }
                }
                _ => {}
            }
        }

        for typ in api
            .types
            .iter()
            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
        {
            if typ.is_opaque {
                // Generate the opaque struct with separate #[php_class] and
                // #[php(name = "Ns\\Type")] attributes (ext-php-rs 0.15+ syntax).
                // Escape '\' in the namespace so the generated Rust string literal is valid.
                let ns_escaped = php_namespace.replace('\\', "\\\\");
                let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped, typ.name);
                let opaque_attr_arr = ["php_class", php_name_attr.as_str()];
                let opaque_cfg = RustBindingConfig {
                    struct_attrs: &opaque_attr_arr,
                    ..cfg
                };
                builder.add_item(&generators::gen_opaque_struct(typ, &opaque_cfg));
                builder.add_item(&gen_opaque_struct_methods(
                    typ,
                    &mapper,
                    &opaque_types,
                    &core_import,
                    &adapter_bodies,
                ));
            } else {
                // gen_struct adds #[derive(Default)] when typ.has_default is true,
                // so no separate Default impl is needed.
                // Pass opaque_type_names so gen_struct_with_per_field_attrs can add
                // #[serde(skip)] to fields whose type is an opaque handle (e.g. VisitorHandle).
                let struct_cfg = RustBindingConfig {
                    opaque_type_names: &opaque_type_names_vec,
                    ..cfg
                };
                builder.add_item(&gen_php_struct(
                    typ,
                    &mapper,
                    &struct_cfg,
                    Some(&php_namespace),
                    &enum_names,
                ));
                builder.add_item(&types::gen_struct_methods_with_exclude(
                    typ,
                    &mapper,
                    has_serde,
                    &core_import,
                    &opaque_types,
                    &enum_names,
                    &api.enums,
                    &exclude_functions,
                ));
            }
        }

        for enum_def in &api.enums {
            if is_tagged_data_enum(enum_def) {
                // Tagged data enums (struct variants) are lowered to a flat PHP class.
                builder.add_item(&gen_flat_data_enum(enum_def, &mapper, Some(&php_namespace)));
                builder.add_item(&gen_flat_data_enum_methods(enum_def, &mapper));
            } else {
                builder.add_item(&gen_enum_constants(enum_def));
            }
        }

        // Generate free functions as static methods on a facade class rather than standalone
        // `#[php_function]` items. Standalone functions rely on the `inventory` crate for
        // auto-registration, which does not work in cdylib builds on macOS. Classes registered
        // via `.class::<T>()` in the module builder DO work on all platforms.
        let included_functions: Vec<_> = api
            .functions
            .iter()
            .filter(|f| !exclude_functions.contains(&f.name))
            .collect();
        if !included_functions.is_empty() {
            let facade_class_name = extension_name.to_pascal_case();
            // Build each static method body (no #[php_function] attribute — they live inside
            // a #[php_impl] block which handles registration via the class machinery).
            let mut method_items: Vec<String> = Vec::new();
            for func in included_functions {
                let bridge_param = crate::trait_bridge::find_bridge_param(func, &config.trait_bridges);
                let bridge_field = crate::trait_bridge::find_bridge_field(func, &api.types, &config.trait_bridges);
                if let Some((param_idx, bridge_cfg)) = bridge_param {
                    method_items.push(crate::trait_bridge::gen_bridge_function(
                        func,
                        param_idx,
                        bridge_cfg,
                        &mapper,
                        &opaque_types,
                        &core_import,
                    ));
                } else if let Some(ref field_match) = bridge_field {
                    method_items.push(crate::trait_bridge::gen_bridge_field_function(
                        func,
                        field_match,
                        &mapper,
                        &opaque_types,
                        &core_import,
                    ));
                } else if func.is_async {
                    method_items.push(gen_async_function_as_static_method(
                        func,
                        &mapper,
                        &opaque_types,
                        &core_import,
                        &config.trait_bridges,
                    ));
                } else {
                    method_items.push(gen_function_as_static_method(
                        func,
                        &mapper,
                        &opaque_types,
                        &core_import,
                        &config.trait_bridges,
                        has_serde,
                    ));
                }
            }

            let methods_joined = method_items
                .iter()
                .map(|m| {
                    // Indent each line of each method by 4 spaces
                    m.lines()
                        .map(|l| {
                            if l.is_empty() {
                                String::new()
                            } else {
                                format!("    {l}")
                            }
                        })
                        .collect::<Vec<_>>()
                        .join("\n")
                })
                .collect::<Vec<_>>()
                .join("\n\n");
            // The PHP-visible class name gets an "Api" suffix to avoid collision with the
            // PHP facade class (e.g. `Kreuzcrawl\Kreuzcrawl`) that Composer autoloads.
            let php_api_class_name = format!("{facade_class_name}Api");
            // Escape '\' so the generated Rust string literal is valid (e.g. "Ns\\ClassName").
            let ns_escaped_facade = php_namespace.replace('\\', "\\\\");
            let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped_facade, php_api_class_name);
            let facade_struct = format!(
                "#[php_class]\n#[{php_name_attr}]\npub struct {facade_class_name}Api;\n\n#[php_impl]\nimpl {facade_class_name}Api {{\n{methods_joined}\n}}"
            );
            builder.add_item(&facade_struct);

            // Trait bridge structs — top-level items (outside the facade class)
            for bridge_cfg in &config.trait_bridges {
                if let Some(trait_type) = api.types.iter().find(|t| t.is_trait && t.name == bridge_cfg.trait_name) {
                    let bridge = crate::trait_bridge::gen_trait_bridge(
                        trait_type,
                        bridge_cfg,
                        &core_import,
                        &config.error_type(),
                        &config.error_constructor(),
                        api,
                    );
                    for imp in &bridge.imports {
                        builder.add_import(imp);
                    }
                    builder.add_item(&bridge.code);
                }
            }
        }

        let convertible = alef_codegen::conversions::convertible_types(api);
        let core_to_binding = alef_codegen::conversions::core_to_binding_convertible_types(api);
        let input_types = alef_codegen::conversions::input_type_names(api);
        // From/Into conversions with PHP-specific i64 casts.
        // Types with enum Named fields (or that reference such types transitively) can't
        // have binding->core From impls because PHP maps enums to String and there's no
        // From<String> for the core enum type. Core->binding is always safe.
        let enum_names_ref = &mapper.enum_names;
        let php_conv_config = ConversionConfig {
            cast_large_ints_to_i64: true,
            enum_string_names: Some(enum_names_ref),
            json_to_string: true,
            include_cfg_metadata: false,
            option_duration_on_defaults: true,
            ..Default::default()
        };
        // Build transitive set of types that can't have binding->core From
        let mut enum_tainted: AHashSet<String> = AHashSet::new();
        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
            if has_enum_named_field(typ, enum_names_ref) {
                enum_tainted.insert(typ.name.clone());
            }
        }
        // Transitively mark types that reference enum-tainted types
        let mut changed = true;
        while changed {
            changed = false;
            for typ in api.types.iter().filter(|typ| !typ.is_trait) {
                if !enum_tainted.contains(&typ.name)
                    && typ.fields.iter().any(|f| references_named_type(&f.ty, &enum_tainted))
                {
                    enum_tainted.insert(typ.name.clone());
                    changed = true;
                }
            }
        }
        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
            // binding->core: only when not enum-tainted and type is used as input
            if input_types.contains(&typ.name)
                && !enum_tainted.contains(&typ.name)
                && alef_codegen::conversions::can_generate_conversion(typ, &convertible)
            {
                builder.add_item(&alef_codegen::conversions::gen_from_binding_to_core_cfg(
                    typ,
                    &core_import,
                    &php_conv_config,
                ));
            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) && has_serde {
                // Enum-tainted types can't use field-by-field From (no From<String> for core enum),
                // but when serde is available we bridge via JSON serialization round-trip.
                builder.add_item(&gen_serde_bridge_from(typ, &core_import));
            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) {
                // Enum-tainted types: generate From with string->enum parsing for enum-Named
                // fields, using first variant as fallback. Data-variant enum fields fill
                // data fields with Default::default().
                builder.add_item(&gen_enum_tainted_from_binding_to_core(
                    typ,
                    &core_import,
                    enum_names_ref,
                    &enum_tainted,
                    &php_conv_config,
                    &api.enums,
                ));
            }
            // core->binding: always (enum->String via format, sanitized fields via format)
            if alef_codegen::conversions::can_generate_conversion(typ, &core_to_binding) {
                builder.add_item(&alef_codegen::conversions::gen_from_core_to_binding_cfg(
                    typ,
                    &core_import,
                    &opaque_types,
                    &php_conv_config,
                ));
            }
        }

        // From impls for tagged data enums lowered to flat PHP classes.
        for enum_def in api.enums.iter().filter(|e| is_tagged_data_enum(e)) {
            builder.add_item(&gen_flat_data_enum_from_impls(enum_def, &core_import));
        }

        // Error converter functions
        for error in &api.errors {
            builder.add_item(&alef_codegen::error_gen::gen_php_error_converter(error, &core_import));
        }

        // Always enable abi_vectorcall on Windows — ext-php-rs requires the
        // `vectorcall` calling convention for PHP entry points there. The feature
        // is unstable on stable Rust; consumers either build with nightly or set
        // RUSTC_BOOTSTRAP=1 (the upstream-recommended workaround). This cfg_attr
        // is a no-op on non-windows so it costs nothing on Linux/macOS builds.
        let php_config = config.php.as_ref();
        builder.add_inner_attribute("cfg_attr(windows, feature(abi_vectorcall))");

        // Optional feature gate — when [php].feature_gate is set, the entire crate
        // is conditionally compiled. Use this for parity with PyO3's `extension-module`
        // pattern; most PHP bindings don't need it.
        if let Some(feature_name) = php_config.and_then(|c| c.feature_gate.as_deref()) {
            builder.add_inner_attribute(&format!("cfg(feature = \"{feature_name}\")"));
        }

        // PHP module entry point — explicit class registration required because
        // `inventory` crate auto-registration doesn't work in cdylib on macOS.
        let mut class_registrations = String::new();
        for typ in api
            .types
            .iter()
            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
        {
            class_registrations.push_str(&format!("\n    .class::<{}>()", typ.name));
        }
        // Register the facade class that wraps free functions as static methods.
        if !api.functions.is_empty() {
            let facade_class_name = extension_name.to_pascal_case();
            class_registrations.push_str(&format!("\n    .class::<{facade_class_name}Api>()"));
        }
        // Tagged data enums are lowered to flat PHP classes — register them like other classes.
        // Unit-variant enums remain as string constants and don't need .class::<T>() registration.
        for enum_def in api.enums.iter().filter(|e| is_tagged_data_enum(e)) {
            class_registrations.push_str(&format!("\n    .class::<{}>()", enum_def.name));
        }
        builder.add_item(&format!(
            "#[php_module]\npub fn get_module(module: ModuleBuilder) -> ModuleBuilder {{\n    module{class_registrations}\n}}"
        ));

        let content = builder.build();

        Ok(vec![GeneratedFile {
            path: PathBuf::from(&output_dir).join("lib.rs"),
            content,
            generated_header: false,
        }])
    }

    fn generate_scaffold(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
        // Generate a global-namespace convenience functions file (`functions.php`) that wraps
        // the first public API function under a short global name (e.g. `html_to_markdown_convert`).
        // This file is registered under `autoload.files` in composer.json so it is loaded
        // automatically; the implementations delegate to the PSR-4 facade class.
        //
        // The namespace is read from config (via `php_autoload_namespace`) so it always stays
        // in sync with the `[php].namespace` / `[php].extension_name` settings in alef.toml,
        // instead of being derived by mechanical case-splitting at the call site.
        if api.functions.is_empty() {
            return Ok(vec![]);
        }
        let extension_name = config.php_extension_name();
        let class_name = extension_name.to_pascal_case();
        let namespace = config.php_autoload_namespace();

        // Use PHP stubs output path if configured, otherwise fall back to packages/php/src/.
        let output_dir = config
            .php
            .as_ref()
            .and_then(|p| p.stubs.as_ref())
            .map(|s| s.output.to_string_lossy().to_string())
            .unwrap_or_else(|| "packages/php/src/".to_string());

        let mut content = String::from("<?php\n\n");
        content.push_str(&hash::header(CommentStyle::DoubleSlash));
        content.push_str("declare(strict_types=1);\n\n");
        // Emit a bracketed global-namespace block so that PSR-4 `use` imports work correctly
        // alongside the inline class alias import.
        content.push_str("namespace {\n\n");
        content.push_str(&format!("    use {}\\{};\n\n", namespace, class_name));

        for func in &api.functions {
            // Skip functions that are not suitable for a simple global wrapper
            // (async, void returns, or functions with more than two params).
            if func.is_async {
                continue;
            }
            let global_fn_name = format!("{}_{}", extension_name, func.name);
            let return_php_type = php_type(&func.return_type);
            let is_void = return_php_type == "void";

            // Build PHPDoc and param list for visible params only.
            let bridge_param_names: ahash::AHashSet<&str> = config
                .trait_bridges
                .iter()
                .filter_map(|b| b.param_name.as_deref())
                .collect();
            let visible_params: Vec<_> = func
                .params
                .iter()
                .filter(|p| !bridge_param_names.contains(p.name.as_str()))
                .collect();

            content.push_str(&format!("    if (!\\function_exists('{}')) {{\n", global_fn_name));
            content.push_str("        /**\n");
            for line in func.doc.lines() {
                if line.is_empty() {
                    content.push_str("         *\n");
                } else {
                    content.push_str(&format!("         * {}\n", line));
                }
            }
            if func.doc.is_empty() {
                content.push_str(&format!("         * {}.\n", global_fn_name));
            }
            content.push_str("         *\n");
            for p in &visible_params {
                let ptype = php_phpdoc_type(&p.ty);
                let nullable_prefix = if p.optional { "?" } else { "" };
                content.push_str(&format!("         * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
            }
            let return_phpdoc = php_phpdoc_type(&func.return_type);
            content.push_str(&format!("         * @return {}\n", return_phpdoc));
            if func.error_type.is_some() {
                content.push_str(&format!(
                    "         * @throws \\{}\\{}Exception\n",
                    namespace, class_name
                ));
            }
            content.push_str("         */\n");

            let mut sorted_params = visible_params.clone();
            sorted_params.sort_by_key(|p| p.optional);
            let params_str: Vec<String> = sorted_params
                .iter()
                .map(|p| {
                    let ptype = php_type(&p.ty);
                    if p.optional {
                        format!("?{} ${} = null", ptype, p.name)
                    } else {
                        format!("{} ${}", ptype, p.name)
                    }
                })
                .collect();
            let method_name = func.name.to_lower_camel_case();
            let call_args: Vec<String> = sorted_params.iter().map(|p| format!("${}", p.name)).collect();
            let call_expr = format!("{}::{}({})", class_name, method_name, call_args.join(", "));
            content.push_str(&format!(
                "        function {}({}): {} {{\n",
                global_fn_name,
                params_str.join(", "),
                return_php_type
            ));
            if is_void {
                content.push_str(&format!("            {};\n", call_expr));
            } else {
                content.push_str(&format!("            return {};\n", call_expr));
            }
            content.push_str("        }\n");
            content.push_str("    }\n\n");
        }

        content.push_str("} // end namespace\n");

        Ok(vec![GeneratedFile {
            path: PathBuf::from(&output_dir).join("functions.php"),
            content,
            generated_header: false,
        }])
    }

    fn generate_public_api(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
        let extension_name = config.php_extension_name();
        let class_name = extension_name.to_pascal_case();

        // Generate PHP wrapper class
        let mut content = String::from("<?php\n\n");
        content.push_str(&hash::header(CommentStyle::DoubleSlash));
        content.push_str("declare(strict_types=1);\n\n");

        // Determine namespace — delegates to config so [php].namespace overrides are respected.
        let namespace = config.php_autoload_namespace();

        content.push_str(&format!("namespace {};\n\n", namespace));
        content.push_str(&format!("final class {}\n", class_name));
        content.push_str("{\n");

        // Build the set of bridge param names so they are excluded from public PHP signatures.
        let bridge_param_names_pub: ahash::AHashSet<&str> = config
            .trait_bridges
            .iter()
            .filter_map(|b| b.param_name.as_deref())
            .collect();

        // Build a lookup from function name → BridgeFieldMatch for options-field bridges.
        // These functions need an extra PHP arg ($options->field) forwarded to the native ext.
        let bridge_field_funcs_pub: std::collections::HashMap<&str, crate::trait_bridge::BridgeFieldMatch<'_>> = api
            .functions
            .iter()
            .filter_map(|func| {
                crate::trait_bridge::find_bridge_field(func, &api.types, &config.trait_bridges)
                    .map(|m| (func.name.as_str(), m))
            })
            .collect();

        // Generate wrapper methods for functions
        for func in &api.functions {
            let method_name = func.name.to_lower_camel_case();
            let return_php_type = php_type(&func.return_type);

            // Visible params exclude bridge params (not surfaced to PHP callers).
            let visible_params: Vec<_> = func
                .params
                .iter()
                .filter(|p| !bridge_param_names_pub.contains(p.name.as_str()))
                .collect();

            // PHPDoc block
            content.push_str("    /**\n");
            for line in func.doc.lines() {
                if line.is_empty() {
                    content.push_str("     *\n");
                } else {
                    content.push_str(&format!("     * {}\n", line));
                }
            }
            if func.doc.is_empty() {
                content.push_str(&format!("     * {}.\n", method_name));
            }
            content.push_str("     *\n");
            for p in &visible_params {
                let ptype = php_phpdoc_type(&p.ty);
                let nullable_prefix = if p.optional { "?" } else { "" };
                content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
            }
            let return_phpdoc = php_phpdoc_type(&func.return_type);
            content.push_str(&format!("     * @return {}\n", return_phpdoc));
            if func.error_type.is_some() {
                content.push_str(&format!("     * @throws \\{}\\{}Exception\n", namespace, class_name));
            }
            content.push_str("     */\n");

            // Method signature with type hints.
            // PHP requires required parameters before optional ones, so stable-sort
            // visible_params: required first, then optional (preserving relative order).
            let mut sorted_visible_params = visible_params.clone();
            sorted_visible_params.sort_by_key(|p| p.optional);

            content.push_str(&format!("    public static function {}(", method_name));

            let params: Vec<String> = sorted_visible_params
                .iter()
                .map(|p| {
                    let ptype = php_type(&p.ty);
                    if p.optional {
                        format!("?{} ${} = null", ptype, p.name)
                    } else {
                        format!("{} ${}", ptype, p.name)
                    }
                })
                .collect();
            content.push_str(&params.join(", "));
            content.push_str(&format!("): {}\n", return_php_type));
            content.push_str("    {\n");
            // Async functions are registered in the extension with an `_async` suffix
            // (see gen_async_function which generates `pub fn {name}_async`).
            // Delegate to the native extension class (registered as `{namespace}\{class_name}Api`).
            // ext-php-rs auto-converts Rust snake_case to PHP camelCase
            let ext_method_name = if func.is_async {
                format!("{}_async", func.name).to_lower_camel_case()
            } else {
                func.name.to_lower_camel_case()
            };
            let is_void = matches!(&func.return_type, TypeRef::Unit);
            // Build the call argument list. For options-field bridge functions, append the
            // bridge field value from the options object (e.g., `$options->visitor`) so the
            // native extension receives it as the extra hidden `{field}_obj` parameter.
            let mut call_arg_parts: Vec<String> =
                sorted_visible_params.iter().map(|p| format!("${}", p.name)).collect();
            if let Some(bfm) = bridge_field_funcs_pub.get(func.name.as_str()) {
                let opts_param_name = &func.params[bfm.param_index].name;
                // Use the null-safe `?->` operator when the options parameter is optional so
                // that PHPStan does not report "Cannot access property on null" when the caller
                // passes `null` for the options argument.
                let access_op = if bfm.param_is_optional { "?->" } else { "->" };
                call_arg_parts.push(format!("${}{}{}", opts_param_name, access_op, bfm.field_name));
            }
            let call_expr = format!(
                "\\{}\\{}Api::{}({})",
                namespace,
                class_name,
                ext_method_name,
                call_arg_parts.join(", ")
            );
            if is_void {
                content.push_str(&format!(
                    "        {}; // delegate to native extension class\n",
                    call_expr
                ));
            } else {
                content.push_str(&format!(
                    "        return {}; // delegate to native extension class\n",
                    call_expr
                ));
            }
            content.push_str("    }\n\n");
        }

        content.push_str("}\n");

        // Use PHP stubs output path if configured, otherwise fall back to packages/php/src/.
        // This is intentionally separate from config.output.php, which controls the Rust binding
        // crate output directory (e.g., crates/kreuzcrawl-php/src/).
        let output_dir = config
            .php
            .as_ref()
            .and_then(|p| p.stubs.as_ref())
            .map(|s| s.output.to_string_lossy().to_string())
            .unwrap_or_else(|| "packages/php/src/".to_string());

        Ok(vec![GeneratedFile {
            path: PathBuf::from(&output_dir).join(format!("{}.php", class_name)),
            content,
            generated_header: false,
        }])
    }

    fn generate_type_stubs(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
        let extension_name = config.php_extension_name();
        let class_name = extension_name.to_pascal_case();

        // Determine namespace — delegates to config so [php].namespace overrides are respected.
        let namespace = config.php_autoload_namespace();

        // Build (type_name, field_name) → PHP bridge class name overrides for options-field bridges.
        let mut bridge_field_overrides: std::collections::HashMap<(String, String), String> =
            std::collections::HashMap::new();
        for bridge_cfg in &config.trait_bridges {
            if bridge_cfg.bind_via != alef_core::config::BridgeBinding::OptionsField {
                continue;
            }
            if let Some(options_type) = bridge_cfg.options_type.as_deref() {
                let field_name = bridge_cfg
                    .resolved_options_field()
                    .unwrap_or(bridge_cfg.trait_name.as_str())
                    .to_string();
                let bridge_class = bridge_cfg
                    .type_alias
                    .as_deref()
                    .unwrap_or(bridge_cfg.trait_name.as_str())
                    .to_string();
                bridge_field_overrides.insert((options_type.to_string(), field_name), bridge_class);
            }
        }

        // Build set of bridge-field function names for stub generation.
        let bridge_field_funcs_stubs: std::collections::HashMap<&str, crate::trait_bridge::BridgeFieldMatch<'_>> = api
            .functions
            .iter()
            .filter_map(|func| {
                crate::trait_bridge::find_bridge_field(func, &api.types, &config.trait_bridges)
                    .map(|m| (func.name.as_str(), m))
            })
            .collect();

        // PSR-12 requires a blank line after the opening `<?php` tag.
        // php-cs-fixer enforces this and would insert it post-write,
        // making `alef verify` see content that differs from what was
        // freshly generated. Emit it here so generated == on-disk.
        let mut content = String::from("<?php\n\n");
        content.push_str(&hash::header(CommentStyle::DoubleSlash));
        content.push_str("// Type stubs for the native PHP extension — declares classes\n");
        content.push_str("// provided at runtime by the compiled Rust extension (.so/.dll).\n");
        content.push_str("// Include this in phpstan.neon scanFiles for static analysis.\n\n");
        content.push_str("declare(strict_types=1);\n\n");
        // Use bracketed namespace syntax so we can add global-namespace function stubs later.
        content.push_str(&format!("namespace {} {{\n\n", namespace));

        // Exception class
        content.push_str(&format!(
            "class {}Exception extends \\RuntimeException\n{{\n",
            class_name
        ));
        content.push_str(
            "    public function getErrorCode(): int { throw new \\RuntimeException('Not implemented.'); }\n",
        );
        content.push_str("}\n\n");

        // Opaque handle classes
        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
            if typ.is_opaque {
                if !typ.doc.is_empty() {
                    content.push_str("/**\n");
                    for line in typ.doc.lines() {
                        if line.is_empty() {
                            content.push_str(" *\n");
                        } else {
                            content.push_str(&format!(" * {}\n", line));
                        }
                    }
                    content.push_str(" */\n");
                }
                content.push_str(&format!("class {}\n{{\n", typ.name));
                // Opaque handles have no public constructors in PHP
                content.push_str("}\n\n");
            }
        }

        // Record / struct types (non-opaque with fields)
        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
            if typ.is_opaque || typ.fields.is_empty() {
                continue;
            }
            if !typ.doc.is_empty() {
                content.push_str("/**\n");
                for line in typ.doc.lines() {
                    if line.is_empty() {
                        content.push_str(" *\n");
                    } else {
                        content.push_str(&format!(" * {}\n", line));
                    }
                }
                content.push_str(" */\n");
            }
            content.push_str(&format!("class {}\n{{\n", typ.name));

            // Public property declarations (ext-php-rs exposes struct fields as properties)
            for field in &typ.fields {
                // Check if this field is overridden by an options-field bridge config.
                let override_key = (typ.name.clone(), field.name.clone());
                if let Some(bridge_class) = bridge_field_overrides.get(&override_key) {
                    content.push_str(&format!("    public ?{} ${};\n", bridge_class, field.name));
                    continue;
                }
                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
                let prop_type = if field.optional {
                    let inner = php_type(&field.ty);
                    if inner.starts_with('?') {
                        inner
                    } else {
                        format!("?{inner}")
                    }
                } else {
                    php_type(&field.ty)
                };
                if is_array {
                    let phpdoc = php_phpdoc_type(&field.ty);
                    let nullable_prefix = if field.optional { "?" } else { "" };
                    content.push_str(&format!("    /** @var {}{} */\n", nullable_prefix, phpdoc));
                }
                content.push_str(&format!("    public {} ${};\n", prop_type, field.name));
            }
            content.push('\n');

            // Constructor with typed parameters.
            // PHP requires required parameters to come before optional ones, so sort
            // the fields: required first, then optional (preserving relative order within each group).
            let mut sorted_fields: Vec<&alef_core::ir::FieldDef> = typ.fields.iter().collect();
            sorted_fields.sort_by_key(|f| f.optional);

            // Emit PHPDoc before the constructor for any array-typed fields so PHPStan
            // understands the generic element type (e.g. `@param array<string> $items`).
            let array_fields: Vec<&alef_core::ir::FieldDef> = sorted_fields
                .iter()
                .copied()
                .filter(|f| matches!(&f.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)))
                .collect();
            if !array_fields.is_empty() {
                content.push_str("    /**\n");
                for f in &array_fields {
                    let phpdoc = php_phpdoc_type(&f.ty);
                    let nullable_prefix = if f.optional { "?" } else { "" };
                    content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, phpdoc, f.name));
                }
                content.push_str("     */\n");
            }

            let params: Vec<String> = sorted_fields
                .iter()
                .map(|f| {
                    let override_key = (typ.name.clone(), f.name.clone());
                    if let Some(bridge_class) = bridge_field_overrides.get(&override_key) {
                        return format!("        ?{} ${} = null", bridge_class, f.name);
                    }
                    let ptype = php_type(&f.ty);
                    let nullable = if f.optional && !ptype.starts_with('?') {
                        format!("?{ptype}")
                    } else {
                        ptype
                    };
                    let default = if f.optional { " = null" } else { "" };
                    format!("        {} ${}{}", nullable, f.name, default)
                })
                .collect();
            content.push_str("    public function __construct(\n");
            content.push_str(&params.join(",\n"));
            content.push_str("\n    ) { }\n\n");

            // Getter methods for each field
            for field in &typ.fields {
                let getter_name = field.name.to_lower_camel_case();
                let override_key = (typ.name.clone(), field.name.clone());
                if let Some(bridge_class) = bridge_field_overrides.get(&override_key) {
                    content.push_str(&format!(
                        "    public function get{}(): ?{} {{ throw new \\RuntimeException('Not implemented.'); }}\n",
                        getter_name.to_pascal_case(),
                        bridge_class
                    ));
                    continue;
                }
                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
                let return_type = if field.optional {
                    let inner = php_type(&field.ty);
                    if inner.starts_with('?') {
                        inner
                    } else {
                        format!("?{inner}")
                    }
                } else {
                    php_type(&field.ty)
                };
                // Emit PHPDoc for array return types so PHPStan knows the element type.
                if is_array {
                    let phpdoc = php_phpdoc_type(&field.ty);
                    let nullable_prefix = if field.optional { "?" } else { "" };
                    content.push_str(&format!("    /** @return {}{} */\n", nullable_prefix, phpdoc));
                }
                let is_void_getter = return_type == "void";
                let getter_body = if is_void_getter {
                    "{ }".to_string()
                } else {
                    "{ throw new \\RuntimeException('Not implemented.'); }".to_string()
                };
                content.push_str(&format!(
                    "    public function get{}(): {} {getter_body}\n",
                    getter_name.to_pascal_case(),
                    return_type
                ));
            }

            content.push_str("}\n\n");
        }

        // Enum constants (PHP 8.1+ enums)
        for enum_def in &api.enums {
            content.push_str(&format!("enum {}: string\n{{\n", enum_def.name));
            for variant in &enum_def.variants {
                content.push_str(&format!("    case {} = '{}';\n", variant.name, variant.name));
            }
            content.push_str("}\n\n");
        }

        // Extension function stubs — generated as a native `{ClassName}Api` class with static
        // methods. The PHP facade (`{ClassName}`) delegates to `{ClassName}Api::method()`.
        // Using a class instead of global functions avoids the `inventory` crate registration
        // issue on macOS (cdylib builds do not collect `#[php_function]` entries there).
        if !api.functions.is_empty() {
            // Bridge params are hidden from the PHP-visible API in stubs too.
            let bridge_param_names_stubs: ahash::AHashSet<&str> = config
                .trait_bridges
                .iter()
                .filter_map(|b| b.param_name.as_deref())
                .collect();

            content.push_str(&format!("class {}Api\n{{\n", class_name));
            for func in &api.functions {
                let return_type = php_type_fq(&func.return_type, &namespace);
                let return_phpdoc = php_phpdoc_type_fq(&func.return_type, &namespace);
                // Visible params exclude bridge params.
                let visible_params: Vec<_> = func
                    .params
                    .iter()
                    .filter(|p| !bridge_param_names_stubs.contains(p.name.as_str()))
                    .collect();
                // PHP requires required parameters before optional ones — stable sort.
                let mut sorted_visible_params = visible_params.clone();
                sorted_visible_params.sort_by_key(|p| p.optional);
                // Emit PHPDoc when any param or the return type is an array, so PHPStan
                // understands generic element types (e.g. array<string> vs bare array).
                let has_array_params = visible_params
                    .iter()
                    .any(|p| matches!(&p.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)));
                let has_array_return = matches!(&func.return_type, TypeRef::Vec(_) | TypeRef::Map(_, _))
                    || matches!(&func.return_type, TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(_) | TypeRef::Map(_, _)));
                if has_array_params || has_array_return {
                    content.push_str("    /**\n");
                    for p in &visible_params {
                        let ptype = php_phpdoc_type_fq(&p.ty, &namespace);
                        let nullable_prefix = if p.optional { "?" } else { "" };
                        content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
                    }
                    content.push_str(&format!("     * @return {}\n", return_phpdoc));
                    content.push_str("     */\n");
                }
                let mut params: Vec<String> = sorted_visible_params
                    .iter()
                    .map(|p| {
                        let ptype = php_type_fq(&p.ty, &namespace);
                        if p.optional {
                            format!("?{} ${} = null", ptype, p.name)
                        } else {
                            format!("{} ${}", ptype, p.name)
                        }
                    })
                    .collect();
                // Bridge-field functions expose an extra visitor param in the native extension.
                if let Some(bfm) = bridge_field_funcs_stubs.get(func.name.as_str()) {
                    let bridge_class = bfm
                        .bridge
                        .type_alias
                        .as_deref()
                        .unwrap_or(bfm.bridge.trait_name.as_str());
                    params.push(format!("?{} ${}_obj = null", bridge_class, bfm.field_name));
                }
                // ext-php-rs auto-converts Rust snake_case to PHP camelCase.
                let stub_method_name = if func.is_async {
                    format!("{}_async", func.name).to_lower_camel_case()
                } else {
                    func.name.to_lower_camel_case()
                };
                let is_void_stub = return_type == "void";
                let stub_body = if is_void_stub {
                    "{ }".to_string()
                } else {
                    "{ throw new \\RuntimeException('Not implemented.'); }".to_string()
                };
                content.push_str(&format!(
                    "    public static function {}({}): {} {stub_body}\n",
                    stub_method_name,
                    params.join(", "),
                    return_type
                ));
            }
            content.push_str("}\n\n");
        }

        // Close the namespaced block
        content.push_str("} // end namespace\n");

        // Use stubs output path if configured, otherwise packages/php/stubs/
        let output_dir = config
            .php
            .as_ref()
            .and_then(|p| p.stubs.as_ref())
            .map(|s| s.output.to_string_lossy().to_string())
            .unwrap_or_else(|| "packages/php/stubs/".to_string());

        Ok(vec![GeneratedFile {
            path: PathBuf::from(&output_dir).join(format!("{}_extension.php", extension_name)),
            content,
            generated_header: false,
        }])
    }

    fn build_config(&self) -> Option<BuildConfig> {
        Some(BuildConfig {
            tool: "cargo",
            crate_suffix: "-php",
            build_dep: BuildDependency::None,
            post_build: vec![],
        })
    }
}

/// Map an IR [`TypeRef`] to a PHPDoc type string with generic parameters (e.g., `array<string>`).
/// PHPStan at level `max` requires iterable value types in PHPDoc annotations.
fn php_phpdoc_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type(inner)),
        TypeRef::Map(k, v) => format!("array<{}, {}>", php_phpdoc_type(k), php_phpdoc_type(v)),
        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type(inner)),
        _ => php_type(ty),
    }
}

/// Map an IR [`TypeRef`] to a fully-qualified PHPDoc type string with generics (e.g., `array<\Ns\T>`).
fn php_phpdoc_type_fq(ty: &TypeRef, namespace: &str) -> String {
    match ty {
        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type_fq(inner, namespace)),
        TypeRef::Map(k, v) => format!(
            "array<{}, {}>",
            php_phpdoc_type_fq(k, namespace),
            php_phpdoc_type_fq(v, namespace)
        ),
        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type_fq(inner, namespace)),
        _ => php_type(ty),
    }
}

/// Map an IR [`TypeRef`] to a fully-qualified PHP type-hint string for use outside the namespace.
fn php_type_fq(ty: &TypeRef, namespace: &str) -> String {
    match ty {
        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
        TypeRef::Optional(inner) => {
            let inner_type = php_type_fq(inner, namespace);
            if inner_type.starts_with('?') {
                inner_type
            } else {
                format!("?{inner_type}")
            }
        }
        _ => php_type(ty),
    }
}

/// Map an IR [`TypeRef`] to a PHP type-hint string.
fn php_type(ty: &TypeRef) -> String {
    match ty {
        TypeRef::String | TypeRef::Char | TypeRef::Json | TypeRef::Bytes | TypeRef::Path => "string".to_string(),
        TypeRef::Primitive(p) => match p {
            PrimitiveType::Bool => "bool".to_string(),
            PrimitiveType::F32 | PrimitiveType::F64 => "float".to_string(),
            PrimitiveType::U8
            | PrimitiveType::U16
            | PrimitiveType::U32
            | PrimitiveType::U64
            | PrimitiveType::I8
            | PrimitiveType::I16
            | PrimitiveType::I32
            | PrimitiveType::I64
            | PrimitiveType::Usize
            | PrimitiveType::Isize => "int".to_string(),
        },
        TypeRef::Optional(inner) => {
            // Flatten nested Option<Option<T>> to a single nullable type.
            // PHP has no double-nullable concept; ?T already covers null.
            let inner_type = php_type(inner);
            if inner_type.starts_with('?') {
                inner_type
            } else {
                format!("?{inner_type}")
            }
        }
        TypeRef::Vec(_) | TypeRef::Map(_, _) => "array".to_string(),
        TypeRef::Named(name) => name.clone(),
        TypeRef::Unit => "void".to_string(),
        TypeRef::Duration => "float".to_string(),
    }
}