Skip to main content

alef_backend_php/gen_bindings/
mod.rs

1mod functions;
2mod helpers;
3mod 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_core::backend::{Backend, BuildConfig, Capabilities, GeneratedFile};
12use alef_core::config::{AlefConfig, Language, detect_serde_available, resolve_output_dir};
13use alef_core::ir::ApiSurface;
14use alef_core::ir::{PrimitiveType, TypeRef};
15use heck::{ToLowerCamelCase, ToPascalCase};
16use std::path::PathBuf;
17
18use functions::{gen_async_function_as_static_method, gen_function_as_static_method};
19use helpers::{
20    gen_enum_tainted_from_binding_to_core, gen_serde_bridge_from, gen_tokio_runtime, has_enum_named_field,
21    references_named_type,
22};
23use types::{gen_enum_constants, gen_opaque_struct_methods, gen_php_struct};
24
25pub struct PhpBackend;
26
27impl PhpBackend {
28    fn binding_config(core_import: &str, has_serde: bool) -> RustBindingConfig<'_> {
29        RustBindingConfig {
30            struct_attrs: &["php_class"],
31            field_attrs: &[],
32            struct_derives: &["Clone"],
33            method_block_attr: Some("php_impl"),
34            constructor_attr: "",
35            static_attr: None,
36            function_attr: "#[php_function]",
37            enum_attrs: &[],
38            enum_derives: &[],
39            needs_signature: false,
40            signature_prefix: "",
41            signature_suffix: "",
42            core_import,
43            async_pattern: AsyncPattern::TokioBlockOn,
44            has_serde,
45            type_name_prefix: "",
46            option_duration_on_defaults: true,
47            opaque_type_names: &[],
48        }
49    }
50}
51
52impl Backend for PhpBackend {
53    fn name(&self) -> &str {
54        "php"
55    }
56
57    fn language(&self) -> Language {
58        Language::Php
59    }
60
61    fn capabilities(&self) -> Capabilities {
62        Capabilities {
63            supports_async: true,
64            supports_classes: true,
65            supports_enums: true,
66            supports_option: true,
67            supports_result: true,
68            ..Capabilities::default()
69        }
70    }
71
72    fn generate_bindings(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
73        let enum_names = api.enums.iter().map(|e| e.name.clone()).collect();
74        let mapper = PhpMapper { enum_names };
75        let core_import = config.core_import();
76
77        // Get exclusion lists from PHP config
78        let php_config = config.php.as_ref();
79        let exclude_functions = php_config.map(|c| c.exclude_functions.clone()).unwrap_or_default();
80        let exclude_types = php_config.map(|c| c.exclude_types.clone()).unwrap_or_default();
81
82        let output_dir = resolve_output_dir(
83            config.output.php.as_ref(),
84            &config.crate_config.name,
85            "crates/{name}-php/src/",
86        );
87        let has_serde = detect_serde_available(&output_dir);
88        let cfg = Self::binding_config(&core_import, has_serde);
89
90        // Build the inner module content (types, methods, conversions)
91        let mut builder = RustFileBuilder::new();
92        builder.add_inner_attribute("allow(dead_code, unused_imports, unused_variables)");
93        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)");
94        builder.add_import("ext_php_rs::prelude::*");
95
96        // Import serde_json when available (needed for serde-based param conversion)
97        if has_serde {
98            builder.add_import("serde_json");
99        }
100
101        // Import traits needed for trait method dispatch
102        for trait_path in generators::collect_trait_imports(api) {
103            builder.add_import(&trait_path);
104        }
105
106        // Only import HashMap when Map-typed fields or returns are present
107        let has_maps = api.types.iter().any(|t| {
108            t.fields
109                .iter()
110                .any(|f| matches!(&f.ty, alef_core::ir::TypeRef::Map(_, _)))
111        }) || api
112            .functions
113            .iter()
114            .any(|f| matches!(&f.return_type, alef_core::ir::TypeRef::Map(_, _)));
115        if has_maps {
116            builder.add_import("std::collections::HashMap");
117        }
118
119        // Custom module declarations
120        let custom_mods = config.custom_modules.for_language(Language::Php);
121        for module in custom_mods {
122            builder.add_item(&format!("pub mod {module};"));
123        }
124
125        // Check if any function or method is async
126        let has_async =
127            api.functions.iter().any(|f| f.is_async) || api.types.iter().any(|t| t.methods.iter().any(|m| m.is_async));
128
129        if has_async {
130            builder.add_item(&gen_tokio_runtime());
131        }
132
133        // Check if we have opaque types and add Arc import if needed
134        let opaque_types: AHashSet<String> = api
135            .types
136            .iter()
137            .filter(|t| t.is_opaque)
138            .map(|t| t.name.clone())
139            .collect();
140        if !opaque_types.is_empty() {
141            builder.add_import("std::sync::Arc");
142        }
143
144        // Enum names for PHP property classification — enums are mapped as String,
145        // so Named(enum) fields should be treated as scalar props not getters.
146        let enum_names: AHashSet<String> = api.enums.iter().map(|e| e.name.clone()).collect();
147
148        // Compute the PHP namespace for namespaced class registration.
149        // Uses the same logic as `generate_public_api` / `generate_type_stubs`.
150        let extension_name = config.php_extension_name();
151        let php_namespace = if extension_name.contains('_') {
152            let parts: Vec<&str> = extension_name.split('_').collect();
153            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
154            ns_parts.join("\\")
155        } else {
156            extension_name.to_pascal_case()
157        };
158
159        // Build adapter body map before type iteration so bodies are available for method generation.
160        let adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Php)?;
161
162        // Emit adapter-generated standalone items (streaming iterators, callback bridges).
163        for adapter in &config.adapters {
164            match adapter.pattern {
165                alef_core::config::AdapterPattern::Streaming => {
166                    let key = format!("{}.__stream_struct__", adapter.item_type.as_deref().unwrap_or(""));
167                    if let Some(struct_code) = adapter_bodies.get(&key) {
168                        builder.add_item(struct_code);
169                    }
170                }
171                alef_core::config::AdapterPattern::CallbackBridge => {
172                    let struct_key = format!("{}.__bridge_struct__", adapter.name);
173                    let impl_key = format!("{}.__bridge_impl__", adapter.name);
174                    if let Some(struct_code) = adapter_bodies.get(&struct_key) {
175                        builder.add_item(struct_code);
176                    }
177                    if let Some(impl_code) = adapter_bodies.get(&impl_key) {
178                        builder.add_item(impl_code);
179                    }
180                }
181                _ => {}
182            }
183        }
184
185        for typ in api
186            .types
187            .iter()
188            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
189        {
190            if typ.is_opaque {
191                // Generate the opaque struct with separate #[php_class] and
192                // #[php(name = "Ns\\Type")] attributes (ext-php-rs 0.15+ syntax).
193                // Escape '\' in the namespace so the generated Rust string literal is valid.
194                let ns_escaped = php_namespace.replace('\\', "\\\\");
195                let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped, typ.name);
196                let opaque_attr_arr = ["php_class", php_name_attr.as_str()];
197                let opaque_cfg = RustBindingConfig {
198                    struct_attrs: &opaque_attr_arr,
199                    ..cfg
200                };
201                builder.add_item(&generators::gen_opaque_struct(typ, &opaque_cfg));
202                builder.add_item(&gen_opaque_struct_methods(
203                    typ,
204                    &mapper,
205                    &opaque_types,
206                    &core_import,
207                    &adapter_bodies,
208                ));
209            } else {
210                // gen_struct adds #[derive(Default)] when typ.has_default is true,
211                // so no separate Default impl is needed.
212                builder.add_item(&gen_php_struct(typ, &mapper, &cfg, Some(&php_namespace), &enum_names));
213                builder.add_item(&types::gen_struct_methods_with_exclude(
214                    typ,
215                    &mapper,
216                    has_serde,
217                    &core_import,
218                    &opaque_types,
219                    &enum_names,
220                    &api.enums,
221                    &exclude_functions,
222                ));
223            }
224        }
225
226        for enum_def in &api.enums {
227            builder.add_item(&gen_enum_constants(enum_def));
228        }
229
230        // Generate free functions as static methods on a facade class rather than standalone
231        // `#[php_function]` items. Standalone functions rely on the `inventory` crate for
232        // auto-registration, which does not work in cdylib builds on macOS. Classes registered
233        // via `.class::<T>()` in the module builder DO work on all platforms.
234        let included_functions: Vec<_> = api
235            .functions
236            .iter()
237            .filter(|f| !exclude_functions.contains(&f.name))
238            .collect();
239        if !included_functions.is_empty() {
240            let facade_class_name = extension_name.to_pascal_case();
241            // Build each static method body (no #[php_function] attribute — they live inside
242            // a #[php_impl] block which handles registration via the class machinery).
243            let mut method_items: Vec<String> = Vec::new();
244            for func in included_functions {
245                let bridge_param = crate::trait_bridge::find_bridge_param(func, &config.trait_bridges);
246                if let Some((param_idx, bridge_cfg)) = bridge_param {
247                    method_items.push(crate::trait_bridge::gen_bridge_function(
248                        func,
249                        param_idx,
250                        bridge_cfg,
251                        &mapper,
252                        &opaque_types,
253                        &core_import,
254                    ));
255                } else if func.is_async {
256                    method_items.push(gen_async_function_as_static_method(
257                        func,
258                        &mapper,
259                        &opaque_types,
260                        &core_import,
261                        &config.trait_bridges,
262                    ));
263                } else {
264                    method_items.push(gen_function_as_static_method(
265                        func,
266                        &mapper,
267                        &opaque_types,
268                        &core_import,
269                        &config.trait_bridges,
270                        has_serde,
271                    ));
272                }
273            }
274
275            let methods_joined = method_items
276                .iter()
277                .map(|m| {
278                    // Indent each line of each method by 4 spaces
279                    m.lines()
280                        .map(|l| {
281                            if l.is_empty() {
282                                String::new()
283                            } else {
284                                format!("    {l}")
285                            }
286                        })
287                        .collect::<Vec<_>>()
288                        .join("\n")
289                })
290                .collect::<Vec<_>>()
291                .join("\n\n");
292            // The PHP-visible class name gets an "Api" suffix to avoid collision with the
293            // PHP facade class (e.g. `Kreuzcrawl\Kreuzcrawl`) that Composer autoloads.
294            let php_api_class_name = format!("{facade_class_name}Api");
295            // Escape '\' so the generated Rust string literal is valid (e.g. "Ns\\ClassName").
296            let ns_escaped_facade = php_namespace.replace('\\', "\\\\");
297            let php_name_attr = format!("php(name = \"{}\\\\{}\")", ns_escaped_facade, php_api_class_name);
298            let facade_struct = format!(
299                "#[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}}"
300            );
301            builder.add_item(&facade_struct);
302
303            // Trait bridge structs — top-level items (outside the facade class)
304            for bridge_cfg in &config.trait_bridges {
305                if let Some(trait_type) = api.types.iter().find(|t| t.is_trait && t.name == bridge_cfg.trait_name) {
306                    let bridge = crate::trait_bridge::gen_trait_bridge(
307                        trait_type,
308                        bridge_cfg,
309                        &core_import,
310                        &config.error_type(),
311                        api,
312                    );
313                    for imp in &bridge.imports {
314                        builder.add_import(imp);
315                    }
316                    builder.add_item(&bridge.code);
317                }
318            }
319        }
320
321        let convertible = alef_codegen::conversions::convertible_types(api);
322        let core_to_binding = alef_codegen::conversions::core_to_binding_convertible_types(api);
323        let input_types = alef_codegen::conversions::input_type_names(api);
324        // From/Into conversions with PHP-specific i64 casts.
325        // Types with enum Named fields (or that reference such types transitively) can't
326        // have binding->core From impls because PHP maps enums to String and there's no
327        // From<String> for the core enum type. Core->binding is always safe.
328        let enum_names_ref = &mapper.enum_names;
329        let php_conv_config = ConversionConfig {
330            cast_large_ints_to_i64: true,
331            enum_string_names: Some(enum_names_ref),
332            json_to_string: true,
333            include_cfg_metadata: false,
334            option_duration_on_defaults: true,
335            ..Default::default()
336        };
337        // Build transitive set of types that can't have binding->core From
338        let mut enum_tainted: AHashSet<String> = AHashSet::new();
339        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
340            if has_enum_named_field(typ, enum_names_ref) {
341                enum_tainted.insert(typ.name.clone());
342            }
343        }
344        // Transitively mark types that reference enum-tainted types
345        let mut changed = true;
346        while changed {
347            changed = false;
348            for typ in api.types.iter().filter(|typ| !typ.is_trait) {
349                if !enum_tainted.contains(&typ.name)
350                    && typ.fields.iter().any(|f| references_named_type(&f.ty, &enum_tainted))
351                {
352                    enum_tainted.insert(typ.name.clone());
353                    changed = true;
354                }
355            }
356        }
357        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
358            // binding->core: only when not enum-tainted and type is used as input
359            if input_types.contains(&typ.name)
360                && !enum_tainted.contains(&typ.name)
361                && alef_codegen::conversions::can_generate_conversion(typ, &convertible)
362            {
363                builder.add_item(&alef_codegen::conversions::gen_from_binding_to_core_cfg(
364                    typ,
365                    &core_import,
366                    &php_conv_config,
367                ));
368            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) && has_serde {
369                // Enum-tainted types can't use field-by-field From (no From<String> for core enum),
370                // but when serde is available we bridge via JSON serialization round-trip.
371                builder.add_item(&gen_serde_bridge_from(typ, &core_import));
372            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) {
373                // Enum-tainted types: generate From with string->enum parsing for enum-Named
374                // fields, using first variant as fallback. Data-variant enum fields fill
375                // data fields with Default::default().
376                builder.add_item(&gen_enum_tainted_from_binding_to_core(
377                    typ,
378                    &core_import,
379                    enum_names_ref,
380                    &enum_tainted,
381                    &php_conv_config,
382                    &api.enums,
383                ));
384            }
385            // core->binding: always (enum->String via format, sanitized fields via format)
386            if alef_codegen::conversions::can_generate_conversion(typ, &core_to_binding) {
387                builder.add_item(&alef_codegen::conversions::gen_from_core_to_binding_cfg(
388                    typ,
389                    &core_import,
390                    &opaque_types,
391                    &php_conv_config,
392                ));
393            }
394        }
395
396        // Error converter functions
397        for error in &api.errors {
398            builder.add_item(&alef_codegen::error_gen::gen_php_error_converter(error, &core_import));
399        }
400
401        // Add feature gate as inner attribute — entire crate is gated
402        let php_config = config.php.as_ref();
403        if let Some(feature_name) = php_config.and_then(|c| c.feature_gate.as_deref()) {
404            builder.add_inner_attribute(&format!("cfg(feature = \"{feature_name}\")"));
405            builder.add_inner_attribute(&format!(
406                "cfg_attr(all(windows, target_env = \"msvc\", feature = \"{feature_name}\"), feature(abi_vectorcall))"
407            ));
408        }
409
410        // PHP module entry point — explicit class registration required because
411        // `inventory` crate auto-registration doesn't work in cdylib on macOS.
412        let mut class_registrations = String::new();
413        for typ in api
414            .types
415            .iter()
416            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
417        {
418            class_registrations.push_str(&format!("\n    .class::<{}>()", typ.name));
419        }
420        // Register the facade class that wraps free functions as static methods.
421        if !api.functions.is_empty() {
422            let facade_class_name = extension_name.to_pascal_case();
423            class_registrations.push_str(&format!("\n    .class::<{facade_class_name}Api>()"));
424        }
425        // Note: enums are represented as PHP string-backed enums, not Rust structs,
426        // so they don't need .class::<T>() registration.
427        builder.add_item(&format!(
428            "#[php_module]\npub fn get_module(module: ModuleBuilder) -> ModuleBuilder {{\n    module{class_registrations}\n}}"
429        ));
430
431        let content = builder.build();
432
433        Ok(vec![GeneratedFile {
434            path: PathBuf::from(&output_dir).join("lib.rs"),
435            content,
436            generated_header: false,
437        }])
438    }
439
440    fn generate_public_api(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
441        let extension_name = config.php_extension_name();
442        let class_name = extension_name.to_pascal_case();
443
444        // Generate PHP wrapper class
445        let mut content = String::from("<?php\n");
446        content.push_str("// This file is auto-generated by alef. DO NOT EDIT.\n");
447        content.push_str("declare(strict_types=1);\n\n");
448
449        // Determine namespace
450        let namespace = if extension_name.contains('_') {
451            let parts: Vec<&str> = extension_name.split('_').collect();
452            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
453            ns_parts.join("\\")
454        } else {
455            class_name.clone()
456        };
457
458        content.push_str(&format!("namespace {};\n\n", namespace));
459        content.push_str(&format!("final class {}\n", class_name));
460        content.push_str("{\n");
461
462        // Build the set of bridge param names so they are excluded from public PHP signatures.
463        let bridge_param_names_pub: ahash::AHashSet<&str> = config
464            .trait_bridges
465            .iter()
466            .filter_map(|b| b.param_name.as_deref())
467            .collect();
468
469        // Generate wrapper methods for functions
470        for func in &api.functions {
471            let method_name = func.name.to_lower_camel_case();
472            let return_php_type = php_type(&func.return_type);
473
474            // Visible params exclude bridge params (not surfaced to PHP callers).
475            let visible_params: Vec<_> = func
476                .params
477                .iter()
478                .filter(|p| !bridge_param_names_pub.contains(p.name.as_str()))
479                .collect();
480
481            // PHPDoc block
482            content.push_str("    /**\n");
483            for line in func.doc.lines() {
484                if line.is_empty() {
485                    content.push_str("     *\n");
486                } else {
487                    content.push_str(&format!("     * {}\n", line));
488                }
489            }
490            if func.doc.is_empty() {
491                content.push_str(&format!("     * {}.\n", method_name));
492            }
493            content.push_str("     *\n");
494            for p in &visible_params {
495                let ptype = php_phpdoc_type(&p.ty);
496                let nullable_prefix = if p.optional { "?" } else { "" };
497                content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
498            }
499            let return_phpdoc = php_phpdoc_type(&func.return_type);
500            content.push_str(&format!("     * @return {}\n", return_phpdoc));
501            if func.error_type.is_some() {
502                content.push_str(&format!("     * @throws \\{}\\{}Exception\n", namespace, class_name));
503            }
504            content.push_str("     */\n");
505
506            // Method signature with type hints
507            content.push_str(&format!("    public static function {}(", method_name));
508
509            let params: Vec<String> = visible_params
510                .iter()
511                .map(|p| {
512                    let ptype = php_type(&p.ty);
513                    if p.optional {
514                        format!("?{} ${} = null", ptype, p.name)
515                    } else {
516                        format!("{} ${}", ptype, p.name)
517                    }
518                })
519                .collect();
520            content.push_str(&params.join(", "));
521            content.push_str(&format!("): {}\n", return_php_type));
522            content.push_str("    {\n");
523            // Async functions are registered in the extension with an `_async` suffix
524            // (see gen_async_function which generates `pub fn {name}_async`).
525            // Delegate to the native extension class (registered as `{namespace}\{class_name}Api`).
526            // ext-php-rs auto-converts Rust snake_case to PHP camelCase
527            let ext_method_name = if func.is_async {
528                format!("{}_async", func.name).to_lower_camel_case()
529            } else {
530                func.name.to_lower_camel_case()
531            };
532            let is_void = matches!(&func.return_type, TypeRef::Unit);
533            let call_expr = format!(
534                "\\{}\\{}Api::{}({})",
535                namespace,
536                class_name,
537                ext_method_name,
538                visible_params
539                    .iter()
540                    .map(|p| format!("${}", p.name))
541                    .collect::<Vec<_>>()
542                    .join(", ")
543            );
544            if is_void {
545                content.push_str(&format!(
546                    "        {}; // delegate to native extension class\n",
547                    call_expr
548                ));
549            } else {
550                content.push_str(&format!(
551                    "        return {}; // delegate to native extension class\n",
552                    call_expr
553                ));
554            }
555            content.push_str("    }\n\n");
556        }
557
558        content.push_str("}\n");
559
560        // Use PHP stubs output path if configured, otherwise fall back to packages/php/src/.
561        // This is intentionally separate from config.output.php, which controls the Rust binding
562        // crate output directory (e.g., crates/kreuzcrawl-php/src/).
563        let output_dir = config
564            .php
565            .as_ref()
566            .and_then(|p| p.stubs.as_ref())
567            .map(|s| s.output.to_string_lossy().to_string())
568            .unwrap_or_else(|| "packages/php/src/".to_string());
569
570        Ok(vec![GeneratedFile {
571            path: PathBuf::from(&output_dir).join(format!("{}.php", class_name)),
572            content,
573            generated_header: false,
574        }])
575    }
576
577    fn generate_type_stubs(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
578        let extension_name = config.php_extension_name();
579        let class_name = extension_name.to_pascal_case();
580
581        // Determine namespace (same logic as generate_public_api)
582        let namespace = if extension_name.contains('_') {
583            let parts: Vec<&str> = extension_name.split('_').collect();
584            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
585            ns_parts.join("\\")
586        } else {
587            class_name.clone()
588        };
589
590        let mut content = String::from("<?php\n");
591        content.push_str("// This file is auto-generated by alef. DO NOT EDIT.\n");
592        content.push_str("// Type stubs for the native PHP extension — declares classes\n");
593        content.push_str("// provided at runtime by the compiled Rust extension (.so/.dll).\n");
594        content.push_str("// Include this in phpstan.neon scanFiles for static analysis.\n\n");
595        content.push_str("declare(strict_types=1);\n\n");
596        // Use bracketed namespace syntax so we can add global-namespace function stubs later.
597        content.push_str(&format!("namespace {} {{\n\n", namespace));
598
599        // Exception class
600        content.push_str(&format!(
601            "class {}Exception extends \\RuntimeException\n{{\n",
602            class_name
603        ));
604        content.push_str("    public function getErrorCode(): int { }\n");
605        content.push_str("}\n\n");
606
607        // Opaque handle classes
608        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
609            if typ.is_opaque {
610                if !typ.doc.is_empty() {
611                    content.push_str("/**\n");
612                    for line in typ.doc.lines() {
613                        if line.is_empty() {
614                            content.push_str(" *\n");
615                        } else {
616                            content.push_str(&format!(" * {}\n", line));
617                        }
618                    }
619                    content.push_str(" */\n");
620                }
621                content.push_str(&format!("class {}\n{{\n", typ.name));
622                // Opaque handles have no public constructors in PHP
623                content.push_str("}\n\n");
624            }
625        }
626
627        // Record / struct types (non-opaque with fields)
628        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
629            if typ.is_opaque || typ.fields.is_empty() {
630                continue;
631            }
632            if !typ.doc.is_empty() {
633                content.push_str("/**\n");
634                for line in typ.doc.lines() {
635                    if line.is_empty() {
636                        content.push_str(" *\n");
637                    } else {
638                        content.push_str(&format!(" * {}\n", line));
639                    }
640                }
641                content.push_str(" */\n");
642            }
643            content.push_str(&format!("class {}\n{{\n", typ.name));
644
645            // Public property declarations (ext-php-rs exposes struct fields as properties)
646            for field in &typ.fields {
647                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
648                let prop_type = if field.optional {
649                    let inner = php_type(&field.ty);
650                    if inner.starts_with('?') {
651                        inner
652                    } else {
653                        format!("?{inner}")
654                    }
655                } else {
656                    php_type(&field.ty)
657                };
658                if is_array {
659                    let phpdoc = php_phpdoc_type(&field.ty);
660                    let nullable_prefix = if field.optional { "?" } else { "" };
661                    content.push_str(&format!("    /** @var {}{} */\n", nullable_prefix, phpdoc));
662                }
663                content.push_str(&format!("    public {} ${};\n", prop_type, field.name));
664            }
665            content.push('\n');
666
667            // Constructor with typed parameters.
668            // PHP requires required parameters to come before optional ones, so sort
669            // the fields: required first, then optional (preserving relative order within each group).
670            let mut sorted_fields: Vec<&alef_core::ir::FieldDef> = typ.fields.iter().collect();
671            sorted_fields.sort_by_key(|f| f.optional);
672
673            // Emit PHPDoc before the constructor for any array-typed fields so PHPStan
674            // understands the generic element type (e.g. `@param array<string> $items`).
675            let array_fields: Vec<&alef_core::ir::FieldDef> = sorted_fields
676                .iter()
677                .copied()
678                .filter(|f| matches!(&f.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)))
679                .collect();
680            if !array_fields.is_empty() {
681                content.push_str("    /**\n");
682                for f in &array_fields {
683                    let phpdoc = php_phpdoc_type(&f.ty);
684                    let nullable_prefix = if f.optional { "?" } else { "" };
685                    content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, phpdoc, f.name));
686                }
687                content.push_str("     */\n");
688            }
689
690            let params: Vec<String> = sorted_fields
691                .iter()
692                .map(|f| {
693                    let ptype = php_type(&f.ty);
694                    let nullable = if f.optional && !ptype.starts_with('?') {
695                        format!("?{ptype}")
696                    } else {
697                        ptype
698                    };
699                    let default = if f.optional { " = null" } else { "" };
700                    format!("        {} ${}{}", nullable, f.name, default)
701                })
702                .collect();
703            content.push_str("    public function __construct(\n");
704            content.push_str(&params.join(",\n"));
705            content.push_str("\n    ) { }\n\n");
706
707            // Getter methods for each field
708            for field in &typ.fields {
709                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
710                let return_type = if field.optional {
711                    let inner = php_type(&field.ty);
712                    if inner.starts_with('?') {
713                        inner
714                    } else {
715                        format!("?{inner}")
716                    }
717                } else {
718                    php_type(&field.ty)
719                };
720                let getter_name = field.name.to_lower_camel_case();
721                // Emit PHPDoc for array return types so PHPStan knows the element type.
722                if is_array {
723                    let phpdoc = php_phpdoc_type(&field.ty);
724                    let nullable_prefix = if field.optional { "?" } else { "" };
725                    content.push_str(&format!("    /** @return {}{} */\n", nullable_prefix, phpdoc));
726                }
727                content.push_str(&format!(
728                    "    public function get{}(): {} {{ }}\n",
729                    getter_name.to_pascal_case(),
730                    return_type
731                ));
732            }
733
734            content.push_str("}\n\n");
735        }
736
737        // Enum constants (PHP 8.1+ enums)
738        for enum_def in &api.enums {
739            content.push_str(&format!("enum {}: string\n{{\n", enum_def.name));
740            for variant in &enum_def.variants {
741                content.push_str(&format!("    case {} = '{}';\n", variant.name, variant.name));
742            }
743            content.push_str("}\n\n");
744        }
745
746        // Extension function stubs — generated as a native `{ClassName}Api` class with static
747        // methods. The PHP facade (`{ClassName}`) delegates to `{ClassName}Api::method()`.
748        // Using a class instead of global functions avoids the `inventory` crate registration
749        // issue on macOS (cdylib builds do not collect `#[php_function]` entries there).
750        if !api.functions.is_empty() {
751            // Bridge params are hidden from the PHP-visible API in stubs too.
752            let bridge_param_names_stubs: ahash::AHashSet<&str> = config
753                .trait_bridges
754                .iter()
755                .filter_map(|b| b.param_name.as_deref())
756                .collect();
757
758            content.push_str(&format!("class {}Api\n{{\n", class_name));
759            for func in &api.functions {
760                let return_type = php_type_fq(&func.return_type, &namespace);
761                let return_phpdoc = php_phpdoc_type_fq(&func.return_type, &namespace);
762                // Visible params exclude bridge params.
763                let visible_params: Vec<_> = func
764                    .params
765                    .iter()
766                    .filter(|p| !bridge_param_names_stubs.contains(p.name.as_str()))
767                    .collect();
768                // PHPDoc block
769                let has_array_params = visible_params
770                    .iter()
771                    .any(|p| matches!(&p.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)));
772                if has_array_params {
773                    content.push_str("    /**\n");
774                    for p in &visible_params {
775                        let ptype = php_phpdoc_type_fq(&p.ty, &namespace);
776                        let nullable_prefix = if p.optional { "?" } else { "" };
777                        content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
778                    }
779                    content.push_str(&format!("     * @return {}\n", return_phpdoc));
780                    content.push_str("     */\n");
781                }
782                let params: Vec<String> = visible_params
783                    .iter()
784                    .map(|p| {
785                        let ptype = php_type_fq(&p.ty, &namespace);
786                        if p.optional {
787                            format!("?{} ${} = null", ptype, p.name)
788                        } else {
789                            format!("{} ${}", ptype, p.name)
790                        }
791                    })
792                    .collect();
793                // ext-php-rs auto-converts Rust snake_case to PHP camelCase.
794                let stub_method_name = if func.is_async {
795                    format!("{}_async", func.name).to_lower_camel_case()
796                } else {
797                    func.name.to_lower_camel_case()
798                };
799                content.push_str(&format!(
800                    "    public static function {}({}): {} {{ }}\n",
801                    stub_method_name,
802                    params.join(", "),
803                    return_type
804                ));
805            }
806            content.push_str("}\n\n");
807        }
808
809        // Close the namespaced block
810        content.push_str("} // end namespace\n");
811
812        // Use stubs output path if configured, otherwise packages/php/stubs/
813        let output_dir = config
814            .php
815            .as_ref()
816            .and_then(|p| p.stubs.as_ref())
817            .map(|s| s.output.to_string_lossy().to_string())
818            .unwrap_or_else(|| "packages/php/stubs/".to_string());
819
820        Ok(vec![GeneratedFile {
821            path: PathBuf::from(&output_dir).join(format!("{}_extension.php", extension_name)),
822            content,
823            generated_header: false,
824        }])
825    }
826
827    fn build_config(&self) -> Option<BuildConfig> {
828        Some(BuildConfig {
829            tool: "cargo",
830            crate_suffix: "-php",
831            depends_on_ffi: false,
832            post_build: vec![],
833        })
834    }
835}
836
837/// Map an IR [`TypeRef`] to a PHPDoc type string with generic parameters (e.g., `array<string>`).
838/// PHPStan at level `max` requires iterable value types in PHPDoc annotations.
839fn php_phpdoc_type(ty: &TypeRef) -> String {
840    match ty {
841        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type(inner)),
842        TypeRef::Map(k, v) => format!("array<{}, {}>", php_phpdoc_type(k), php_phpdoc_type(v)),
843        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type(inner)),
844        _ => php_type(ty),
845    }
846}
847
848/// Map an IR [`TypeRef`] to a fully-qualified PHPDoc type string with generics (e.g., `array<\Ns\T>`).
849fn php_phpdoc_type_fq(ty: &TypeRef, namespace: &str) -> String {
850    match ty {
851        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type_fq(inner, namespace)),
852        TypeRef::Map(k, v) => format!(
853            "array<{}, {}>",
854            php_phpdoc_type_fq(k, namespace),
855            php_phpdoc_type_fq(v, namespace)
856        ),
857        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
858        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type_fq(inner, namespace)),
859        _ => php_type(ty),
860    }
861}
862
863/// Map an IR [`TypeRef`] to a fully-qualified PHP type-hint string for use outside the namespace.
864fn php_type_fq(ty: &TypeRef, namespace: &str) -> String {
865    match ty {
866        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
867        TypeRef::Optional(inner) => {
868            let inner_type = php_type_fq(inner, namespace);
869            if inner_type.starts_with('?') {
870                inner_type
871            } else {
872                format!("?{inner_type}")
873            }
874        }
875        _ => php_type(ty),
876    }
877}
878
879/// Map an IR [`TypeRef`] to a PHP type-hint string.
880fn php_type(ty: &TypeRef) -> String {
881    match ty {
882        TypeRef::String | TypeRef::Char | TypeRef::Json | TypeRef::Bytes | TypeRef::Path => "string".to_string(),
883        TypeRef::Primitive(p) => match p {
884            PrimitiveType::Bool => "bool".to_string(),
885            PrimitiveType::F32 | PrimitiveType::F64 => "float".to_string(),
886            PrimitiveType::U8
887            | PrimitiveType::U16
888            | PrimitiveType::U32
889            | PrimitiveType::U64
890            | PrimitiveType::I8
891            | PrimitiveType::I16
892            | PrimitiveType::I32
893            | PrimitiveType::I64
894            | PrimitiveType::Usize
895            | PrimitiveType::Isize => "int".to_string(),
896        },
897        TypeRef::Optional(inner) => {
898            // Flatten nested Option<Option<T>> to a single nullable type.
899            // PHP has no double-nullable concept; ?T already covers null.
900            let inner_type = php_type(inner);
901            if inner_type.starts_with('?') {
902                inner_type
903            } else {
904                format!("?{inner_type}")
905            }
906        }
907        TypeRef::Vec(_) | TypeRef::Map(_, _) => "array".to_string(),
908        TypeRef::Named(name) => name.clone(),
909        TypeRef::Unit => "void".to_string(),
910        TypeRef::Duration => "float".to_string(),
911    }
912}