alef-backend-php 0.15.17

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
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
use crate::type_map::PhpMapper;
use ahash::AHashSet;
use alef_adapters::AdapterBodies;
use alef_codegen::builder::ImplBuilder;
use alef_codegen::generators::{self, RustBindingConfig};
use alef_codegen::shared::partition_methods;
use alef_codegen::type_mapper::TypeMapper;
use alef_core::ir::{EnumDef, EnumVariant, FieldDef, TypeDef, TypeRef};

use super::functions::{
    gen_async_instance_method, gen_async_static_method, gen_instance_method, gen_instance_method_non_opaque,
    gen_static_method,
};

/// Returns true if the type is "scalar-compatible" — i.e. ext-php-rs can handle it as a
/// Check if a type is scalar-compatible for PHP properties, considering enum names.
/// `#[php(prop)]` without needing a manual getter.  Scalar-compatible means the mapped Rust
/// type implements `IntoZval` + `FromZval` automatically:
///   primitives, String, bool, Duration (→ u64), Path (→ String), Option<scalar>,
///   Vec<primitive> (the `Vec<T: IntoZval>` blanket impl).
/// Anything containing a Named struct, Map, nested Vec, Json, or Bytes requires a getter.
/// Enums are mapped as String in the PHP binding, so they count as scalar.
fn is_php_prop_scalar_with_enums(ty: &TypeRef, enum_names: &AHashSet<String>) -> bool {
    match ty {
        TypeRef::Primitive(_) | TypeRef::String | TypeRef::Char | TypeRef::Duration | TypeRef::Path => true,
        TypeRef::Optional(inner) => is_php_prop_scalar_with_enums(inner, enum_names),
        TypeRef::Vec(inner) => {
            matches!(inner.as_ref(), TypeRef::Primitive(_) | TypeRef::String | TypeRef::Char)
                || matches!(inner.as_ref(), TypeRef::Named(n) if enum_names.contains(n))
        }
        TypeRef::Named(n) if enum_names.contains(n) => true,
        TypeRef::Named(_) | TypeRef::Map(_, _) | TypeRef::Json | TypeRef::Bytes | TypeRef::Unit => false,
    }
}

/// Returns `true` if the PHP-mapped type is `Copy`, meaning `.clone()` can be omitted.
/// Primitives (bool, integers, floats) are Copy.  Option<Primitive> is also Copy.
/// String, Named structs, Vec, Map are NOT Copy.
fn is_php_copy_type(ty: &TypeRef) -> bool {
    match ty {
        TypeRef::Primitive(_) => true,
        TypeRef::Optional(inner) => matches!(inner.as_ref(), TypeRef::Primitive(_)),
        _ => false,
    }
}

/// Generate ext-php-rs methods for an opaque struct (delegates to self.inner).
pub(crate) fn gen_opaque_struct_methods(
    typ: &TypeDef,
    mapper: &PhpMapper,
    opaque_types: &AHashSet<String>,
    core_import: &str,
    adapter_bodies: &AdapterBodies,
) -> String {
    let mut impl_builder = ImplBuilder::new(&typ.name);
    impl_builder.add_attr("php_impl");

    let (instance, statics) = partition_methods(&typ.methods);

    for method in &instance {
        if method.is_async {
            impl_builder.add_method(&gen_async_instance_method(
                method,
                mapper,
                true,
                &typ.name,
                opaque_types,
                adapter_bodies,
            ));
        } else {
            impl_builder.add_method(&gen_instance_method(
                method,
                mapper,
                true,
                &typ.name,
                opaque_types,
                core_import,
                adapter_bodies,
            ));
        }
    }
    for method in &statics {
        if method.is_async {
            impl_builder.add_method(&gen_async_static_method(method, mapper, opaque_types));
        } else {
            impl_builder.add_method(&gen_static_method(method, mapper, opaque_types, typ, core_import));
        }
    }

    impl_builder.build()
}

