Skip to main content

alef_backend_php/gen_bindings/
mod.rs

1mod functions;
2mod helpers;
3pub mod types;
4
5use crate::type_map::PhpMapper;
6use ahash::AHashSet;
7use alef_codegen::builder::RustFileBuilder;
8use alef_codegen::conversions::ConversionConfig;
9use alef_codegen::generators::RustBindingConfig;
10use alef_codegen::generators::{self, AsyncPattern};
11use alef_codegen::naming::to_php_name;
12use alef_codegen::shared::binding_fields;
13use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
14use alef_core::config::{Language, ResolvedCrateConfig, detect_serde_available, resolve_output_dir};
15use alef_core::hash::{self, CommentStyle};
16use alef_core::ir::ApiSurface;
17use alef_core::ir::{PrimitiveType, TypeRef};
18use heck::{ToLowerCamelCase, ToPascalCase};
19use minijinja::context;
20use std::path::PathBuf;
21
22use crate::naming::php_autoload_namespace;
23use functions::{gen_async_function_as_static_method, gen_function_as_static_method};
24
25/// PHP 8.1 enum cases cannot use case-insensitive `class` (reserved for
26/// `EnumName::class` syntax). Append a trailing underscore for those cases.
27fn sanitize_php_enum_case(name: &str) -> String {
28    if name.eq_ignore_ascii_case("class") {
29        format!("{name}_")
30    } else {
31        name.to_string()
32    }
33}
34use helpers::{gen_enum_tainted_from_binding_to_core, gen_tokio_runtime, has_enum_named_field, references_named_type};
35use types::{
36    gen_enum_constants, gen_flat_data_enum, gen_flat_data_enum_from_impls, gen_flat_data_enum_methods,
37    gen_opaque_struct_methods, gen_php_struct, is_tagged_data_enum, is_untagged_data_enum,
38};
39
40pub struct PhpBackend;
41
42impl PhpBackend {
43    fn binding_config(core_import: &str, has_serde: bool) -> RustBindingConfig<'_> {
44        RustBindingConfig {
45            struct_attrs: &["php_class"],
46            field_attrs: &[],
47            struct_derives: &["Clone"],
48            method_block_attr: Some("php_impl"),
49            constructor_attr: "",
50            static_attr: None,
51            function_attr: "#[php_function]",
52            enum_attrs: &[],
53            enum_derives: &[],
54            needs_signature: false,
55            signature_prefix: "",
56            signature_suffix: "",
57            core_import,
58            async_pattern: AsyncPattern::TokioBlockOn,
59            has_serde,
60            type_name_prefix: "",
61            option_duration_on_defaults: true,
62            opaque_type_names: &[],
63            skip_impl_constructor: false,
64            cast_uints_to_i32: false,
65            cast_large_ints_to_f64: false,
66            named_non_opaque_params_by_ref: false,
67            lossy_skip_types: &[],
68            serializable_opaque_type_names: &[],
69            never_skip_cfg_field_names: &[],
70        }
71    }
72}
73
74impl Backend for PhpBackend {
75    fn name(&self) -> &str {
76        "php"
77    }
78
79    fn language(&self) -> Language {
80        Language::Php
81    }
82
83    fn capabilities(&self) -> Capabilities {
84        Capabilities {
85            supports_async: false,
86            supports_classes: true,
87            supports_enums: true,
88            supports_option: true,
89            supports_result: true,
90            ..Capabilities::default()
91        }
92    }
93
94    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
95        // Separate unit-variant enums (→ String), tagged data enums (→ flat PHP class),
96        // and untagged data enums (→ serde_json::Value, converted via from_value at binding↔core boundary).
97        let data_enum_names: AHashSet<String> = api
98            .enums
99            .iter()
100            .filter(|e| is_tagged_data_enum(e))
101            .map(|e| e.name.clone())
102            .collect();
103        let untagged_data_enum_names: AHashSet<String> = api
104            .enums
105            .iter()
106            .filter(|e| is_untagged_data_enum(e))
107            .map(|e| e.name.clone())
108            .collect();
109        // String-mapped enums: everything that is NOT a tagged-data enum AND NOT an untagged-data enum.
110        // Includes unit-variant enums (FilePurpose, ToolType, …) which are exposed as PHP string constants.
111        let enum_names: AHashSet<String> = api
112            .enums
113            .iter()
114            .filter(|e| !is_tagged_data_enum(e) && !is_untagged_data_enum(e))
115            .map(|e| e.name.clone())
116            .collect();
117        let mapper = PhpMapper {
118            enum_names: enum_names.clone(),
119            data_enum_names: data_enum_names.clone(),
120            untagged_data_enum_names: untagged_data_enum_names.clone(),
121        };
122        let core_import = config.core_import_name();
123        let lang_rename_all = config.serde_rename_all_for_language(Language::Php);
124
125        // Get exclusion lists from PHP config
126        let php_config = config.php.as_ref();
127        let exclude_functions = php_config.map(|c| c.exclude_functions.clone()).unwrap_or_default();
128        let exclude_types = php_config.map(|c| c.exclude_types.clone()).unwrap_or_default();
129
130        let output_dir = resolve_output_dir(config.output_paths.get("php"), &config.name, "crates/{name}-php/src/");
131        let has_serde = detect_serde_available(&output_dir);
132
133        // Build the opaque type names list: IR opaque types + bridge type aliases.
134        // Bridge type aliases (e.g. `VisitorHandle`) wrap Rc-based handles and cannot
135        // implement serde::Serialize/Deserialize.  Including them ensures gen_php_struct
136        // emits #[serde(skip)] for fields of those types so derives on the enclosing
137        // struct (e.g. ConversionOptions) still compile.
138        let bridge_type_aliases_php: Vec<String> = config
139            .trait_bridges
140            .iter()
141            .filter_map(|b| b.type_alias.clone())
142            .collect();
143        let bridge_type_aliases_set: AHashSet<String> = bridge_type_aliases_php.iter().cloned().collect();
144        let mut opaque_names_vec_php: Vec<String> = api
145            .types
146            .iter()
147            .filter(|t| t.is_opaque)
148            .map(|t| t.name.clone())
149            .collect();
150        opaque_names_vec_php.extend(bridge_type_aliases_php);
151
152        let mut cfg = Self::binding_config(&core_import, has_serde);
153        cfg.opaque_type_names = &opaque_names_vec_php;
154        let never_skip_cfg_field_names: Vec<String> = config
155            .trait_bridges
156            .iter()
157            .filter_map(|b| {
158                if b.bind_via == alef_core::config::BridgeBinding::OptionsField {
159                    b.resolved_options_field().map(|s| s.to_string())
160                } else {
161                    None
162                }
163            })
164            .collect();
165        cfg.never_skip_cfg_field_names = &never_skip_cfg_field_names;
166
167        // Build the inner module content (types, methods, conversions)
168        let mut builder = RustFileBuilder::new().with_generated_header();
169        builder.add_inner_attribute("allow(dead_code, unused_imports, unused_variables)");
170        builder.add_inner_attribute("allow(unsafe_code)");
171        // PHP parameter names are lowerCamelCase; Rust complains about non-snake_case variables.
172        builder.add_inner_attribute("allow(non_snake_case)");
173        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, clippy::arc_with_non_send_sync, clippy::collapsible_if, clippy::clone_on_copy, clippy::should_implement_trait, clippy::useless_conversion)");
174        builder.add_import("ext_php_rs::prelude::*");
175
176        // Import serde_json when available (needed for serde-based param conversion)
177        if has_serde {
178            builder.add_import("serde_json");
179        }
180
181        // Import traits needed for trait method dispatch
182        for trait_path in generators::collect_trait_imports(api) {
183            builder.add_import(&trait_path);
184        }
185
186        // Only import HashMap when Map-typed fields or returns are present
187        let has_maps = api.types.iter().any(|t| {
188            t.fields
189                .iter()
190                .any(|f| matches!(&f.ty, alef_core::ir::TypeRef::Map(_, _)))
191        }) || api
192            .functions
193            .iter()
194            .any(|f| matches!(&f.return_type, alef_core::ir::TypeRef::Map(_, _)));
195        if has_maps {
196            builder.add_import("std::collections::HashMap");
197        }
198
199        // PhpBytes wrapper: accepts PHP binary strings without UTF-8 validation.
200        // ext-php-rs's String FromZval rejects non-UTF-8 strings, so binary content
201        // (PDFs, images, etc.) gets "Invalid value given for argument" errors. This
202        // wrapper reads the raw bytes via `zend_str()` and exposes them as Vec<u8>.
203        builder.add_item(
204            "#[derive(Debug, Clone, Default)]\n\
205             pub struct PhpBytes(pub Vec<u8>);\n\
206             \n\
207             impl<'a> ext_php_rs::convert::FromZval<'a> for PhpBytes {\n    \
208                 const TYPE: ext_php_rs::flags::DataType = ext_php_rs::flags::DataType::String;\n    \
209                 fn from_zval(zval: &'a ext_php_rs::types::Zval) -> Option<Self> {\n        \
210                     zval.zend_str().map(|zs| PhpBytes(zs.as_bytes().to_vec()))\n    \
211                 }\n\
212             }\n\
213             \n\
214             impl From<PhpBytes> for Vec<u8> {\n    \
215                 fn from(b: PhpBytes) -> Self { b.0 }\n\
216             }\n\
217             \n\
218             impl From<Vec<u8>> for PhpBytes {\n    \
219                 fn from(v: Vec<u8>) -> Self { PhpBytes(v) }\n\
220             }\n",
221        );
222
223        // Custom module declarations
224        let custom_mods = config.custom_modules.for_language(Language::Php);
225        for module in custom_mods {
226            builder.add_item(&format!("pub mod {module};"));
227        }
228
229        // Check if any function or method is async
230        let has_async =
231            api.functions.iter().any(|f| f.is_async) || api.types.iter().any(|t| t.methods.iter().any(|m| m.is_async));
232
233        if has_async {
234            builder.add_item(&gen_tokio_runtime());
235        }
236
237        // Check if we have opaque types and add Arc import if needed
238        let opaque_types: AHashSet<String> = api
239            .types
240            .iter()
241            .filter(|t| t.is_opaque)
242            .map(|t| t.name.clone())
243            .collect();
244        if !opaque_types.is_empty() {
245            builder.add_import("std::sync::Arc");
246        }
247
248        // Compute mutex types: opaque types with &mut self methods
249        let mutex_types: AHashSet<String> = api
250            .types
251            .iter()
252            .filter(|t| t.is_opaque && alef_codegen::generators::type_needs_mutex(t))
253            .map(|t| t.name.clone())
254            .collect();
255        if !mutex_types.is_empty() {
256            builder.add_import("std::sync::Mutex");
257        }
258
259        // Compute the PHP namespace for namespaced class registration.
260        // Delegates to config so [php].namespace overrides are respected.
261        let extension_name = config.php_extension_name();
262        let php_namespace = php_autoload_namespace(config);
263
264        // Build adapter body map before type iteration so bodies are available for method generation.
265        let adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Php)?;
266
267        // Emit adapter-generated standalone items (streaming iterators, callback bridges).
268        for adapter in &config.adapters {
269            match adapter.pattern {
270                alef_core::config::AdapterPattern::Streaming => {
271                    let key = format!("{}.__stream_struct__", adapter.item_type.as_deref().unwrap_or(""));
272                    if let Some(struct_code) = adapter_bodies.get(&key) {
273                        builder.add_item(struct_code);
274                    }
275                }
276                alef_core::config::AdapterPattern::CallbackBridge => {
277                    let struct_key = format!("{}.__bridge_struct__", adapter.name);
278                    let impl_key = format!("{}.__bridge_impl__", adapter.name);
279                    if let Some(struct_code) = adapter_bodies.get(&struct_key) {
280                        builder.add_item(struct_code);
281                    }
282                    if let Some(impl_code) = adapter_bodies.get(&impl_key) {
283                        builder.add_item(impl_code);
284                    }
285                }
286                _ => {}
287            }
288        }
289
290        for typ in api
291            .types
292            .iter()
293            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
294        {
295            if typ.is_opaque {
296                // Generate the opaque struct with separate #[php_class] and
297                // #[php(name = "Ns\\Type")] attributes (ext-php-rs 0.15+ syntax).
298                // Escape '\' in the namespace so the generated Rust string literal is valid.
299                let ns_escaped = php_namespace.replace('\\', "\\\\");
300                let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped, typ.name);
301                let opaque_attr_arr = ["php_class", php_name_attr.as_str()];
302                let opaque_cfg = RustBindingConfig {
303                    struct_attrs: &opaque_attr_arr,
304                    ..cfg
305                };
306                builder.add_item(&generators::gen_opaque_struct(typ, &opaque_cfg));
307                builder.add_item(&gen_opaque_struct_methods(
308                    typ,
309                    &mapper,
310                    &opaque_types,
311                    &core_import,
312                    &adapter_bodies,
313                    &mutex_types,
314                ));
315            } else {
316                // gen_struct adds #[derive(Default)] when typ.has_default is true,
317                // so no separate Default impl is needed.
318                builder.add_item(&gen_php_struct(
319                    typ,
320                    &mapper,
321                    &cfg,
322                    Some(&php_namespace),
323                    &enum_names,
324                    &lang_rename_all,
325                ));
326                builder.add_item(&types::gen_struct_methods_with_exclude(
327                    typ,
328                    &mapper,
329                    has_serde,
330                    &core_import,
331                    &opaque_types,
332                    &enum_names,
333                    &api.enums,
334                    &exclude_functions,
335                    &bridge_type_aliases_set,
336                    &never_skip_cfg_field_names,
337                    &mutex_types,
338                ));
339            }
340        }
341
342        for enum_def in &api.enums {
343            if is_tagged_data_enum(enum_def) {
344                // Tagged data enums (struct variants) are lowered to a flat PHP class.
345                builder.add_item(&gen_flat_data_enum(enum_def, &mapper, Some(&php_namespace)));
346                builder.add_item(&gen_flat_data_enum_methods(enum_def, &mapper));
347            } else {
348                builder.add_item(&gen_enum_constants(enum_def));
349            }
350        }
351
352        // Generate free functions as static methods on a facade class rather than standalone
353        // `#[php_function]` items. Standalone functions rely on the `inventory` crate for
354        // auto-registration, which does not work in cdylib builds on macOS. Classes registered
355        // via `.class::<T>()` in the module builder DO work on all platforms.
356        let included_functions: Vec<_> = api
357            .functions
358            .iter()
359            .filter(|f| !exclude_functions.contains(&f.name))
360            .collect();
361        if !included_functions.is_empty() {
362            let facade_class_name = extension_name.to_pascal_case();
363            // Build each static method body (no #[php_function] attribute — they live inside
364            // a #[php_impl] block which handles registration via the class machinery).
365            let mut method_items: Vec<String> = Vec::new();
366            for func in included_functions {
367                let bridge_param = crate::trait_bridge::find_bridge_param(func, &config.trait_bridges);
368                if let Some((param_idx, bridge_cfg)) = bridge_param {
369                    let bridge_handle_path = bridge_handle_path(api, bridge_cfg, &core_import);
370                    method_items.push(crate::trait_bridge::gen_bridge_function(
371                        func,
372                        param_idx,
373                        bridge_cfg,
374                        &mapper,
375                        &opaque_types,
376                        &core_import,
377                        &bridge_handle_path,
378                    ));
379                } else if func.is_async {
380                    method_items.push(gen_async_function_as_static_method(
381                        func,
382                        &mapper,
383                        &opaque_types,
384                        &core_import,
385                        &config.trait_bridges,
386                        &mutex_types,
387                    ));
388                } else {
389                    method_items.push(gen_function_as_static_method(
390                        func,
391                        &mapper,
392                        &opaque_types,
393                        &core_import,
394                        &config.trait_bridges,
395                        has_serde,
396                        &mutex_types,
397                    ));
398                }
399            }
400
401            let methods_joined = method_items
402                .iter()
403                .map(|m| {
404                    // Indent each line of each method by 4 spaces
405                    m.lines()
406                        .map(|l| {
407                            if l.is_empty() {
408                                String::new()
409                            } else {
410                                format!("    {l}")
411                            }
412                        })
413                        .collect::<Vec<_>>()
414                        .join("\n")
415                })
416                .collect::<Vec<_>>()
417                .join("\n\n");
418            // The PHP-visible class name gets an "Api" suffix to avoid collision with the
419            // PHP facade class (e.g. `Kreuzcrawl\Kreuzcrawl`) that Composer autoloads.
420            let php_api_class_name = format!("{facade_class_name}Api");
421            // Escape '\' so the generated Rust string literal is valid (e.g. "Ns\\ClassName").
422            let ns_escaped_facade = php_namespace.replace('\\', "\\\\");
423            let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped_facade, php_api_class_name);
424            let facade_struct = format!(
425                "#[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}}"
426            );
427            builder.add_item(&facade_struct);
428
429            // Trait bridge structs — top-level items (outside the facade class)
430            for bridge_cfg in &config.trait_bridges {
431                if let Some(trait_type) = api.types.iter().find(|t| t.is_trait && t.name == bridge_cfg.trait_name) {
432                    let bridge = crate::trait_bridge::gen_trait_bridge(
433                        trait_type,
434                        bridge_cfg,
435                        &core_import,
436                        &config.error_type_name(),
437                        &config.error_constructor_expr(),
438                        api,
439                    );
440                    for imp in &bridge.imports {
441                        builder.add_import(imp);
442                    }
443                    builder.add_item(&bridge.code);
444                }
445            }
446        }
447
448        let convertible = alef_codegen::conversions::convertible_types(api);
449        let core_to_binding = alef_codegen::conversions::core_to_binding_convertible_types(api);
450        let input_types = alef_codegen::conversions::input_type_names(api);
451        // From/Into conversions with PHP-specific i64 casts.
452        // Types with enum Named fields (or that reference such types transitively) can't
453        // have binding->core From impls because PHP maps enums to String and there's no
454        // From<String> for the core enum type. Core->binding is always safe.
455        let enum_names_ref = &mapper.enum_names;
456        let bridge_skip_types: Vec<String> = config
457            .trait_bridges
458            .iter()
459            .filter(|b| !matches!(b.bind_via, alef_core::config::BridgeBinding::OptionsField))
460            .filter_map(|b| b.type_alias.clone())
461            .collect();
462        // Trait-bridge fields whose binding-side wrapper holds `inner: Arc<core::T>`
463        // (every OptionsField-style bridge in alef follows this convention). Used by
464        // `binding_to_core` to emit `val.{f}.map(|v| (*v.inner).clone())` instead of
465        // `Default::default()` so the visitor handle survives the `.into()` call.
466        let trait_bridge_arc_wrapper_field_names: Vec<String> = config
467            .trait_bridges
468            .iter()
469            .filter(|b| b.bind_via == alef_core::config::BridgeBinding::OptionsField)
470            .filter_map(|b| b.resolved_options_field().map(String::from))
471            .collect();
472        // Set of opaque type names for ConversionConfig. Combines Rust `#[opaque]`
473        // types in the API with trait-bridge type aliases (e.g. VisitorHandle) so the
474        // `is_opaque_no_wrapper_field` branch in binding_to_core fires for those
475        // fields and emits the Arc-wrapper forwarding pattern.
476        let mut conv_opaque_types: AHashSet<String> = opaque_types.clone();
477        for bridge in &config.trait_bridges {
478            if let Some(alias) = &bridge.type_alias {
479                conv_opaque_types.insert(alias.clone());
480            }
481        }
482        let php_conv_config = ConversionConfig {
483            cast_large_ints_to_i64: true,
484            enum_string_names: Some(enum_names_ref),
485            untagged_data_enum_names: Some(&mapper.untagged_data_enum_names),
486            // PHP keeps `serde_json::Value` as-is in the binding struct (matches PhpMapper::json).
487            // `json_to_string` was previously enabled but caused `from_json` to fail when a JSON
488            // object/array landed in a `String`-typed field (e.g. tool `parameters` schema).
489            json_as_value: true,
490            include_cfg_metadata: false,
491            option_duration_on_defaults: true,
492            from_binding_skip_types: &bridge_skip_types,
493            never_skip_cfg_field_names: &never_skip_cfg_field_names,
494            opaque_types: Some(&conv_opaque_types),
495            trait_bridge_arc_wrapper_field_names: &trait_bridge_arc_wrapper_field_names,
496            ..Default::default()
497        };
498        // Build transitive set of types that can't have binding->core From
499        let mut enum_tainted: AHashSet<String> = AHashSet::new();
500        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
501            if has_enum_named_field(typ, enum_names_ref) {
502                enum_tainted.insert(typ.name.clone());
503            }
504        }
505        // Transitively mark types that reference enum-tainted types
506        let mut changed = true;
507        while changed {
508            changed = false;
509            for typ in api.types.iter().filter(|typ| !typ.is_trait) {
510                if !enum_tainted.contains(&typ.name)
511                    && binding_fields(&typ.fields).any(|f| references_named_type(&f.ty, &enum_tainted))
512                {
513                    enum_tainted.insert(typ.name.clone());
514                    changed = true;
515                }
516            }
517        }
518        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
519            // binding->core: only when not enum-tainted and type is used as input
520            if input_types.contains(&typ.name)
521                && !enum_tainted.contains(&typ.name)
522                && alef_codegen::conversions::can_generate_conversion(typ, &convertible)
523            {
524                builder.add_item(&alef_codegen::conversions::gen_from_binding_to_core_cfg(
525                    typ,
526                    &core_import,
527                    &php_conv_config,
528                ));
529            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) {
530                // Enum-tainted types: generate From with string->enum parsing for enum-Named
531                // fields, using first variant as fallback. Data-variant enum fields fill
532                // data fields with Default::default().
533                // Note: JSON roundtrip was previously used when has_serde=true, but that
534                // breaks on non-optional Duration fields (null != u64) and empty-string enum
535                // fields ("" is not a valid variant). Field-by-field conversion handles both.
536                builder.add_item(&gen_enum_tainted_from_binding_to_core(
537                    typ,
538                    &core_import,
539                    enum_names_ref,
540                    &enum_tainted,
541                    &php_conv_config,
542                    &api.enums,
543                    &bridge_type_aliases_set,
544                ));
545            }
546            // core->binding: always (enum->String via format, sanitized fields via format)
547            if alef_codegen::conversions::can_generate_conversion(typ, &core_to_binding) {
548                builder.add_item(&alef_codegen::conversions::gen_from_core_to_binding_cfg(
549                    typ,
550                    &core_import,
551                    &opaque_types,
552                    &php_conv_config,
553                ));
554            }
555        }
556
557        // From impls for tagged data enums lowered to flat PHP classes.
558        for enum_def in api.enums.iter().filter(|e| is_tagged_data_enum(e)) {
559            builder.add_item(&gen_flat_data_enum_from_impls(enum_def, &core_import));
560        }
561
562        // Error converter functions
563        for error in &api.errors {
564            builder.add_item(&alef_codegen::error_gen::gen_php_error_converter(error, &core_import));
565        }
566
567        // Serde default helpers for bool fields whose core default is `true`,
568        // and for SecurityLimits fields which use struct-level defaults.
569        // Referenced by #[serde(default = "crate::serde_defaults::...")] on struct fields.
570        if has_serde {
571            let serde_module = "mod serde_defaults {\n    pub fn bool_true() -> bool { true }\n\
572                   pub fn max_archive_size() -> i64 { 500 * 1024 * 1024 }\n\
573                   pub fn max_compression_ratio() -> i64 { 100 }\n\
574                   pub fn max_files_in_archive() -> i64 { 10_000 }\n\
575                   pub fn max_nesting_depth() -> i64 { 1024 }\n\
576                   pub fn max_entity_length() -> i64 { 1024 * 1024 }\n\
577                   pub fn max_content_size() -> i64 { 100 * 1024 * 1024 }\n\
578                   pub fn max_iterations() -> i64 { 10_000_000 }\n\
579                   pub fn max_xml_depth() -> i64 { 1024 }\n\
580                   pub fn max_table_cells() -> i64 { 100_000 }\n\
581                }";
582            builder.add_item(serde_module);
583        }
584
585        // Always enable abi_vectorcall on Windows — ext-php-rs requires the
586        // `vectorcall` calling convention for PHP entry points there. The feature
587        // is unstable on stable Rust; consumers either build with nightly or set
588        // RUSTC_BOOTSTRAP=1 (the upstream-recommended workaround). This cfg_attr
589        // is a no-op on non-windows so it costs nothing on Linux/macOS builds.
590        let php_config = config.php.as_ref();
591        builder.add_inner_attribute("cfg_attr(windows, feature(abi_vectorcall))");
592
593        // Optional feature gate — when [php].feature_gate is set, the entire crate
594        // is conditionally compiled. Use this for parity with PyO3's `extension-module`
595        // pattern; most PHP bindings don't need it.
596        if let Some(feature_name) = php_config.and_then(|c| c.feature_gate.as_deref()) {
597            builder.add_inner_attribute(&format!("cfg(feature = \"{feature_name}\")"));
598        }
599
600        // PHP module entry point — explicit class registration required because
601        // `inventory` crate auto-registration doesn't work in cdylib on macOS.
602        let mut class_registrations = String::new();
603        for typ in api
604            .types
605            .iter()
606            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
607        {
608            class_registrations.push_str(&crate::template_env::render(
609                "php_class_registration.jinja",
610                context! { class_name => &typ.name },
611            ));
612        }
613        // Register the facade class that wraps free functions as static methods.
614        if !api.functions.is_empty() {
615            let facade_class_name = extension_name.to_pascal_case();
616            class_registrations.push_str(&crate::template_env::render(
617                "php_class_registration.jinja",
618                context! { class_name => &format!("{facade_class_name}Api") },
619            ));
620        }
621        // Tagged data enums are lowered to flat PHP classes — register them like other classes.
622        // Unit-variant enums remain as string constants and don't need .class::<T>() registration.
623        for enum_def in api.enums.iter().filter(|e| is_tagged_data_enum(e)) {
624            class_registrations.push_str(&crate::template_env::render(
625                "php_class_registration.jinja",
626                context! { class_name => &enum_def.name },
627            ));
628        }
629        builder.add_item(&format!(
630            "#[php_module]\npub fn get_module(module: ModuleBuilder) -> ModuleBuilder {{\n    module{class_registrations}\n}}"
631        ));
632
633        let mut content = builder.build();
634
635        // Post-process generated code to replace the bridge builder method.
636        // The generated code produces `visitor(Option<&VisitorHandle>)` which is
637        // unreachable from PHP. Replace the entire method — signature and body —
638        // with one that accepts a ZendObject and builds the proper bridge handle.
639        for bridge in &config.trait_bridges {
640            if let Some(field_name) = bridge.resolved_options_field() {
641                let param_name = bridge.param_name.as_deref().unwrap_or(field_name);
642                let type_alias = bridge.type_alias.as_deref().unwrap_or("VisitorHandle");
643                let options_type = bridge.options_type.as_deref().unwrap_or("ConversionOptions");
644                let builder_type = format!("{}Builder", options_type);
645                let bridge_struct = format!("Php{}Bridge", bridge.trait_name);
646                let bridge_handle_path = bridge_handle_path(api, bridge, &core_import);
647
648                // Match the verbatim pre-rustfmt output from codegen.
649                // gen_instance_method produces 4-space-indented lines (signature + body),
650                // then ImplBuilder.build() adds 4 more spaces to every line → 8/8/4 indent.
651                // The body is a single-line Self { inner: Arc::new(...) } expression.
652                // rustfmt later reformats this to the 4/8/8/4 multi-line style on disk.
653                let old_method = format!(
654                    "        pub fn {field_name}(&self, {param_name}: Option<&{type_alias}>) -> {builder_type} {{\n        Self {{ inner: Arc::new((*self.inner).clone().{field_name}({param_name}.as_ref().map(|v| &v.inner))) }}\n    }}"
655                );
656                let new_method = format!(
657                    "        pub fn {field_name}(&self, {param_name}: &mut ext_php_rs::types::ZendObject) -> {builder_type} {{\n        let bridge = {bridge_struct}::new({param_name});\n        let handle: {bridge_handle_path} = std::sync::Arc::new(std::sync::Mutex::new(bridge));\n        Self {{ inner: Arc::new((*self.inner).clone().{field_name}(Some(handle))) }}\n    }}"
658                );
659
660                content = content.replace(&old_method, &new_method);
661            }
662        }
663
664        Ok(vec![GeneratedFile {
665            path: PathBuf::from(&output_dir).join("lib.rs"),
666            content,
667            generated_header: false,
668        }])
669    }
670
671    fn generate_public_api(
672        &self,
673        api: &ApiSurface,
674        config: &ResolvedCrateConfig,
675    ) -> anyhow::Result<Vec<GeneratedFile>> {
676        let extension_name = config.php_extension_name();
677        let class_name = extension_name.to_pascal_case();
678
679        // Generate PHP wrapper class
680        let mut content = String::new();
681        content.push_str(&crate::template_env::render(
682            "php_file_header.jinja",
683            minijinja::Value::default(),
684        ));
685        content.push_str(&hash::header(CommentStyle::DoubleSlash));
686        content.push_str(&crate::template_env::render(
687            "php_declare_strict_types.jinja",
688            minijinja::Value::default(),
689        ));
690        // PSR-12: blank line between `declare(strict_types=1);` and `namespace`.
691        content.push('\n');
692
693        // Determine namespace — delegates to config so [php].namespace overrides are respected.
694        let namespace = php_autoload_namespace(config);
695
696        content.push_str(&crate::template_env::render(
697            "php_namespace.jinja",
698            context! { namespace => &namespace },
699        ));
700        // PSR-12: blank line between `namespace` and class declaration.
701        content.push('\n');
702        content.push_str(&crate::template_env::render(
703            "php_facade_class_declaration.jinja",
704            context! { class_name => &class_name },
705        ));
706
707        // Build the set of bridge param names so they are excluded from public PHP signatures.
708        let bridge_param_names_pub: ahash::AHashSet<&str> = config
709            .trait_bridges
710            .iter()
711            .filter_map(|b| b.param_name.as_deref())
712            .collect();
713
714        // Config types whose PHP constructors can be called with zero arguments.
715        // Only qualifies when ALL fields are optional (PHP constructor needs no required args).
716        // `has_default` (Rust Default impl) is NOT sufficient — the PHP constructor is
717        // generated from struct fields and still requires non-optional ones.
718        let no_arg_constructor_types: AHashSet<String> = api
719            .types
720            .iter()
721            .filter(|t| t.fields.iter().all(|f| f.optional))
722            .map(|t| t.name.clone())
723            .collect();
724
725        // Generate wrapper methods for functions
726        for func in &api.functions {
727            // PHP method names are based on the Rust source name (camelCased).
728            // Async functions do not get a suffix because PHP blocks on async internally
729            // via `block_on`, presenting a synchronous API to callers.
730            // For example: `scrape` (async in Rust) → `scrape()` (sync from PHP perspective).
731            let method_name = func.name.to_lower_camel_case();
732            let return_php_type = php_type(&func.return_type);
733
734            // Visible params exclude bridge params (not surfaced to PHP callers).
735            let visible_params: Vec<_> = func
736                .params
737                .iter()
738                .filter(|p| !bridge_param_names_pub.contains(p.name.as_str()))
739                .collect();
740
741            // PHPDoc block
742            content.push_str(&crate::template_env::render(
743                "php_phpdoc_block_start.jinja",
744                minijinja::Value::default(),
745            ));
746            if func.doc.is_empty() {
747                content.push_str(&crate::template_env::render(
748                    "php_phpdoc_text_line.jinja",
749                    context! { text => &format!("{}.", method_name) },
750                ));
751            } else {
752                content.push_str(&crate::template_env::render(
753                    "php_phpdoc_lines.jinja",
754                    context! {
755                        doc_lines => func.doc.lines().collect::<Vec<_>>(),
756                        indent => "     ",
757                    },
758                ));
759            }
760            content.push_str(&crate::template_env::render(
761                "php_phpdoc_empty_line.jinja",
762                minijinja::Value::default(),
763            ));
764            for p in &visible_params {
765                let ptype = php_phpdoc_type(&p.ty);
766                let nullable_prefix = if p.optional { "?" } else { "" };
767                content.push_str(&crate::template_env::render(
768                    "php_phpdoc_param_line.jinja",
769                    context! {
770                        nullable_prefix => nullable_prefix,
771                        param_type => &ptype,
772                        param_name => &p.name,
773                    },
774                ));
775            }
776            let return_phpdoc = php_phpdoc_type(&func.return_type);
777            content.push_str(&crate::template_env::render(
778                "php_phpdoc_return_line.jinja",
779                context! { return_type => &return_phpdoc },
780            ));
781            if func.error_type.is_some() {
782                content.push_str(&crate::template_env::render(
783                    "php_phpdoc_throws_line.jinja",
784                    context! {
785                        namespace => namespace.as_str(),
786                        class_name => &class_name,
787                    },
788                ));
789            }
790            content.push_str(&crate::template_env::render(
791                "php_phpdoc_block_end.jinja",
792                minijinja::Value::default(),
793            ));
794
795            // Method signature with type hints.
796            // Keep parameters in their original Rust order.
797            // Since PHP doesn't allow optional params before required ones, and some Rust
798            // functions have optional params in the middle, we must make all params after
799            // the first optional one also optional (nullable with null default).
800            // This ensures e2e generated test code (which uses Rust param order) will work.
801            // Additionally, config-like parameters (Named types ending in "Config") should
802            // be treated as optional for PHP even if not explicitly marked as such in the IR.
803            // Helper: a config param is only treated as optional when its type can be
804            // constructed with zero arguments (all fields are optional in the IR).
805            let is_optional_config_param = |p: &alef_core::ir::ParamDef| -> bool {
806                if let TypeRef::Named(name) = &p.ty {
807                    (name.ends_with("Config") || name.as_str() == "config")
808                        && no_arg_constructor_types.contains(name.as_str())
809                } else {
810                    false
811                }
812            };
813
814            let mut first_optional_idx = None;
815            for (idx, p) in visible_params.iter().enumerate() {
816                if p.optional || is_optional_config_param(p) {
817                    first_optional_idx = Some(idx);
818                    break;
819                }
820            }
821
822            content.push_str(&crate::template_env::render(
823                "php_method_signature_start.jinja",
824                context! { method_name => &method_name },
825            ));
826
827            let params: Vec<String> = visible_params
828                .iter()
829                .enumerate()
830                .map(|(idx, p)| {
831                    let ptype = php_type(&p.ty);
832                    // Make param optional if:
833                    // 1. It's explicitly optional OR
834                    // 2. It's a config parameter with a no-arg constructor OR
835                    // 3. It comes after the first optional/config param
836                    let should_be_optional = p.optional
837                        || is_optional_config_param(p)
838                        || first_optional_idx.is_some_and(|first| idx >= first);
839                    if should_be_optional {
840                        format!("?{} ${} = null", ptype, p.name)
841                    } else {
842                        format!("{} ${}", ptype, p.name)
843                    }
844                })
845                .collect();
846            content.push_str(&params.join(", "));
847            content.push_str(&crate::template_env::render(
848                "php_method_signature_end.jinja",
849                context! { return_type => &return_php_type },
850            ));
851            // Delegate to the native extension class (registered as `{namespace}\{class_name}Api`).
852            // ext-php-rs auto-converts Rust snake_case to PHP camelCase.
853            // PHP does not expose async — async behaviour is handled internally via Tokio
854            // block_on, so the Rust function name matches the PHP method name exactly.
855            let ext_method_name = func.name.to_lower_camel_case();
856            let is_void = matches!(&func.return_type, TypeRef::Unit);
857            // Pass parameters to the native function in their ORIGINAL order (not sorted).
858            // The native extension expects parameters in the order defined in the Rust function.
859            // The PHP facade reorders them only in its own signature for PHP syntax compliance,
860            // but must pass them in the original order when calling the native method.
861            // Config-type params that were made optional (nullable) in the facade must be
862            // coerced to their default constructor when null, since the native ext requires
863            // non-nullable objects.
864            let call_params = visible_params
865                .iter()
866                .enumerate()
867                .map(|(idx, p)| {
868                    let should_be_optional = p.optional
869                        || is_optional_config_param(p)
870                        || first_optional_idx.is_some_and(|first| idx >= first);
871                    if should_be_optional && is_optional_config_param(p) {
872                        if let TypeRef::Named(type_name) = &p.ty {
873                            return format!("${} ?? new {}()", p.name, type_name);
874                        }
875                    }
876                    format!("${}", p.name)
877                })
878                .collect::<Vec<_>>()
879                .join(", ");
880            let call_expr = format!("\\{namespace}\\{class_name}Api::{ext_method_name}({call_params})");
881            if is_void {
882                content.push_str(&crate::template_env::render(
883                    "php_method_call_statement.jinja",
884                    context! { call_expr => &call_expr },
885                ));
886            } else {
887                content.push_str(&crate::template_env::render(
888                    "php_method_call_return.jinja",
889                    context! { call_expr => &call_expr },
890                ));
891            }
892            content.push_str(&crate::template_env::render(
893                "php_method_end.jinja",
894                minijinja::Value::default(),
895            ));
896        }
897
898        content.push_str(&crate::template_env::render(
899            "php_class_end.jinja",
900            minijinja::Value::default(),
901        ));
902
903        // Use PHP stubs output path if configured, otherwise fall back to packages/php/src/.
904        // This is intentionally separate from config.output.php, which controls the Rust binding
905        // crate output directory (e.g., crates/kreuzcrawl-php/src/).
906        let output_dir = config
907            .php
908            .as_ref()
909            .and_then(|p| p.stubs.as_ref())
910            .map(|s| s.output.to_string_lossy().to_string())
911            .unwrap_or_else(|| "packages/php/src/".to_string());
912
913        let mut files: Vec<GeneratedFile> = Vec::new();
914        files.push(GeneratedFile {
915            path: PathBuf::from(&output_dir).join(format!("{}.php", class_name)),
916            content,
917            generated_header: false,
918        });
919
920        // Emit a per-opaque-type PHP class file alongside the facade. These provide
921        // method declarations for static analysis (PHPStan) and IDE autocomplete.
922        // The native PHP extension registers the same class names at module load
923        // (before Composer autoload runs), so these userland files are never
924        // included at runtime — the native class always wins.
925        for typ in api.types.iter().filter(|t| t.is_opaque && !t.is_trait) {
926            let opaque_file = gen_php_opaque_class_file(typ, &namespace);
927            files.push(GeneratedFile {
928                path: PathBuf::from(&output_dir).join(format!("{}.php", typ.name)),
929                content: opaque_file,
930                generated_header: false,
931            });
932        }
933
934        Ok(files)
935    }
936
937    fn generate_type_stubs(
938        &self,
939        api: &ApiSurface,
940        config: &ResolvedCrateConfig,
941    ) -> anyhow::Result<Vec<GeneratedFile>> {
942        let extension_name = config.php_extension_name();
943        let class_name = extension_name.to_pascal_case();
944
945        // Determine namespace — delegates to config so [php].namespace overrides are respected.
946        let namespace = php_autoload_namespace(config);
947
948        // PSR-12 requires a blank line after the opening `<?php` tag.
949        // php-cs-fixer enforces this and would insert it post-write,
950        // making `alef verify` see content that differs from what was
951        // freshly generated. Emit it here so generated == on-disk.
952        let mut content = String::new();
953        content.push_str(&crate::template_env::render(
954            "php_file_header.jinja",
955            minijinja::Value::default(),
956        ));
957        content.push_str(&hash::header(CommentStyle::DoubleSlash));
958        content.push_str("// Type stubs for the native PHP extension — declares classes\n");
959        content.push_str("// provided at runtime by the compiled Rust extension (.so/.dll).\n");
960        content.push_str("// Include this in phpstan.neon scanFiles for static analysis.\n\n");
961        content.push_str(&crate::template_env::render(
962            "php_declare_strict_types.jinja",
963            minijinja::Value::default(),
964        ));
965        // PSR-12: blank line between `declare(strict_types=1);` and `namespace`.
966        content.push('\n');
967        // Use bracketed namespace syntax so we can add global-namespace function stubs later.
968        content.push_str(&crate::template_env::render(
969            "php_namespace_block_begin.jinja",
970            context! { namespace => &namespace },
971        ));
972
973        // Exception class
974        content.push_str(&crate::template_env::render(
975            "php_exception_class_declaration.jinja",
976            context! { class_name => &class_name },
977        ));
978        content.push_str(
979            "    public function getErrorCode(): int { throw new \\RuntimeException('Not implemented.'); }\n",
980        );
981        content.push_str("}\n\n");
982
983        // Opaque handle classes are declared as per-type PHP files in
984        // `packages/php/src/{TypeName}.php` (see `generate_public_api`). They
985        // are intentionally omitted from this aggregate extension stub so PHPStan
986        // does not see two class declarations for the same fully-qualified name.
987
988        // Record / struct types (non-opaque with fields)
989        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
990            if typ.is_opaque || typ.fields.is_empty() {
991                continue;
992            }
993            if !typ.doc.is_empty() {
994                content.push_str("/**\n");
995                content.push_str(&crate::template_env::render(
996                    "php_phpdoc_lines.jinja",
997                    context! {
998                        doc_lines => typ.doc.lines().collect::<Vec<_>>(),
999                        indent => "",
1000                    },
1001                ));
1002                content.push_str(" */\n");
1003            }
1004            content.push_str(&crate::template_env::render(
1005                "php_record_class_stub_declaration.jinja",
1006                context! { class_name => &typ.name },
1007            ));
1008
1009            // PHP 8.3+ constructor property promotion with `public readonly`.
1010            // Required parameters come before optional ones (PHP syntax requirement).
1011            let mut sorted_fields: Vec<&alef_core::ir::FieldDef> = binding_fields(&typ.fields).collect();
1012            sorted_fields.sort_by_key(|f| f.optional);
1013
1014            // Promoted readonly parameters replace both separate property declarations
1015            // and redundant getter methods — direct property access is the PHP 8.3+ idiom.
1016            // Each promoted parameter gets an inline /** @var T [description] */ block so that
1017            // phpdoc-lint (phpstan level max) and IDEs see the precise generic type and field docs.
1018            let params: Vec<String> = sorted_fields
1019                .iter()
1020                .map(|f| {
1021                    let ptype = php_type(&f.ty);
1022                    let nullable = if f.optional && !ptype.starts_with('?') {
1023                        format!("?{ptype}")
1024                    } else {
1025                        ptype
1026                    };
1027                    let default = if f.optional { " = null" } else { "" };
1028                    let php_name = to_php_name(&f.name);
1029                    let phpdoc_type = php_phpdoc_type(&f.ty);
1030                    let var_type = if f.optional && !phpdoc_type.starts_with('?') {
1031                        format!("?{phpdoc_type}")
1032                    } else {
1033                        phpdoc_type
1034                    };
1035                    let phpdoc = php_property_phpdoc(&var_type, &f.doc, "        ");
1036                    format!("{phpdoc}        public readonly {nullable} ${php_name}{default}",)
1037                })
1038                .collect();
1039            content.push_str(&crate::template_env::render(
1040                "php_constructor_method.jinja",
1041                context! { params => &params.join(",\n") },
1042            ));
1043
1044            content.push_str("}\n\n");
1045        }
1046
1047        // Emit tagged data enums as classes (they're lowered to flat PHP classes in the binding).
1048        // Unit-variant enums → PHP 8.1+ enum constants.
1049        for enum_def in &api.enums {
1050            if is_tagged_data_enum(enum_def) {
1051                // Tagged data enums are lowered to flat classes; emit class stubs.
1052                if !enum_def.doc.is_empty() {
1053                    content.push_str("/**\n");
1054                    content.push_str(&crate::template_env::render(
1055                        "php_phpdoc_lines.jinja",
1056                        context! {
1057                            doc_lines => enum_def.doc.lines().collect::<Vec<_>>(),
1058                            indent => "",
1059                        },
1060                    ));
1061                    content.push_str(" */\n");
1062                }
1063                content.push_str(&crate::template_env::render(
1064                    "php_record_class_stub_declaration.jinja",
1065                    context! { class_name => &enum_def.name },
1066                ));
1067                content.push_str("}\n\n");
1068            } else {
1069                // Unit-variant enums → PHP 8.1+ enum constants.
1070                content.push_str(&crate::template_env::render(
1071                    "php_tagged_enum_declaration.jinja",
1072                    context! { enum_name => &enum_def.name },
1073                ));
1074                for variant in &enum_def.variants {
1075                    let case_name = sanitize_php_enum_case(&variant.name);
1076                    content.push_str(&crate::template_env::render(
1077                        "php_enum_variant_stub.jinja",
1078                        context! {
1079                            variant_name => case_name,
1080                            value => &variant.name,
1081                        },
1082                    ));
1083                }
1084                content.push_str("}\n\n");
1085            }
1086        }
1087
1088        // Extension function stubs — generated as a native `{ClassName}Api` class with static
1089        // methods. The PHP facade (`{ClassName}`) delegates to `{ClassName}Api::method()`.
1090        // Using a class instead of global functions avoids the `inventory` crate registration
1091        // issue on macOS (cdylib builds do not collect `#[php_function]` entries there).
1092        if !api.functions.is_empty() {
1093            // Bridge params are hidden from the PHP-visible API in stubs too.
1094            let bridge_param_names_stubs: ahash::AHashSet<&str> = config
1095                .trait_bridges
1096                .iter()
1097                .filter_map(|b| b.param_name.as_deref())
1098                .collect();
1099
1100            content.push_str(&crate::template_env::render(
1101                "php_api_class_declaration.jinja",
1102                context! { class_name => &class_name },
1103            ));
1104            for func in &api.functions {
1105                let return_type = php_type_fq(&func.return_type, &namespace);
1106                let return_phpdoc = php_phpdoc_type_fq(&func.return_type, &namespace);
1107                // Visible params exclude bridge params.
1108                let visible_params: Vec<_> = func
1109                    .params
1110                    .iter()
1111                    .filter(|p| !bridge_param_names_stubs.contains(p.name.as_str()))
1112                    .collect();
1113                // Stubs declare the ACTUAL native interface, which has parameters in their original order
1114                // (ext-php-rs doesn't reorder them). DO NOT sort them here.
1115                // The PHP facade may reorder them for syntax compliance, but the stub must match
1116                // the actual native extension signature.
1117                // Emit PHPDoc when any param or the return type is an array, so PHPStan
1118                // understands generic element types (e.g. array<string> vs bare array).
1119                let has_array_params = visible_params
1120                    .iter()
1121                    .any(|p| matches!(&p.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)));
1122                let has_array_return = matches!(&func.return_type, TypeRef::Vec(_) | TypeRef::Map(_, _))
1123                    || matches!(&func.return_type, TypeRef::Optional(inner) if matches!(inner.as_ref(), TypeRef::Vec(_) | TypeRef::Map(_, _)));
1124                let first_optional_idx = visible_params.iter().position(|p| p.optional);
1125                if has_array_params || has_array_return {
1126                    content.push_str("    /**\n");
1127                    for (idx, p) in visible_params.iter().enumerate() {
1128                        let ptype = php_phpdoc_type_fq(&p.ty, &namespace);
1129                        let nullable_prefix = if p.optional || first_optional_idx.is_some_and(|first| idx >= first) {
1130                            "?"
1131                        } else {
1132                            ""
1133                        };
1134                        content.push_str(&crate::template_env::render(
1135                            "php_phpdoc_static_param.jinja",
1136                            context! {
1137                                nullable_prefix => nullable_prefix,
1138                                ptype => &ptype,
1139                                param_name => &p.name,
1140                            },
1141                        ));
1142                    }
1143                    content.push_str(&crate::template_env::render(
1144                        "php_phpdoc_static_return.jinja",
1145                        context! { return_phpdoc => &return_phpdoc },
1146                    ));
1147                    content.push_str("     */\n");
1148                }
1149                let params: Vec<String> = visible_params
1150                    .iter()
1151                    .enumerate()
1152                    .map(|(idx, p)| {
1153                        let ptype = php_type_fq(&p.ty, &namespace);
1154                        if p.optional || first_optional_idx.is_some_and(|first| idx >= first) {
1155                            let nullable_ptype = if ptype.starts_with('?') {
1156                                ptype
1157                            } else {
1158                                format!("?{ptype}")
1159                            };
1160                            format!("{} ${} = null", nullable_ptype, p.name)
1161                        } else {
1162                            format!("{} ${}", ptype, p.name)
1163                        }
1164                    })
1165                    .collect();
1166                // ext-php-rs auto-converts Rust snake_case to PHP camelCase.
1167                // PHP does not expose async — async behaviour is handled internally via
1168                // Tokio block_on, so the stub method name matches the Rust function name.
1169                let stub_method_name = func.name.to_lower_camel_case();
1170                let is_void_stub = return_type == "void";
1171                let stub_body = if is_void_stub {
1172                    "{ }".to_string()
1173                } else {
1174                    "{ throw new \\RuntimeException('Not implemented.'); }".to_string()
1175                };
1176                content.push_str(&crate::template_env::render(
1177                    "php_static_method_stub.jinja",
1178                    context! {
1179                        method_name => &stub_method_name,
1180                        params => &params.join(", "),
1181                        return_type => &return_type,
1182                        stub_body => &stub_body,
1183                    },
1184                ));
1185            }
1186            content.push_str("}\n\n");
1187        }
1188
1189        // Close the namespaced block
1190        content.push_str(&crate::template_env::render(
1191            "php_namespace_block_end.jinja",
1192            minijinja::Value::default(),
1193        ));
1194
1195        // Use stubs output path if configured, otherwise packages/php/stubs/
1196        let output_dir = config
1197            .php
1198            .as_ref()
1199            .and_then(|p| p.stubs.as_ref())
1200            .map(|s| s.output.to_string_lossy().to_string())
1201            .unwrap_or_else(|| "packages/php/stubs/".to_string());
1202
1203        Ok(vec![GeneratedFile {
1204            path: PathBuf::from(&output_dir).join(format!("{}_extension.php", extension_name)),
1205            content,
1206            generated_header: false,
1207        }])
1208    }
1209
1210    fn build_config(&self) -> Option<BuildConfig> {
1211        Some(BuildConfig {
1212            tool: "cargo",
1213            crate_suffix: "-php",
1214            build_dep: BuildDependency::None,
1215            post_build: vec![],
1216        })
1217    }
1218}
1219
1220fn bridge_handle_path(api: &ApiSurface, bridge: &alef_core::config::TraitBridgeConfig, core_import: &str) -> String {
1221    let alias = bridge.type_alias.as_deref().unwrap_or("VisitorHandle");
1222    api.types
1223        .iter()
1224        .find(|t| t.name == alias && !t.rust_path.is_empty())
1225        .map(|t| t.rust_path.replace('-', "_"))
1226        .or_else(|| api.excluded_type_paths.get(alias).map(|path| path.replace('-', "_")))
1227        .unwrap_or_else(|| format!("{core_import}::visitor::{alias}"))
1228}
1229
1230/// Map an IR [`TypeRef`] to a PHPDoc type string with generic parameters (e.g., `array<string>`).
1231/// PHPStan at level `max` requires iterable value types in PHPDoc annotations.
1232fn php_phpdoc_type(ty: &TypeRef) -> String {
1233    match ty {
1234        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type(inner)),
1235        TypeRef::Map(k, v) => format!("array<{}, {}>", php_phpdoc_type(k), php_phpdoc_type(v)),
1236        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type(inner)),
1237        _ => php_type(ty),
1238    }
1239}
1240
1241/// Map an IR [`TypeRef`] to a fully-qualified PHPDoc type string with generics (e.g., `array<\Ns\T>`).
1242fn php_phpdoc_type_fq(ty: &TypeRef, namespace: &str) -> String {
1243    match ty {
1244        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type_fq(inner, namespace)),
1245        TypeRef::Map(k, v) => format!(
1246            "array<{}, {}>",
1247            php_phpdoc_type_fq(k, namespace),
1248            php_phpdoc_type_fq(v, namespace)
1249        ),
1250        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
1251        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type_fq(inner, namespace)),
1252        _ => php_type(ty),
1253    }
1254}
1255
1256/// Map an IR [`TypeRef`] to a fully-qualified PHP type-hint string for use outside the namespace.
1257fn php_type_fq(ty: &TypeRef, namespace: &str) -> String {
1258    match ty {
1259        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
1260        TypeRef::Optional(inner) => {
1261            let inner_type = php_type_fq(inner, namespace);
1262            if inner_type.starts_with('?') {
1263                inner_type
1264            } else {
1265                format!("?{inner_type}")
1266            }
1267        }
1268        _ => php_type(ty),
1269    }
1270}
1271
1272/// Generate a per-opaque-type PHP class file for `packages/php/src/{TypeName}.php`.
1273///
1274/// The native ext-php-rs extension registers the same class at module load time
1275/// (before Composer autoload runs), so this userland file is never included at
1276/// runtime — the native class always wins. The file is consumed by PHPStan and
1277/// IDEs as the authoritative declaration of the type's public API surface.
1278fn gen_php_opaque_class_file(typ: &alef_core::ir::TypeDef, namespace: &str) -> String {
1279    let mut content = String::new();
1280    content.push_str(&crate::template_env::render(
1281        "php_file_header.jinja",
1282        minijinja::Value::default(),
1283    ));
1284    content.push_str(&hash::header(CommentStyle::DoubleSlash));
1285    content.push_str(&crate::template_env::render(
1286        "php_declare_strict_types.jinja",
1287        minijinja::Value::default(),
1288    ));
1289    // PSR-12: blank line between `declare(strict_types=1);` and `namespace`.
1290    content.push('\n');
1291    content.push_str(&crate::template_env::render(
1292        "php_namespace.jinja",
1293        context! { namespace => namespace },
1294    ));
1295    // PSR-12: blank line between `namespace` and class declaration.
1296    content.push('\n');
1297
1298    // Type-level docblock.
1299    if !typ.doc.is_empty() {
1300        content.push_str("/**\n");
1301        content.push_str(&crate::template_env::render(
1302            "php_phpdoc_lines.jinja",
1303            context! {
1304                doc_lines => typ.doc.lines().collect::<Vec<_>>(),
1305                indent => "",
1306            },
1307        ));
1308        content.push_str(" */\n");
1309    }
1310
1311    content.push_str(&format!("final class {}\n{{\n", typ.name));
1312
1313    // Instance methods first, static methods second.
1314    let mut method_order: Vec<&alef_core::ir::MethodDef> = Vec::new();
1315    method_order.extend(typ.methods.iter().filter(|m| m.receiver.is_some()));
1316    method_order.extend(typ.methods.iter().filter(|m| m.receiver.is_none()));
1317
1318    for method in method_order {
1319        let method_name = method.name.to_lower_camel_case();
1320        let return_type = php_type(&method.return_type);
1321        let is_void = matches!(&method.return_type, TypeRef::Unit);
1322        let is_static = method.receiver.is_none();
1323
1324        // PHPDoc block — keep it short to avoid line-width issues.
1325        let mut doc_lines: Vec<String> = vec![];
1326        let doc_line = method.doc.lines().next().unwrap_or("").trim();
1327        if !doc_line.is_empty() {
1328            doc_lines.push(doc_line.to_string());
1329        }
1330
1331        // Add @param PHPDoc for array parameters so PHPStan knows the element type
1332        let mut phpdoc_params: Vec<String> = vec![];
1333        for param in &method.params {
1334            if matches!(&param.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)) {
1335                let phpdoc_type = php_phpdoc_type(&param.ty);
1336                phpdoc_params.push(format!("@param {} ${}", phpdoc_type, param.name));
1337            }
1338        }
1339        doc_lines.extend(phpdoc_params);
1340
1341        // Add @return PHPDoc for array types so PHPStan knows the element type
1342        let needs_return_phpdoc = matches!(&method.return_type, TypeRef::Vec(_) | TypeRef::Map(_, _));
1343        if needs_return_phpdoc {
1344            let phpdoc_type = php_phpdoc_type(&method.return_type);
1345            doc_lines.push(format!("@return {phpdoc_type}"));
1346        }
1347
1348        // Emit PHPDoc if needed
1349        if !doc_lines.is_empty() {
1350            content.push_str("    /**\n");
1351            for line in doc_lines {
1352                content.push_str(&format!("     * {}\n", line));
1353            }
1354            content.push_str("     */\n");
1355        }
1356
1357        // Method signature.
1358        let static_kw = if is_static { "static " } else { "" };
1359        let first_optional_idx = method.params.iter().position(|p| p.optional);
1360        let params: Vec<String> = method
1361            .params
1362            .iter()
1363            .enumerate()
1364            .map(|(idx, p)| {
1365                let ptype = php_type(&p.ty);
1366                if p.optional || first_optional_idx.is_some_and(|first| idx >= first) {
1367                    let nullable = if ptype.starts_with('?') { "" } else { "?" };
1368                    format!("{nullable}{ptype} ${} = null", p.name)
1369                } else {
1370                    format!("{} ${}", ptype, p.name)
1371                }
1372            })
1373            .collect();
1374        content.push_str(&format!(
1375            "    public {static_kw}function {method_name}({}): {return_type}\n",
1376            params.join(", ")
1377        ));
1378        let body = if is_void {
1379            "    {\n    }\n"
1380        } else {
1381            "    {\n        throw new \\RuntimeException('Not implemented — provided by the native extension.');\n    }\n"
1382        };
1383        content.push_str(body);
1384    }
1385
1386    content.push_str("}\n");
1387    content
1388}
1389
1390/// Map an IR [`TypeRef`] to a PHP type-hint string.
1391fn php_type(ty: &TypeRef) -> String {
1392    match ty {
1393        TypeRef::String | TypeRef::Char | TypeRef::Json | TypeRef::Bytes | TypeRef::Path => "string".to_string(),
1394        TypeRef::Primitive(p) => match p {
1395            PrimitiveType::Bool => "bool".to_string(),
1396            PrimitiveType::F32 | PrimitiveType::F64 => "float".to_string(),
1397            PrimitiveType::U8
1398            | PrimitiveType::U16
1399            | PrimitiveType::U32
1400            | PrimitiveType::U64
1401            | PrimitiveType::I8
1402            | PrimitiveType::I16
1403            | PrimitiveType::I32
1404            | PrimitiveType::I64
1405            | PrimitiveType::Usize
1406            | PrimitiveType::Isize => "int".to_string(),
1407        },
1408        TypeRef::Optional(inner) => {
1409            // Flatten nested Option<Option<T>> to a single nullable type.
1410            // PHP has no double-nullable concept; ?T already covers null.
1411            let inner_type = php_type(inner);
1412            if inner_type.starts_with('?') {
1413                inner_type
1414            } else {
1415                format!("?{inner_type}")
1416            }
1417        }
1418        TypeRef::Vec(_) | TypeRef::Map(_, _) => "array".to_string(),
1419        TypeRef::Named(name) => name.clone(),
1420        TypeRef::Unit => "void".to_string(),
1421        TypeRef::Duration => "float".to_string(),
1422    }
1423}
1424
1425/// Build an inline PHPDoc block for a class property or constructor-promoted parameter.
1426///
1427/// - When `doc` is non-empty and multi-line, emits a multi-line block with description lines
1428///   followed by an `@var` tag.
1429/// - When `doc` is non-empty and single-line, emits a compact `/** @var T Description. */` form.
1430/// - When `doc` is empty, emits the type-only compact form `/** @var T */`.
1431///
1432/// `indent` is prepended to every line of the output (typically 4 or 8 spaces).
1433fn php_property_phpdoc(var_type: &str, doc: &str, indent: &str) -> String {
1434    let doc = doc.trim();
1435    if doc.is_empty() {
1436        return format!("{indent}/** @var {var_type} */\n");
1437    }
1438    let lines: Vec<&str> = doc.lines().collect();
1439    if lines.len() == 1 {
1440        let line = lines[0].trim();
1441        return format!("{indent}/** @var {var_type} {line} */\n");
1442    }
1443    // Multi-line: description block + @var tag.
1444    let mut out = format!("{indent}/**\n");
1445    for line in &lines {
1446        let trimmed = line.trim();
1447        if trimmed.is_empty() {
1448            out.push_str(&format!("{indent} *\n"));
1449        } else {
1450            out.push_str(&format!("{indent} * {trimmed}\n"));
1451        }
1452    }
1453    out.push_str(&format!("{indent} *\n"));
1454    out.push_str(&format!("{indent} * @var {var_type}\n"));
1455    out.push_str(&format!("{indent} */\n"));
1456    out
1457}