/// Generate a PHP struct, adding `serde::Serialize` and `serde::Deserialize` when serde is available.
/// All structs need Deserialize (not just those with Named params) because
/// structs with from_json may reference other structs that also need Deserialize.
/// Serialize is needed for the serde bridge `From<BindingType> for CoreType` used
/// by enum-tainted types (types with enum-Named fields that PHP maps to String).
///
/// When `php_namespace` is provided, a separate `#[php(name = "Namespace\\ClassName")]` attribute
/// is generated alongside the plain `#[php_class]` so that ext-php-rs 0.15+ registers the class
/// in the correct PHP namespace (e.g. `Kreuzcrawl\CrawlConfig` instead of global `CrawlConfig`).
/// Note: `#[php_class(name = "...")]` was removed in ext-php-rs 0.15; the two-attribute form is required.
pub(crate) fn gen_php_struct(
    typ: &TypeDef,
    mapper: &PhpMapper,
    cfg: &RustBindingConfig<'_>,
    php_namespace: Option<&str>,
    enum_names: &AHashSet<String>,
) -> String {
    // Build the php_class attributes: with namespace → plain #[php_class] + #[php(name = "Ns\\ClassName")],
    // without → use the config's struct_attrs unchanged.
    // ext-php-rs 0.15+ uses a separate #[php] attr for the name; #[php_class(<args>)] is no longer supported.
    let php_name_attr: String;
    let struct_attrs_override: Vec<&str>;
    let effective_struct_attrs: &[&str] = if let Some(ns) = php_namespace {
        // In the generated Rust source file, backslashes in string literals must be escaped.
        // The namespace string contains literal '\' separators (e.g. "Html\To\Markdown\Rs"),
        // so we double them so the generated code compiles: "Html\\To\\Markdown\\Rs\\ClassName".
        let ns_escaped = ns.replace('\\', "\\\\");
        php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped, typ.name);
        struct_attrs_override = vec!["php_class", php_name_attr.as_str()];
        &struct_attrs_override
    } else {
        cfg.struct_attrs
    };

    // Per-field attribute callback: add `php(prop)` for scalar-compatible fields so that
    // ext-php-rs 0.15 exposes them as PHP properties automatically.  Non-scalar fields get
    // no automatic attribute; instead a `#[php(getter)]` method is generated separately in
    // `gen_struct_methods`.
    let field_attrs_fn = |field: &FieldDef| -> Vec<String> {
        let mut attrs = if is_php_prop_scalar_with_enums(&field.ty, enum_names) {
            // Convert field names to lowerCamelCase for PHP (e.g., mime_type -> mimeType)
            let php_name = alef_codegen::naming::to_php_name(&field.name);
            vec![format!("php(prop, name = \"{}\")", php_name)]
        } else {
            vec![]
        };
        // Non-optional Duration fields are stored as Option<i64> when has_serde is enabled
        // (option_duration_on_defaults). When None, serde serializes them as JSON null, but
        // the core Duration field uses a custom duration_ms deserializer that rejects null.
        // Skip-serializing None ensures the field is omitted so the core uses its default.
        if cfg.has_serde && matches!(field.ty, TypeRef::Duration) && !field.optional {
            attrs.push("serde(skip_serializing_if = \"Option::is_none\")".to_string());
        }
        // Bool fields whose core default is `true` need an explicit per-field serde override.
        // Without it, serde uses bool::default() = false for structs with #[serde(default)],
        // which is wrong for fields like PreprocessingOptions.enabled.
        if cfg.has_serde
            && typ.has_default
            && matches!(
                field.typed_default,
                Some(alef_core::ir::DefaultValue::BoolLiteral(true))
            )
        {
            attrs.push("serde(default = \"crate::serde_defaults::bool_true\")".to_string());
        }
        // Enum-backed String fields (PHP maps unit enums to plain `String`) default to "" via
        // `String::default()`, but the core enum doesn't accept `""` as a valid variant. Skip
        // serializing the empty string so the core deserializer falls back to the enum's own
        // `Default` (which always corresponds to a real variant).
        if cfg.has_serde {
            let enum_backed_string = match &field.ty {
                TypeRef::Named(n) if enum_names.contains(n) => true,
                TypeRef::Optional(inner) => matches!(inner.as_ref(), TypeRef::Named(n) if enum_names.contains(n)),
                _ => false,
            };
            if enum_backed_string {
                if field.optional {
                    attrs.push("serde(skip_serializing_if = \"Option::is_none\")".to_string());
                } else {
                    attrs.push("serde(skip_serializing_if = \"String::is_empty\")".to_string());
                }
            }
        }
        // SecurityLimits fields need custom serde defaults to match the Rust struct's Default impl.
        // When JSON is missing a field, we want the security limit (e.g., 500MB) not 0.
        if cfg.has_serde && typ.name == "SecurityLimits" && !field.optional {
            match field.name.as_str() {
                "max_archive_size"
                | "max_compression_ratio"
                | "max_files_in_archive"
                | "max_nesting_depth"
                | "max_entity_length"
                | "max_content_size"
                | "max_iterations"
                | "max_xml_depth"
                | "max_table_cells" => {
                    let serde_attr = format!("serde(default = \"crate::serde_defaults::{}\")", field.name);
                    attrs.push(serde_attr);
                }
                _ => {}
            }
        }
        attrs
    };

    if cfg.has_serde {
        // Build a modified config that also derives Serialize + Deserialize, and adds
        // #[serde(default)] so from_json() works with partial JSON (missing fields use
        // their Default values instead of failing deserialization).
        let mut extra_derives: Vec<&str> = cfg.struct_derives.to_vec();
        extra_derives.push("serde::Serialize");
        extra_derives.push("serde::Deserialize");
        let mut serde_struct_attrs: Vec<&str> = effective_struct_attrs.to_vec();
        // No rename_all here: PHP class fields keep their core snake_case names so
        // serde round-trips losslessly through `kreuzberg::Foo` (which is also snake_case).
        // This lets us serialize the PHP-side config to JSON and deserialize it as the
        // core config without any field-name translation.
        serde_struct_attrs.push("serde(default)");
        let modified_cfg = RustBindingConfig {
            struct_attrs: &serde_struct_attrs,
            field_attrs: cfg.field_attrs,
            struct_derives: &extra_derives,
            method_block_attr: cfg.method_block_attr,
            constructor_attr: cfg.constructor_attr,
            static_attr: cfg.static_attr,
            function_attr: cfg.function_attr,
            enum_attrs: cfg.enum_attrs,
            enum_derives: cfg.enum_derives,
            needs_signature: cfg.needs_signature,
            signature_prefix: cfg.signature_prefix,
            signature_suffix: cfg.signature_suffix,
            core_import: cfg.core_import,
            async_pattern: cfg.async_pattern,
            has_serde: cfg.has_serde,
            type_name_prefix: cfg.type_name_prefix,
            option_duration_on_defaults: cfg.option_duration_on_defaults,
            opaque_type_names: cfg.opaque_type_names,
            skip_impl_constructor: cfg.skip_impl_constructor,
            cast_uints_to_i32: cfg.cast_uints_to_i32,
            cast_large_ints_to_f64: cfg.cast_large_ints_to_f64,
            named_non_opaque_params_by_ref: cfg.named_non_opaque_params_by_ref,
            lossy_skip_types: cfg.lossy_skip_types,
            serializable_opaque_type_names: cfg.serializable_opaque_type_names,
        };
        generators::gen_struct_with_per_field_attrs(typ, mapper, &modified_cfg, field_attrs_fn)
    } else {
        let modified_cfg = RustBindingConfig {
            struct_attrs: effective_struct_attrs,
            ..*cfg
        };
        generators::gen_struct_with_per_field_attrs(typ, mapper, &modified_cfg, field_attrs_fn)
    }
}

/// Generate ext-php-rs methods for a struct.
#[allow(dead_code)]
pub(crate) fn gen_struct_methods(
    typ: &TypeDef,
    mapper: &PhpMapper,
    has_serde: bool,
    core_import: &str,
    opaque_types: &AHashSet<String>,
    enum_names: &AHashSet<String>,
    enums: &[EnumDef],
) -> String {
    gen_struct_methods_impl(
        typ,
        mapper,
        has_serde,
        core_import,
        opaque_types,
        enum_names,
        enums,
        &[],              // exclude_functions: empty by default
        &AHashSet::new(), // bridge_type_aliases: empty by default
    )
}

#[allow(clippy::too_many_arguments)]
pub fn gen_struct_methods_with_exclude(
    typ: &TypeDef,
    mapper: &PhpMapper,
    has_serde: bool,
    core_import: &str,
    opaque_types: &AHashSet<String>,
    enum_names: &AHashSet<String>,
    enums: &[EnumDef],
    exclude_functions: &[String],
    bridge_type_aliases: &AHashSet<String>,
) -> String {
    gen_struct_methods_impl(
        typ,
        mapper,
        has_serde,
        core_import,
        opaque_types,
        enum_names,
        enums,
        exclude_functions,
        bridge_type_aliases,
    )
}

#[allow(clippy::too_many_arguments)]
fn gen_struct_methods_impl(
    typ: &TypeDef,
    mapper: &PhpMapper,
    has_serde: bool,
    core_import: &str,
    opaque_types: &AHashSet<String>,
    enum_names: &AHashSet<String>,
    enums: &[EnumDef],
    exclude_functions: &[String],
    bridge_type_aliases: &AHashSet<String>,
) -> String {
    let mut impl_builder = ImplBuilder::new(&typ.name);
    impl_builder.add_attr("php_impl");

    if !typ.fields.is_empty() {
        let has_named_params = typ
            .fields
            .iter()
            .any(|f| !is_php_prop_scalar_with_enums(&f.ty, enum_names));
        // When has_serde and the struct has defaults, always emit from_json so callers can
        // use partial JSON. PHP enum fields map to String in the binding; their Rust-native
        // defaults (e.g. BrowserMode::Auto) are not valid in the generated binding code, so
        // a PHP kwargs __construct would fail to compile for any struct with enum-typed fields.
        let use_from_json = has_serde && (has_named_params || typ.has_default);
        if use_from_json {
            let constructor = "#[php(name = \"from_json\")]\npub fn from_json(json: String) -> PhpResult<Self> {\n    \
                 serde_json::from_str(&json)\n        \
                 .map_err(|e| PhpException::default(e.to_string()))\n\
                 }"
            .to_string();
            impl_builder.add_method(&constructor);

            // Also generate a #[php(constructor)] for named construction.
            // Include parameters for all scalar/Vec fields (required and optional).
            // Omit complex optional fields (they default to None).
            fn field_can_be_param(
                ty: &alef_core::ir::TypeRef,
                enum_names: &AHashSet<String>,
                opaque_types: &AHashSet<String>,
            ) -> bool {
                match ty {
                    alef_core::ir::TypeRef::Vec(inner) => {
                        // Vec<NonOpaqueCustomType> cannot be a constructor param (requires error handling for FromZval)
                        match inner.as_ref() {
                            alef_core::ir::TypeRef::Named(name) => {
                                // Only allow if it's opaque or an enum (which map to String)
                                opaque_types.contains(name.as_str()) || enum_names.contains(name.as_str())
                            }
                            // Vec<serde_json::Value> does not implement FromZval; skip.
                            alef_core::ir::TypeRef::Json => false,
                            _ => true, // Vec<primitive>, Vec<String>, etc.
                        }
                    }
                    alef_core::ir::TypeRef::Bytes => true,
                    alef_core::ir::TypeRef::Optional(inner) => {
                        // Optional scalar/Vec can be a param; optional complex cannot
                        field_can_be_param(inner, enum_names, opaque_types)
                    }
                    _ => is_php_prop_scalar_with_enums(ty, enum_names),
                }
            }

            // Only generate constructor if there's at least one representable required field (otherwise from_json is simpler)
            let has_representable_required = typ
                .fields
                .iter()
                .any(|f| !f.optional && field_can_be_param(&f.ty, enum_names, opaque_types));

            if has_representable_required {
                // Build parameter lines using gen_php_function_params logic for proper type conversions
                // For Vec<NonOpaqueCustomType>, this converts to &ZendHashTable
                let param_defs: Vec<alef_core::ir::ParamDef> = typ
                    .fields
                    .iter()
                    .filter(|f| field_can_be_param(&f.ty, enum_names, opaque_types))
                    .map(|f| {
                        let php_param_name = alef_codegen::naming::to_php_name(&f.name);
                        // Non-optional Duration fields are stored as `Option<i64>` in the
                        // binding when `has_serde` is enabled on a `has_default` type
                        // (option_duration_on_defaults). The constructor signature must
                        // match the field type or the struct init will fail to type-check.
                        let optional =
                            f.optional || (has_serde && typ.has_default && matches!(f.ty, TypeRef::Duration));
                        alef_core::ir::ParamDef {
                            name: php_param_name,
                            ty: f.ty.clone(),
                            optional,
                            default: None,
                            is_ref: false,
                            is_mut: false,
                            newtype_wrapper: None,
                            sanitized: false,
                            original_type: None,
                            typed_default: None,
                        }
                    })
                    .collect();

                let param_lines =
                    super::helpers::gen_php_function_params(&param_defs, mapper, opaque_types, &AHashSet::new());

                // Generate let bindings for Vec<NonOpaqueCustomType> fields
                let mut let_bindings = String::new();
                for f in typ
                    .fields
                    .iter()
                    .filter(|f| field_can_be_param(&f.ty, enum_names, opaque_types))
                {
                    if let TypeRef::Vec(inner) = &f.ty {
                        if let TypeRef::Named(name) = inner.as_ref() {
                            if !opaque_types.contains(name.as_str()) && !enum_names.contains(name.as_str()) {
                                // Vec<NonOpaqueCustomType> parameter needs conversion from ZendHashTable
                                let php_param_name = alef_codegen::naming::to_php_name(&f.name);
                                if f.optional {
                                    let_bindings.push_str(&format!(
                                        "let {}_core: Option<Vec<{}::{}>> = if let Some(ht) = {} {{\n        \
                                         let mut result = Vec::new();\n        \
                                         for (_, item) in ht.iter() {{\n            \
                                         if let Some(parsed) = <&{} as ext_php_rs::convert::FromZval>::from_zval(item) {{\n                \
                                         result.push(parsed.clone().into());\n            \
                                         }} else {{\n                \
                                         return Err(ext_php_rs::exception::PhpException::default(\"Failed to convert array element to {}\".to_string()));\n            \
                                         }}\n        \
                                         }}\n        \
                                         Some(result)\n    \
                                         }} else {{\n        \
                                         None\n    \
                                         }};\n    ",
                                        php_param_name, core_import, name, php_param_name, name, name
                                    ));
                                } else {
                                    let_bindings.push_str(&format!(
                                        "let mut {}_core_result: Vec<{}::{}> = Vec::new();\n    \
                                         for (_, item) in {}.iter() {{\n        \
                                         if let Some(parsed) = <&{} as ext_php_rs::convert::FromZval>::from_zval(item) {{\n            \
                                         {}_core_result.push(parsed.clone().into());\n        \
                                         }} else {{\n            \
                                         return Err(ext_php_rs::exception::PhpException::default(\"Failed to convert array element to {}\".to_string()));\n        \
                                         }}\n    \
                                         }}\n    \
                                         let {}_core: Vec<{}::{}> = {}_core_result;\n    ",
                                        php_param_name, core_import, name, php_param_name, name,
                                        php_param_name, name, php_param_name, core_import, name, php_param_name
                                    ));
                                }
                            }
                        }
                    }
                }

                let param_init = typ
                    .fields
                    .iter()
                    .map(|f| {
                        let php_param_name = alef_codegen::naming::to_php_name(&f.name);
                        if field_can_be_param(&f.ty, enum_names, opaque_types) {
                            // Check if this needs let-binding conversion
                            if let TypeRef::Vec(inner) = &f.ty {
                                if let TypeRef::Named(name) = inner.as_ref() {
                                    if !opaque_types.contains(name.as_str()) && !enum_names.contains(name.as_str()) {
                                        // Use the _core binding
                                        return format!("{}: {}_core", f.name, php_param_name);
                                    }
                                }
                            }
                            // Bytes: param is PhpBytes (PHP-side); field is Vec<u8>. Unwrap.
                            let is_bytes = matches!(&f.ty, TypeRef::Bytes)
                                || matches!(&f.ty, TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Bytes));
                            if is_bytes {
                                if f.optional {
                                    return format!("{}: {}.map(|b| b.0)", f.name, php_param_name);
                                }
                                return format!("{}: {}.0", f.name, php_param_name);
                            }
                            // Params that are in the constructor
                            format!("{}: {}", f.name, php_param_name)
                        } else {
                            // Complex fields default to None/Default
                            format!("{}: Default::default()", f.name)
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                let named_constructor = format!(
                    "#[php(constructor)]\npub fn new(\n{param_lines}\n) -> Self {{\n    \
                     {let_bindings}Self {{ {param_init} }}\n\
                     }}"
                );
                impl_builder.add_method(&named_constructor);
            }
        } else if has_named_params {
            let constructor = format!(
                "pub fn __construct() -> PhpResult<Self> {{\n    \
                 Err(PhpException::default(\"Not implemented: constructor for {} requires complex params\".to_string()))\n\
                 }}",
                typ.name
            );
            impl_builder.add_method(&constructor);
        } else {
            let map_fn = |ty: &alef_core::ir::TypeRef| mapper.map_type(ty);
            if typ.has_default {
                // kwargs-style constructor: all fields optional with defaults (no serde, no Named fields)
                let config_method = alef_codegen::config_gen::gen_php_kwargs_constructor(typ, &map_fn);
                impl_builder.add_method(&config_method);
            } else {
                // Named constructor for non-Default types. Generate a factory method
                // decorated with #[php(constructor)] that accepts named parameters.
                // Use gen_php_function_params for proper Vec<NonOpaqueCustomType> handling
                let param_defs: Vec<alef_core::ir::ParamDef> = typ
                    .fields
                    .iter()
                    .map(|f| alef_core::ir::ParamDef {
                        name: f.name.clone(),
                        ty: f.ty.clone(),
                        optional: f.optional,
                        default: None,
                        is_ref: false,
                        is_mut: false,
                        newtype_wrapper: None,
                        sanitized: false,
                        original_type: None,
                        typed_default: None,
                    })
                    .collect();

                let param_lines =
                    super::helpers::gen_php_function_params(&param_defs, mapper, opaque_types, &AHashSet::new());

                // Generate let bindings for Vec<NonOpaqueCustomType> fields
                let mut let_bindings = String::new();
                for f in typ.fields.iter() {
                    if let TypeRef::Vec(inner) = &f.ty {
                        if let TypeRef::Named(name) = inner.as_ref() {
                            if !opaque_types.contains(name.as_str()) && !enum_names.contains(name.as_str()) {
                                // Vec<NonOpaqueCustomType> parameter needs conversion from ZendHashTable
                                if f.optional {
                                    let_bindings.push_str(&format!(
                                        "let {}_core: Option<Vec<{}::{}>> = if let Some(ht) = {} {{\n        \
                                         let mut result = Vec::new();\n        \
                                         for (_, item) in ht.iter() {{\n            \
                                         if let Some(parsed) = <&{} as ext_php_rs::convert::FromZval>::from_zval(item) {{\n                \
                                         result.push(parsed.clone().into());\n            \
                                         }} else {{\n                \
                                         return Err(ext_php_rs::exception::PhpException::default(\"Failed to convert array element to {}\".to_string()));\n            \
                                         }}\n        \
                                         }}\n        \
                                         Some(result)\n    \
                                         }} else {{\n        \
                                         None\n    \
                                         }};\n    ",
                                        f.name, core_import, name, f.name, name, name
                                    ));
                                } else {
                                    let_bindings.push_str(&format!(
                                        "let mut {}_core_result: Vec<{}::{}> = Vec::new();\n    \
                                         for (_, item) in {}.iter() {{\n        \
                                         if let Some(parsed) = <&{} as ext_php_rs::convert::FromZval>::from_zval(item) {{\n            \
                                         {}_core_result.push(parsed.clone().into());\n        \
                                         }} else {{\n            \
                                         return Err(ext_php_rs::exception::PhpException::default(\"Failed to convert array element to {}\".to_string()));\n        \
                                         }}\n    \
                                         }}\n    \
                                         let {}_core: Vec<{}::{}> = {}_core_result;\n    ",
                                        f.name, core_import, name, f.name, name,
                                        f.name, name, f.name, core_import, name, f.name
                                    ));
                                }
                            }
                        }
                    }
                }

                let param_init = typ
                    .fields
                    .iter()
                    .map(|f| {
                        let php_param_name = alef_codegen::naming::to_php_name(&f.name);
                        // Check if this needs let-binding conversion
                        if let TypeRef::Vec(inner) = &f.ty {
                            if let TypeRef::Named(name) = inner.as_ref() {
                                if !opaque_types.contains(name.as_str()) && !enum_names.contains(name.as_str()) {
                                    // Use the _core binding
                                    return format!("{}: {}_core", f.name, php_param_name);
                                }
                            }
                        }
                        // Default: use php parameter name (camelCase) for the value
                        format!("{}: {}", f.name, php_param_name)
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                let constructor = format!(
                    "#[php(constructor)]\npub fn new(\n{param_lines}\n) -> Self {{\n    \
                     {let_bindings}Self {{ {param_init} }}\n\
                     }}"
                );
                impl_builder.add_method(&constructor);
            }
        }
    }

    // Generate #[php(getter)] methods for non-scalar fields so PHP can access them as
    // $obj->fieldName.  Scalar fields already have #[php(prop)] on the struct field itself.
    for field in &typ.fields {
        if field.cfg.is_some() {
            continue;
        }
        let effective_ty = &field.ty;
        if !is_php_prop_scalar_with_enums(effective_ty, enum_names) {
            // ext-php-rs derives the PHP property name from the Rust method ident (stripping `get_`),
            // *not* from the `#[php(name = ...)]` attribute (which only renames the PHP method).
            // Use a camelCase Rust ident (`get_toolCalls`) so the resulting property is `toolCalls`,
            // matching the `#[php(prop, name = "...")]` convention used for scalar fields.
            let php_field_name = alef_codegen::naming::to_php_name(&field.name);
            let getter_ident = format!("get_{php_field_name}");

            // Untagged data enums and `TypeRef::Json` both map to `serde_json::Value` in
            // the binding struct, but ext-php-rs has no IntoZval impl for `serde_json::Value`.
            // Emit a JSON-string getter (Option<String>) so PHP can introspect the serialized
            // form, while the actual round-trip through `from_json` uses the Value field directly.
            // Map<_, Json> and Optional<Map<_, Json>> are caught here too — ext-php-rs 0.15.12+
            // tightened HashMap IntoZval bounds to require V: IntoZval, which Value does not impl.
            fn ty_is_or_wraps_json(t: &TypeRef) -> bool {
                match t {
                    TypeRef::Json => true,
                    TypeRef::Optional(inner) | TypeRef::Vec(inner) => ty_is_or_wraps_json(inner),
                    TypeRef::Map(_, v) => matches!(v.as_ref(), TypeRef::Json),
                    _ => false,
                }
            }
            let is_json_field = ty_is_or_wraps_json(&field.ty);
            if ty_references_untagged_data_enum(&field.ty, &mapper.untagged_data_enum_names) || is_json_field {
                let body = if field.optional {
                    format!(
                        "self.{name}.as_ref().and_then(|v| serde_json::to_string(v).ok())",
                        name = field.name
                    )
                } else {
                    format!("serde_json::to_string(&self.{name}).ok()", name = field.name)
                };
                let getter_method =
                    format!("#[php(getter)]\npub fn {getter_ident}(&self) -> Option<String> {{\n    {body}\n}}");
                impl_builder.add_method(&getter_method);
                continue;
            }
            let map_fn = |ty: &alef_core::ir::TypeRef| mapper.map_type(ty);
            let rust_return_type = if field.optional {
                mapper.optional(&mapper.map_type(&field.ty))
            } else {
                map_fn(&field.ty)
            };
            let getter_method = format!(
                "#[php(getter)]\npub fn {getter_ident}(&self) -> {ret} {{\n    self.{field_name}.clone()\n}}",
                field_name = field.name,
                ret = rust_return_type,
            );
            impl_builder.add_method(&getter_method);

            // Note: setters for Named/Vec/Map fields are not generated because
            // ext-php-rs doesn't support &T: FromZval for #[php(setter)] parameters.
            // Config types with complex fields should be constructed via fromJson().
        }
    }

    // Non-opaque structs don't have adapter bodies — adapters apply to opaque types only.
    let empty_adapter_bodies: alef_adapters::AdapterBodies = Default::default();

    let (instance, statics) = partition_methods(&typ.methods);

    for method in &instance {
        if method.is_async {
            impl_builder.add_method(&gen_async_instance_method(
                method,
                mapper,
                false,
                &typ.name,
                opaque_types,
                &empty_adapter_bodies,
            ));
        } else {
            impl_builder.add_method(&gen_instance_method_non_opaque(
                method,
                mapper,
                typ,
                core_import,
                opaque_types,
                enums,
                bridge_type_aliases,
            ));
        }
    }
    for method in &statics {
        // Skip methods that are in the exclusion list
        if exclude_functions.contains(&method.name) {
            continue;
        }
        if method.is_async {
            impl_builder.add_method(&gen_async_static_method(method, mapper, opaque_types));
        } else {
            impl_builder.add_method(&gen_static_method(method, mapper, opaque_types, typ, core_import));
        }
    }

    impl_builder.build()
}

/// Generate PHP enum constants (enums as string constants).
pub(crate) fn gen_enum_constants(enum_def: &EnumDef) -> String {
    let mut lines = vec![format!("// {} enum values", enum_def.name)];

    for variant in &enum_def.variants {
        let const_name = format!("{}_{}", enum_def.name.to_uppercase(), variant.name.to_uppercase());
        lines.push(format!("pub const {}: &str = \"{}\";", const_name, variant.name));
    }

    lines.join("\n")
}

/// Return true if an enum is a "tagged data enum" — has a serde tag AND at least one variant
/// with named fields. These are lowered to flat PHP classes rather than string constants.
pub(crate) fn is_tagged_data_enum(enum_def: &EnumDef) -> bool {
    enum_def.serde_tag.is_some() && enum_def.variants.iter().any(|v| !v.fields.is_empty())
}

/// Return true if an enum is an "untagged data enum" — has `#[serde(untagged)]` AND at
/// least one variant carrying data (e.g. `Single(String) | Multiple(Vec<String>)`).
/// These cannot be lowered to a single `String` in the PHP binding because the wire
/// JSON shape varies per variant; they are mapped to `serde_json::Value` and converted
/// to the typed core enum via `serde_json::from_value` in the binding→core `From` impl.
pub(crate) fn is_untagged_data_enum(enum_def: &EnumDef) -> bool {
    enum_def.serde_untagged && enum_def.variants.iter().any(|v| !v.fields.is_empty())
}

/// Returns true if `ty` references (directly or via Optional/Vec wrap) a Named type whose
/// name is in `untagged_data_enum_names`.  Used to choose the correct getter / From-impl
/// branch in the PHP binding code generator.
pub(crate) fn ty_references_untagged_data_enum(ty: &TypeRef, untagged_data_enum_names: &AHashSet<String>) -> bool {
    match ty {
        TypeRef::Named(n) => untagged_data_enum_names.contains(n.as_str()),
        TypeRef::Optional(inner) | TypeRef::Vec(inner) => {
            ty_references_untagged_data_enum(inner, untagged_data_enum_names)
        }
        _ => false,
    }
}

/// Compute the flat struct field name for a single field of a variant.
///
/// For tuple variants (fields named `_0`, `_1`, …), the flat field name is derived from
/// the variant name to avoid collisions when multiple variants each have a positional `_0`:
/// - Single-field tuple variant `Foo(_0)` → `foo`
/// - Multi-field tuple variant `Foo(_0, _1)` → `foo_0`, `foo_1`
///
/// For struct variants (named fields), the field's own name is used unchanged.
fn flat_field_name(variant: &EnumVariant, field_index: usize) -> String {
    use heck::ToSnakeCase as _;
    if alef_codegen::conversions::is_tuple_variant(&variant.fields) {
        let base = variant.name.to_snake_case();
        if variant.fields.len() == 1 {
            base
        } else {
            format!("{base}_{field_index}")
        }
    } else {
        variant.fields[field_index].name.clone()
    }
}

/// Generate a flat `#[php_class]` struct for a tagged data enum.
///
/// The struct unions all variant fields as `Option<T>` plus a string discriminator named
/// after the serde tag (defaulting to `"type"`). This lets `HashMap<String, SecuritySchemeInfo>`
/// stay as `HashMap<String, SecuritySchemeInfo>` (the flat PHP class) with working `From` impls.
pub(crate) fn gen_flat_data_enum(enum_def: &EnumDef, mapper: &PhpMapper, php_namespace: Option<&str>) -> String {
    let tag_field = enum_def.serde_tag.as_deref().unwrap_or("type");

    let php_attrs: String = if let Some(ns) = php_namespace {
        let ns_escaped = ns.replace('\\', "\\\\");
        let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped, enum_def.name);
        format!("#[php_class]\n#[{php_name_attr}]")
    } else {
        "#[php_class]".to_string()
    };

    let mut out = String::new();
    out.push_str(&crate::template_env::render(
        "php_flat_enum_struct_start.jinja",
        minijinja::context! {
            php_attrs => &php_attrs,
            enum_name => &enum_def.name,
        },
    ));
    // Discriminator field
    out.push_str(&crate::template_env::render(
        "php_flat_enum_tag_field.jinja",
        minijinja::context! {
            tag_field => tag_field,
        },
    ));

    // Collect all unique flat fields across variants, all made Optional.
    // For tuple variants each positional field gets a per-variant name so that
    // `System(_0: SystemMessage)` and `User(_0: UserMessage)` produce distinct
    // fields `system: Option<SystemMessage>` and `user: Option<UserMessage>`.
    // For struct variants the original field name is used (shared across variants).
    let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for variant in &enum_def.variants {
        for (idx, field) in variant.fields.iter().enumerate() {
            let flat_name = flat_field_name(variant, idx);
            if seen.insert(flat_name.clone()) {
                let mapped = mapper.map_type(&field.ty).to_string();
                // All variant fields become Option in the flat struct. If the core
                // field is already optional (field.optional == true), the mapped type
                // is the inner type and we still wrap it in Option.
                let field_ty = format!("Option<{mapped}>");
                out.push_str(&crate::template_env::render(
                    "php_flat_enum_option_field.jinja",
                    minijinja::context! {
                        flat_name => &flat_name,
                        field_ty => &field_ty,
                    },
                ));
            }
        }
    }
    out.push_str(&crate::template_env::render(
        "php_flat_enum_struct_end.jinja",
        minijinja::Value::default(),
    ));
    out
}

/// Generate `#[php_impl]` accessor methods and a `from_json` constructor for the flat data enum.
pub(crate) fn gen_flat_data_enum_methods(enum_def: &EnumDef, mapper: &PhpMapper) -> String {
    let tag_field = enum_def.serde_tag.as_deref().unwrap_or("type");
    let mut impl_builder = ImplBuilder::new(&enum_def.name);
    impl_builder.add_attr("php_impl");

    // from_json constructor so PHP can construct the value.
    let from_json = "#[php(name = \"from_json\")]\npub fn from_json(json: String) -> PhpResult<Self> {\n    \
        serde_json::from_str(&json)\n        \
        .map_err(|e| PhpException::default(e.to_string()))\n\
        }"
    .to_string();
    impl_builder.add_method(&from_json);

    // Getter for the tag discriminator field
    let tag_getter =
        format!("#[php(getter)]\npub fn get_{tag_field}_tag(&self) -> String {{\n    self.{tag_field}_tag.clone()\n}}");
    impl_builder.add_method(&tag_getter);

    let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for variant in &enum_def.variants {
        for (idx, field) in variant.fields.iter().enumerate() {
            let flat_name = flat_field_name(variant, idx);
            if seen.insert(flat_name.clone()) {
                let mapped = mapper.map_type(&field.ty).to_string();
                // Getter returns Option<T> for every variant field (all are optional in flat struct).
                let field_ty = format!("Option<{mapped}>");
                // For Copy types (Option<primitive>), omit `.clone()` to avoid clone_on_copy.
                let body_expr = if is_php_copy_type(&field.ty) {
                    format!("self.{flat_name}")
                } else {
                    format!("self.{flat_name}.clone()")
                };
                let getter_body =
                    format!("#[php(getter)]\npub fn get_{flat_name}(&self) -> {field_ty} {{\n    {body_expr}\n}}",);
                impl_builder.add_method(&getter_body);
            }
        }
    }

    let mut out = String::new();
    let impl_code = impl_builder.build();
    out.push_str(&impl_code);
    out.push('\n');
    out
}

/// Returns the serde-renamed tag string for a variant.
fn variant_tag_value(variant: &EnumVariant, enum_def: &EnumDef) -> String {
    if let Some(rename) = &variant.serde_rename {
        return rename.clone();
    }
    if let Some(rename_all) = &enum_def.serde_rename_all {
        return apply_rename_all(&variant.name, rename_all);
    }
    variant.name.clone()
}

fn apply_rename_all(name: &str, strategy: &str) -> String {
    use heck::{ToKebabCase, ToLowerCamelCase, ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
    match strategy {
        "lowercase" => name.to_lowercase(),
        "UPPERCASE" => name.to_uppercase(),
        "camelCase" => name.to_lower_camel_case(),
        "PascalCase" => name.to_upper_camel_case(),
        "snake_case" => name.to_snake_case(),
        "SCREAMING_SNAKE_CASE" => name.to_shouty_snake_case(),
        "kebab-case" => name.to_kebab_case(),
        _ => name.to_string(),
    }
}

/// Generate `From<core::DataEnum> for PhpDataEnum` and `From<PhpDataEnum> for core::DataEnum`
/// for a tagged data enum lowered to a flat PHP class.
pub(crate) fn gen_flat_data_enum_from_impls(enum_def: &EnumDef, core_import: &str) -> String {
    use alef_core::ir::{PrimitiveType, TypeRef};
    let tag_field = enum_def.serde_tag.as_deref().unwrap_or("type");
    let core_path = alef_codegen::conversions::core_enum_path(enum_def, core_import);
    let binding_name = &enum_def.name;

    // Pre-compute the complete set of flat struct field names (excluding the tag discriminator).
    // This lets us detect when a variant covers ALL fields so we can omit `..Default::default()`.
    let all_flat_fields: std::collections::BTreeSet<String> = {
        let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        for variant in &enum_def.variants {
            for (idx, _) in variant.fields.iter().enumerate() {
                seen.insert(flat_field_name(variant, idx));
            }
        }
        seen
    };

    let mut out = String::new();

    // --- core → binding ---
    // Converts a core enum value to the flat PHP binding struct.
    // Destructuring patterns for boxed fields use the raw IR name (e.g. `_0`);
    // sanitized fields are excluded from the pattern (bound with `_`-prefixed name),
    // Path fields are converted via `to_string_lossy()`, Usize/U64/Isize are cast to i64.
    out.push_str(&crate::template_env::render(
        "php_flat_enum_impl_from_start.jinja",
        minijinja::context! {
            core_path => &core_path,
            binding_name => &binding_name,
        },
    ));
    for variant in &enum_def.variants {
        let tag_val = variant_tag_value(variant, enum_def);
        if variant.fields.is_empty() {
            // No variant fields: only the tag is set; all Option fields default to None.
            // `..Default::default()` is only needed when the struct has other fields.
            out.push_str(&crate::template_env::render(
                "php_flat_enum_variant_match_empty.jinja",
                minijinja::context! {
                    core_path => &core_path,
                    variant_name => &variant.name,
                    tag_field => tag_field,
                    tag_val => &tag_val,
                    needs_default => !all_flat_fields.is_empty(),
                },
            ));
        } else {
            let is_tuple = alef_codegen::conversions::is_tuple_variant(&variant.fields);
            // Build destructuring pattern.
            // - Tuple variants: positional names (IR names like `_0`, `_1`); sanitized fields
            //   use a discard binding with a leading underscore prefix (e.g. `__0`).
            // - Struct variants: `field` or `field: _field` for sanitized fields (the `_` prefix
            //   suppresses the "unused variable" warning while keeping Rust happy that the field
            //   is mentioned in the pattern — `_field` can't be used in the pattern directly for
            //   struct variants).
            let pattern = if is_tuple {
                let names: Vec<String> = variant
                    .fields
                    .iter()
                    .map(|f| {
                        if f.sanitized {
                            format!("_{}", f.name)
                        } else {
                            f.name.clone()
                        }
                    })
                    .collect();
                names.join(", ")
            } else {
                let bindings: Vec<String> = variant
                    .fields
                    .iter()
                    .map(|f| {
                        if f.sanitized {
                            // `field_name: _field_name` — Rust ignores the value but accepts the pattern.
                            format!("{}: _{}", f.name, f.name)
                        } else {
                            f.name.clone()
                        }
                    })
                    .collect();
                bindings.join(", ")
            };
            let pattern_start = if is_tuple {
                format!("            {core_path}::{}({pattern}) => Self {{", variant.name)
            } else {
                format!("            {core_path}::{}{{ {pattern} }} => Self {{", variant.name)
            };
            out.push_str(&pattern_start);
            out.push_str(&crate::template_env::render(
                "php_flat_enum_tag_assignment.jinja",
                minijinja::context! {
                    tag_field => tag_field,
                    tag_val => &tag_val,
                },
            ));
            for (idx, f) in variant.fields.iter().enumerate() {
                let flat_name = flat_field_name(variant, idx);
                // The destructuring variable name:
                // - tuple variants: sanitized fields use `_`-prefixed IR name.
                // - struct variants: sanitized fields use `_`-prefixed field name (from pattern above).
                // - non-sanitized: use the plain field name.
                let bound_var = if f.sanitized {
                    format!("_{}", f.name)
                } else {
                    f.name.clone()
                };
                // f.optional means the core field is Option<T>; binding is always Option<T>.
                let expr = flat_enum_core_to_binding_field_expr(f, &bound_var);
                out.push_str(&crate::template_env::render(
                    "php_flat_enum_variant_field.jinja",
                    minijinja::context! {
                        flat_name => &flat_name,
                        expr => &expr,
                    },
                ));
            }
            // Omit `..Default::default()` when this variant's fields cover every flat struct
            // field — the struct update would have no effect and triggers `clippy::needless_update`.
            let variant_flat_names: std::collections::BTreeSet<String> =
                (0..variant.fields.len()).map(|i| flat_field_name(variant, i)).collect();
            if variant_flat_names == all_flat_fields {
                out.push_str(" },\n");
            } else {
                out.push_str(" ..Default::default() },\n");
            }
        }
    }
    out.push_str(&crate::template_env::render(
        "php_flat_enum_impl_match_end.jinja",
        minijinja::Value::default(),
    ));

    // --- binding → core: match on the tag field to reconstruct the correct variant ---
    // We use tag-value matching rather than serde round-trip to avoid serde field rename
    // mismatches between the flat struct (uses Rust snake_case names) and the core type
    // (may have #[serde(rename = "camelCase")] on individual variant fields).
    out.push_str(&crate::template_env::render(
        "php_flat_enum_impl_into_start.jinja",
        minijinja::context! {
            binding_name => &binding_name,
            core_path => &core_path,
            tag_field => tag_field,
        },
    ));
    for variant in &enum_def.variants {
        let tag_val = variant_tag_value(variant, enum_def);
        if variant.fields.is_empty() {
            out.push_str(&crate::template_env::render(
                "php_flat_enum_variant_match_into_empty.jinja",
                minijinja::context! {
                    tag_val => &tag_val,
                    core_path => &core_path,
                    variant_name => &variant.name,
                },
            ));
        } else {
            let is_tuple = alef_codegen::conversions::is_tuple_variant(&variant.fields);
            let pattern_start = if is_tuple {
                format!("            \"{tag_val}\" => {core_path}::{}(", variant.name)
            } else {
                format!("            \"{tag_val}\" => {core_path}::{}{{", variant.name)
            };
            out.push_str(&pattern_start);
            if is_tuple {
                // Tuple variant: positional syntax uses `, ` separators.
                let exprs: Vec<String> = variant
                    .fields
                    .iter()
                    .enumerate()
                    .map(|(idx, f)| flat_enum_binding_to_core_field_expr(f, &flat_field_name(variant, idx)))
                    .collect();
                out.push_str(&crate::template_env::render(
                    "php_flat_enum_tuple_exprs.jinja",
                    minijinja::context! {
                        exprs_joined => exprs.join(", "),
                    },
                ));
                out.push_str(" ),\n");
            } else {
                // Struct variant: `field_name: <expr>,` for each field.
                for (idx, f) in variant.fields.iter().enumerate() {
                    let flat_name = flat_field_name(variant, idx);
                    let expr = flat_enum_binding_to_core_field_expr(f, &flat_name);
                    out.push_str(&crate::template_env::render(
                        "php_flat_enum_variant_field.jinja",
                        minijinja::context! {
                            flat_name => &flat_name,
                            expr => &expr,
                        },
                    ));
                }
                out.push_str(" },\n");
            }
        }
    }
    // Fallback to first variant (with all fields defaulted) for unrecognised tags.
    if let Some(first) = enum_def.variants.first() {
        if first.fields.is_empty() {
            out.push_str(&crate::template_env::render(
                "php_flat_enum_fallback_variant_empty.jinja",
                minijinja::context! {
                    core_path => &core_path,
                    variant_name => &first.name,
                },
            ));
        } else if alef_codegen::conversions::is_tuple_variant(&first.fields) {
            out.push_str(&crate::template_env::render(
                "php_flat_enum_fallback_variant_tuple_start.jinja",
                minijinja::context! {
                    core_path => &core_path,
                    variant_name => &first.name,
                },
            ));
            let parts: Vec<String> = first
                .fields
                .iter()
                .map(|f| {
                    if f.is_boxed {
                        "Box::new(Default::default())".to_string()
                    } else {
                        "Default::default()".to_string()
                    }
                })
                .collect();
            out.push_str(&crate::template_env::render(
                "php_flat_enum_tuple_exprs.jinja",
                minijinja::context! {
                    exprs_joined => parts.join(", "),
                },
            ));
            out.push_str(" ),\n");
        } else {
            out.push_str(&crate::template_env::render(
                "php_flat_enum_fallback_variant_struct_start.jinja",
                minijinja::context! {
                    core_path => &core_path,
                    variant_name => &first.name,
                },
            ));
            for f in &first.fields {
                // Pass only the expression (without "name: " prefix and without trailing comma)
                // since php_flat_enum_fallback_variant_field.jinja adds "{{ field_name }}: {{ default_expr }},"
                let default_expr = if f.is_boxed {
                    "Box::new(Default::default())".to_string()
                } else {
                    "Default::default()".to_string()
                };
                out.push_str(&crate::template_env::render(
                    "php_flat_enum_fallback_variant_field.jinja",
                    minijinja::context! {
                        field_name => &f.name,
                        default_expr => &default_expr,
                    },
                ));
            }
            out.push_str(" },\n");
        }
    }
    out.push_str(&crate::template_env::render(
        "php_flat_enum_impl_match_end.jinja",
        minijinja::Value::default(),
    ));

    // Suppress the unused import warning that would appear when TypeRef/PrimitiveType
    // are only referenced inside the helper closures above (Rust may not see the use).
    let _ = TypeRef::Unit;
    let _ = PrimitiveType::Bool;

    out
}

/// Build the expression for a single flat-enum variant field when converting core → binding.
/// The binding struct field is always `Option<MappedType>` for flat data enums.
///
/// - Sanitized fields cannot be converted (the core type is unknown/complex); emit `None`.
/// - `is_boxed` fields: unbox with `*` before converting.
/// - `TypeRef::Path`: convert via `to_string_lossy().into_owned()`.
/// - `TypeRef::Primitive(Usize | U64 | Isize)`: cast to `i64` (PHP's integer representation).
/// - Everything else: use `.into()` / `.map(Into::into)`.
fn flat_enum_core_to_binding_field_expr(f: &alef_core::ir::FieldDef, bound_var: &str) -> String {
    use alef_core::ir::{PrimitiveType, TypeRef};

    if f.sanitized {
        // Sanitized fields have an unknown/complex core type; we can't produce a PHP value.
        return "None".to_string();
    }

    // Helper: produce `Some(<inner>)` from a raw owned expression.
    let wrap_some = |inner: String| -> String { format!("Some({inner})") };

    match &f.ty {
        TypeRef::Path => {
            // PathBuf → String via to_string_lossy
            if f.optional {
                format!("{bound_var}.map(|p| p.to_string_lossy().into_owned())")
            } else {
                wrap_some(format!("{bound_var}.to_string_lossy().into_owned()"))
            }
        }
        TypeRef::Primitive(PrimitiveType::Usize | PrimitiveType::U64 | PrimitiveType::Isize) => {
            if f.optional {
                format!("{bound_var}.map(|v| v as i64)")
            } else {
                wrap_some(format!("{bound_var} as i64"))
            }
        }
        TypeRef::Named(_) if f.is_boxed => {
            // Boxed Named: unbox then convert.
            if f.optional {
                format!("{bound_var}.map(|v| (*v).into())")
            } else {
                wrap_some(format!("(*{bound_var}).into()"))
            }
        }
        // Primitives that map to the same type in PHP (all except u64/usize/isize which map
        // to i64) and String: binding type == core type, no conversion needed.
        TypeRef::Primitive(_) | TypeRef::String => {
            if f.optional {
                // Core field is Option<T>, binding field is Option<T>: pass through directly.
                bound_var.to_string()
            } else {
                // Core field is T, binding field is Option<T>: wrap in Some.
                wrap_some(bound_var.to_string())
            }
        }
        _ => {
            if f.optional {
                format!("{bound_var}.map(Into::into)")
            } else {
                wrap_some(format!("{bound_var}.into()"))
            }
        }
    }
}

/// Build the expression for a single flat-enum variant field when converting binding → core.
/// The binding struct field is always `Option<MappedType>`; the core field may be non-optional.
///
/// - Sanitized fields: emit `Default::default()` (cannot round-trip through PHP).
/// - `is_boxed` fields: wrap the result in `Box::new(...)`.
/// - `TypeRef::Path`: convert `String → PathBuf` via `PathBuf::from`.
/// - `TypeRef::Primitive(Usize | U64 | Isize)`: cast `i64 → usize/u64/isize`.
/// - Everything else: `.into()` / `.map(Into::into)`.
fn flat_enum_binding_to_core_field_expr(f: &alef_core::ir::FieldDef, flat_name: &str) -> String {
    use alef_core::ir::{PrimitiveType, TypeRef};

    if f.sanitized {
        return if f.is_boxed {
            "Box::new(Default::default())".to_string()
        } else {
            "Default::default()".to_string()
        };
    }

    let expr = match &f.ty {
        TypeRef::Path => {
            if f.optional {
                format!("val.{flat_name}.map(std::path::PathBuf::from)")
            } else {
                format!("val.{flat_name}.map(std::path::PathBuf::from).unwrap_or_default()")
            }
        }
        TypeRef::Primitive(p @ (PrimitiveType::Usize | PrimitiveType::U64 | PrimitiveType::Isize)) => {
            let core_ty = match p {
                PrimitiveType::Usize => "usize",
                PrimitiveType::U64 => "u64",
                PrimitiveType::Isize => "isize",
                _ => unreachable!(),
            };
            if f.optional {
                format!("val.{flat_name}.map(|v| v as {core_ty})")
            } else {
                format!("val.{flat_name}.map(|v| v as {core_ty}).unwrap_or_default()")
            }
        }
        // Primitives that map to the same type in PHP (all except u64/usize/isize) and
        // String: binding type == core type, no conversion needed.
        TypeRef::Primitive(_) | TypeRef::String => {
            // Binding field is Option<T>; unwrap for non-optional core fields.
            if f.optional {
                format!("val.{flat_name}")
            } else {
                format!("val.{flat_name}.unwrap_or_default()")
            }
        }
        _ => {
            if f.optional {
                format!("val.{flat_name}.map(Into::into)")
            } else {
                format!("val.{flat_name}.map(Into::into).unwrap_or_default()")
            }
        }
    };

    if f.is_boxed { format!("Box::new({expr})") } else { expr }
}