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_code = crate::trait_bridge::gen_trait_bridge(trait_type, bridge_cfg, &core_import, api);
307                    builder.add_item(&bridge_code);
308                }
309            }
310        }
311
312        let convertible = alef_codegen::conversions::convertible_types(api);
313        let core_to_binding = alef_codegen::conversions::core_to_binding_convertible_types(api);
314        let input_types = alef_codegen::conversions::input_type_names(api);
315        // From/Into conversions with PHP-specific i64 casts.
316        // Types with enum Named fields (or that reference such types transitively) can't
317        // have binding->core From impls because PHP maps enums to String and there's no
318        // From<String> for the core enum type. Core->binding is always safe.
319        let enum_names_ref = &mapper.enum_names;
320        let php_conv_config = ConversionConfig {
321            cast_large_ints_to_i64: true,
322            enum_string_names: Some(enum_names_ref),
323            json_to_string: true,
324            include_cfg_metadata: false,
325            option_duration_on_defaults: true,
326            ..Default::default()
327        };
328        // Build transitive set of types that can't have binding->core From
329        let mut enum_tainted: AHashSet<String> = AHashSet::new();
330        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
331            if has_enum_named_field(typ, enum_names_ref) {
332                enum_tainted.insert(typ.name.clone());
333            }
334        }
335        // Transitively mark types that reference enum-tainted types
336        let mut changed = true;
337        while changed {
338            changed = false;
339            for typ in api.types.iter().filter(|typ| !typ.is_trait) {
340                if !enum_tainted.contains(&typ.name)
341                    && typ.fields.iter().any(|f| references_named_type(&f.ty, &enum_tainted))
342                {
343                    enum_tainted.insert(typ.name.clone());
344                    changed = true;
345                }
346            }
347        }
348        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
349            // binding->core: only when not enum-tainted and type is used as input
350            if input_types.contains(&typ.name)
351                && !enum_tainted.contains(&typ.name)
352                && alef_codegen::conversions::can_generate_conversion(typ, &convertible)
353            {
354                builder.add_item(&alef_codegen::conversions::gen_from_binding_to_core_cfg(
355                    typ,
356                    &core_import,
357                    &php_conv_config,
358                ));
359            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) && has_serde {
360                // Enum-tainted types can't use field-by-field From (no From<String> for core enum),
361                // but when serde is available we bridge via JSON serialization round-trip.
362                builder.add_item(&gen_serde_bridge_from(typ, &core_import));
363            } else if input_types.contains(&typ.name) && enum_tainted.contains(&typ.name) {
364                // Enum-tainted types: generate From with string->enum parsing for enum-Named
365                // fields, using first variant as fallback. Data-variant enum fields fill
366                // data fields with Default::default().
367                builder.add_item(&gen_enum_tainted_from_binding_to_core(
368                    typ,
369                    &core_import,
370                    enum_names_ref,
371                    &enum_tainted,
372                    &php_conv_config,
373                    &api.enums,
374                ));
375            }
376            // core->binding: always (enum->String via format, sanitized fields via format)
377            if alef_codegen::conversions::can_generate_conversion(typ, &core_to_binding) {
378                builder.add_item(&alef_codegen::conversions::gen_from_core_to_binding_cfg(
379                    typ,
380                    &core_import,
381                    &opaque_types,
382                    &php_conv_config,
383                ));
384            }
385        }
386
387        // Error converter functions
388        for error in &api.errors {
389            builder.add_item(&alef_codegen::error_gen::gen_php_error_converter(error, &core_import));
390        }
391
392        // Add feature gate as inner attribute — entire crate is gated
393        let php_config = config.php.as_ref();
394        if let Some(feature_name) = php_config.and_then(|c| c.feature_gate.as_deref()) {
395            builder.add_inner_attribute(&format!("cfg(feature = \"{feature_name}\")"));
396            builder.add_inner_attribute(&format!(
397                "cfg_attr(all(windows, target_env = \"msvc\", feature = \"{feature_name}\"), feature(abi_vectorcall))"
398            ));
399        }
400
401        // PHP module entry point — explicit class registration required because
402        // `inventory` crate auto-registration doesn't work in cdylib on macOS.
403        let mut class_registrations = String::new();
404        for typ in api
405            .types
406            .iter()
407            .filter(|typ| !typ.is_trait && !exclude_types.contains(&typ.name))
408        {
409            class_registrations.push_str(&format!("\n    .class::<{}>()", typ.name));
410        }
411        // Register the facade class that wraps free functions as static methods.
412        if !api.functions.is_empty() {
413            let facade_class_name = extension_name.to_pascal_case();
414            class_registrations.push_str(&format!("\n    .class::<{facade_class_name}Api>()"));
415        }
416        // Note: enums are represented as PHP string-backed enums, not Rust structs,
417        // so they don't need .class::<T>() registration.
418        builder.add_item(&format!(
419            "#[php_module]\npub fn get_module(module: ModuleBuilder) -> ModuleBuilder {{\n    module{class_registrations}\n}}"
420        ));
421
422        let content = builder.build();
423
424        Ok(vec![GeneratedFile {
425            path: PathBuf::from(&output_dir).join("lib.rs"),
426            content,
427            generated_header: false,
428        }])
429    }
430
431    fn generate_public_api(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
432        let extension_name = config.php_extension_name();
433        let class_name = extension_name.to_pascal_case();
434
435        // Generate PHP wrapper class
436        let mut content = String::from("<?php\n");
437        content.push_str("// This file is auto-generated by alef. DO NOT EDIT.\n");
438        content.push_str("declare(strict_types=1);\n\n");
439
440        // Determine namespace
441        let namespace = if extension_name.contains('_') {
442            let parts: Vec<&str> = extension_name.split('_').collect();
443            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
444            ns_parts.join("\\")
445        } else {
446            class_name.clone()
447        };
448
449        content.push_str(&format!("namespace {};\n\n", namespace));
450        content.push_str(&format!("final class {}\n", class_name));
451        content.push_str("{\n");
452
453        // Build the set of bridge param names so they are excluded from public PHP signatures.
454        let bridge_param_names_pub: ahash::AHashSet<&str> = config
455            .trait_bridges
456            .iter()
457            .filter_map(|b| b.param_name.as_deref())
458            .collect();
459
460        // Generate wrapper methods for functions
461        for func in &api.functions {
462            let method_name = func.name.to_lower_camel_case();
463            let return_php_type = php_type(&func.return_type);
464
465            // Visible params exclude bridge params (not surfaced to PHP callers).
466            let visible_params: Vec<_> = func
467                .params
468                .iter()
469                .filter(|p| !bridge_param_names_pub.contains(p.name.as_str()))
470                .collect();
471
472            // PHPDoc block
473            content.push_str("    /**\n");
474            for line in func.doc.lines() {
475                if line.is_empty() {
476                    content.push_str("     *\n");
477                } else {
478                    content.push_str(&format!("     * {}\n", line));
479                }
480            }
481            if func.doc.is_empty() {
482                content.push_str(&format!("     * {}.\n", method_name));
483            }
484            content.push_str("     *\n");
485            for p in &visible_params {
486                let ptype = php_phpdoc_type(&p.ty);
487                let nullable_prefix = if p.optional { "?" } else { "" };
488                content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
489            }
490            let return_phpdoc = php_phpdoc_type(&func.return_type);
491            content.push_str(&format!("     * @return {}\n", return_phpdoc));
492            if func.error_type.is_some() {
493                content.push_str(&format!("     * @throws \\{}\\{}Exception\n", namespace, class_name));
494            }
495            content.push_str("     */\n");
496
497            // Method signature with type hints
498            content.push_str(&format!("    public static function {}(", method_name));
499
500            let params: Vec<String> = visible_params
501                .iter()
502                .map(|p| {
503                    let ptype = php_type(&p.ty);
504                    if p.optional {
505                        format!("?{} ${} = null", ptype, p.name)
506                    } else {
507                        format!("{} ${}", ptype, p.name)
508                    }
509                })
510                .collect();
511            content.push_str(&params.join(", "));
512            content.push_str(&format!("): {}\n", return_php_type));
513            content.push_str("    {\n");
514            // Async functions are registered in the extension with an `_async` suffix
515            // (see gen_async_function which generates `pub fn {name}_async`).
516            // Delegate to the native extension class (registered as `{namespace}\{class_name}Api`).
517            // ext-php-rs auto-converts Rust snake_case to PHP camelCase
518            let ext_method_name = if func.is_async {
519                format!("{}_async", func.name).to_lower_camel_case()
520            } else {
521                func.name.to_lower_camel_case()
522            };
523            let is_void = matches!(&func.return_type, TypeRef::Unit);
524            let call_expr = format!(
525                "\\{}\\{}Api::{}({})",
526                namespace,
527                class_name,
528                ext_method_name,
529                visible_params
530                    .iter()
531                    .map(|p| format!("${}", p.name))
532                    .collect::<Vec<_>>()
533                    .join(", ")
534            );
535            if is_void {
536                content.push_str(&format!(
537                    "        {}; // delegate to native extension class\n",
538                    call_expr
539                ));
540            } else {
541                content.push_str(&format!(
542                    "        return {}; // delegate to native extension class\n",
543                    call_expr
544                ));
545            }
546            content.push_str("    }\n\n");
547        }
548
549        content.push_str("}\n");
550
551        // Use PHP stubs output path if configured, otherwise fall back to packages/php/src/.
552        // This is intentionally separate from config.output.php, which controls the Rust binding
553        // crate output directory (e.g., crates/kreuzcrawl-php/src/).
554        let output_dir = config
555            .php
556            .as_ref()
557            .and_then(|p| p.stubs.as_ref())
558            .map(|s| s.output.to_string_lossy().to_string())
559            .unwrap_or_else(|| "packages/php/src/".to_string());
560
561        Ok(vec![GeneratedFile {
562            path: PathBuf::from(&output_dir).join(format!("{}.php", class_name)),
563            content,
564            generated_header: false,
565        }])
566    }
567
568    fn generate_type_stubs(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
569        let extension_name = config.php_extension_name();
570        let class_name = extension_name.to_pascal_case();
571
572        // Determine namespace (same logic as generate_public_api)
573        let namespace = if extension_name.contains('_') {
574            let parts: Vec<&str> = extension_name.split('_').collect();
575            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
576            ns_parts.join("\\")
577        } else {
578            class_name.clone()
579        };
580
581        let mut content = String::from("<?php\n");
582        content.push_str("// This file is auto-generated by alef. DO NOT EDIT.\n");
583        content.push_str("// Type stubs for the native PHP extension — declares classes\n");
584        content.push_str("// provided at runtime by the compiled Rust extension (.so/.dll).\n");
585        content.push_str("// Include this in phpstan.neon scanFiles for static analysis.\n\n");
586        content.push_str("declare(strict_types=1);\n\n");
587        // Use bracketed namespace syntax so we can add global-namespace function stubs later.
588        content.push_str(&format!("namespace {} {{\n\n", namespace));
589
590        // Exception class
591        content.push_str(&format!(
592            "class {}Exception extends \\RuntimeException\n{{\n",
593            class_name
594        ));
595        content.push_str("    public function getErrorCode(): int { }\n");
596        content.push_str("}\n\n");
597
598        // Opaque handle classes
599        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
600            if typ.is_opaque {
601                if !typ.doc.is_empty() {
602                    content.push_str("/**\n");
603                    for line in typ.doc.lines() {
604                        if line.is_empty() {
605                            content.push_str(" *\n");
606                        } else {
607                            content.push_str(&format!(" * {}\n", line));
608                        }
609                    }
610                    content.push_str(" */\n");
611                }
612                content.push_str(&format!("class {}\n{{\n", typ.name));
613                // Opaque handles have no public constructors in PHP
614                content.push_str("}\n\n");
615            }
616        }
617
618        // Record / struct types (non-opaque with fields)
619        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
620            if typ.is_opaque || typ.fields.is_empty() {
621                continue;
622            }
623            if !typ.doc.is_empty() {
624                content.push_str("/**\n");
625                for line in typ.doc.lines() {
626                    if line.is_empty() {
627                        content.push_str(" *\n");
628                    } else {
629                        content.push_str(&format!(" * {}\n", line));
630                    }
631                }
632                content.push_str(" */\n");
633            }
634            content.push_str(&format!("class {}\n{{\n", typ.name));
635
636            // Public property declarations (ext-php-rs exposes struct fields as properties)
637            for field in &typ.fields {
638                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
639                let prop_type = if field.optional {
640                    let inner = php_type(&field.ty);
641                    if inner.starts_with('?') {
642                        inner
643                    } else {
644                        format!("?{inner}")
645                    }
646                } else {
647                    php_type(&field.ty)
648                };
649                if is_array {
650                    let phpdoc = php_phpdoc_type(&field.ty);
651                    let nullable_prefix = if field.optional { "?" } else { "" };
652                    content.push_str(&format!("    /** @var {}{} */\n", nullable_prefix, phpdoc));
653                }
654                content.push_str(&format!("    public {} ${};\n", prop_type, field.name));
655            }
656            content.push('\n');
657
658            // Constructor with typed parameters.
659            // PHP requires required parameters to come before optional ones, so sort
660            // the fields: required first, then optional (preserving relative order within each group).
661            let mut sorted_fields: Vec<&alef_core::ir::FieldDef> = typ.fields.iter().collect();
662            sorted_fields.sort_by_key(|f| f.optional);
663
664            // Emit PHPDoc before the constructor for any array-typed fields so PHPStan
665            // understands the generic element type (e.g. `@param array<string> $items`).
666            let array_fields: Vec<&alef_core::ir::FieldDef> = sorted_fields
667                .iter()
668                .copied()
669                .filter(|f| matches!(&f.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)))
670                .collect();
671            if !array_fields.is_empty() {
672                content.push_str("    /**\n");
673                for f in &array_fields {
674                    let phpdoc = php_phpdoc_type(&f.ty);
675                    let nullable_prefix = if f.optional { "?" } else { "" };
676                    content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, phpdoc, f.name));
677                }
678                content.push_str("     */\n");
679            }
680
681            let params: Vec<String> = sorted_fields
682                .iter()
683                .map(|f| {
684                    let ptype = php_type(&f.ty);
685                    let nullable = if f.optional && !ptype.starts_with('?') {
686                        format!("?{ptype}")
687                    } else {
688                        ptype
689                    };
690                    let default = if f.optional { " = null" } else { "" };
691                    format!("        {} ${}{}", nullable, f.name, default)
692                })
693                .collect();
694            content.push_str("    public function __construct(\n");
695            content.push_str(&params.join(",\n"));
696            content.push_str("\n    ) { }\n\n");
697
698            // Getter methods for each field
699            for field in &typ.fields {
700                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
701                let return_type = if field.optional {
702                    let inner = php_type(&field.ty);
703                    if inner.starts_with('?') {
704                        inner
705                    } else {
706                        format!("?{inner}")
707                    }
708                } else {
709                    php_type(&field.ty)
710                };
711                let getter_name = field.name.to_lower_camel_case();
712                // Emit PHPDoc for array return types so PHPStan knows the element type.
713                if is_array {
714                    let phpdoc = php_phpdoc_type(&field.ty);
715                    let nullable_prefix = if field.optional { "?" } else { "" };
716                    content.push_str(&format!("    /** @return {}{} */\n", nullable_prefix, phpdoc));
717                }
718                content.push_str(&format!(
719                    "    public function get{}(): {} {{ }}\n",
720                    getter_name.to_pascal_case(),
721                    return_type
722                ));
723            }
724
725            content.push_str("}\n\n");
726        }
727
728        // Enum constants (PHP 8.1+ enums)
729        for enum_def in &api.enums {
730            content.push_str(&format!("enum {}: string\n{{\n", enum_def.name));
731            for variant in &enum_def.variants {
732                content.push_str(&format!("    case {} = '{}';\n", variant.name, variant.name));
733            }
734            content.push_str("}\n\n");
735        }
736
737        // Extension function stubs — generated as a native `{ClassName}Api` class with static
738        // methods. The PHP facade (`{ClassName}`) delegates to `{ClassName}Api::method()`.
739        // Using a class instead of global functions avoids the `inventory` crate registration
740        // issue on macOS (cdylib builds do not collect `#[php_function]` entries there).
741        if !api.functions.is_empty() {
742            // Bridge params are hidden from the PHP-visible API in stubs too.
743            let bridge_param_names_stubs: ahash::AHashSet<&str> = config
744                .trait_bridges
745                .iter()
746                .filter_map(|b| b.param_name.as_deref())
747                .collect();
748
749            content.push_str(&format!("class {}Api\n{{\n", class_name));
750            for func in &api.functions {
751                let return_type = php_type_fq(&func.return_type, &namespace);
752                let return_phpdoc = php_phpdoc_type_fq(&func.return_type, &namespace);
753                // Visible params exclude bridge params.
754                let visible_params: Vec<_> = func
755                    .params
756                    .iter()
757                    .filter(|p| !bridge_param_names_stubs.contains(p.name.as_str()))
758                    .collect();
759                // PHPDoc block
760                let has_array_params = visible_params
761                    .iter()
762                    .any(|p| matches!(&p.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)));
763                if has_array_params {
764                    content.push_str("    /**\n");
765                    for p in &visible_params {
766                        let ptype = php_phpdoc_type_fq(&p.ty, &namespace);
767                        let nullable_prefix = if p.optional { "?" } else { "" };
768                        content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
769                    }
770                    content.push_str(&format!("     * @return {}\n", return_phpdoc));
771                    content.push_str("     */\n");
772                }
773                let params: Vec<String> = visible_params
774                    .iter()
775                    .map(|p| {
776                        let ptype = php_type_fq(&p.ty, &namespace);
777                        if p.optional {
778                            format!("?{} ${} = null", ptype, p.name)
779                        } else {
780                            format!("{} ${}", ptype, p.name)
781                        }
782                    })
783                    .collect();
784                // ext-php-rs auto-converts Rust snake_case to PHP camelCase.
785                let stub_method_name = if func.is_async {
786                    format!("{}_async", func.name).to_lower_camel_case()
787                } else {
788                    func.name.to_lower_camel_case()
789                };
790                content.push_str(&format!(
791                    "    public static function {}({}): {} {{ }}\n",
792                    stub_method_name,
793                    params.join(", "),
794                    return_type
795                ));
796            }
797            content.push_str("}\n\n");
798        }
799
800        // Close the namespaced block
801        content.push_str("} // end namespace\n");
802
803        // Use stubs output path if configured, otherwise packages/php/stubs/
804        let output_dir = config
805            .php
806            .as_ref()
807            .and_then(|p| p.stubs.as_ref())
808            .map(|s| s.output.to_string_lossy().to_string())
809            .unwrap_or_else(|| "packages/php/stubs/".to_string());
810
811        Ok(vec![GeneratedFile {
812            path: PathBuf::from(&output_dir).join(format!("{}_extension.php", extension_name)),
813            content,
814            generated_header: false,
815        }])
816    }
817
818    fn build_config(&self) -> Option<BuildConfig> {
819        Some(BuildConfig {
820            tool: "cargo",
821            crate_suffix: "-php",
822            depends_on_ffi: false,
823            post_build: vec![],
824        })
825    }
826}
827
828/// Map an IR [`TypeRef`] to a PHPDoc type string with generic parameters (e.g., `array<string>`).
829/// PHPStan at level `max` requires iterable value types in PHPDoc annotations.
830fn php_phpdoc_type(ty: &TypeRef) -> String {
831    match ty {
832        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type(inner)),
833        TypeRef::Map(k, v) => format!("array<{}, {}>", php_phpdoc_type(k), php_phpdoc_type(v)),
834        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type(inner)),
835        _ => php_type(ty),
836    }
837}
838
839/// Map an IR [`TypeRef`] to a fully-qualified PHPDoc type string with generics (e.g., `array<\Ns\T>`).
840fn php_phpdoc_type_fq(ty: &TypeRef, namespace: &str) -> String {
841    match ty {
842        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type_fq(inner, namespace)),
843        TypeRef::Map(k, v) => format!(
844            "array<{}, {}>",
845            php_phpdoc_type_fq(k, namespace),
846            php_phpdoc_type_fq(v, namespace)
847        ),
848        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
849        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type_fq(inner, namespace)),
850        _ => php_type(ty),
851    }
852}
853
854/// Map an IR [`TypeRef`] to a fully-qualified PHP type-hint string for use outside the namespace.
855fn php_type_fq(ty: &TypeRef, namespace: &str) -> String {
856    match ty {
857        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
858        TypeRef::Optional(inner) => {
859            let inner_type = php_type_fq(inner, namespace);
860            if inner_type.starts_with('?') {
861                inner_type
862            } else {
863                format!("?{inner_type}")
864            }
865        }
866        _ => php_type(ty),
867    }
868}
869
870/// Map an IR [`TypeRef`] to a PHP type-hint string.
871fn php_type(ty: &TypeRef) -> String {
872    match ty {
873        TypeRef::String | TypeRef::Char | TypeRef::Json | TypeRef::Bytes | TypeRef::Path => "string".to_string(),
874        TypeRef::Primitive(p) => match p {
875            PrimitiveType::Bool => "bool".to_string(),
876            PrimitiveType::F32 | PrimitiveType::F64 => "float".to_string(),
877            PrimitiveType::U8
878            | PrimitiveType::U16
879            | PrimitiveType::U32
880            | PrimitiveType::U64
881            | PrimitiveType::I8
882            | PrimitiveType::I16
883            | PrimitiveType::I32
884            | PrimitiveType::I64
885            | PrimitiveType::Usize
886            | PrimitiveType::Isize => "int".to_string(),
887        },
888        TypeRef::Optional(inner) => {
889            // Flatten nested Option<Option<T>> to a single nullable type.
890            // PHP has no double-nullable concept; ?T already covers null.
891            let inner_type = php_type(inner);
892            if inner_type.starts_with('?') {
893                inner_type
894            } else {
895                format!("?{inner_type}")
896            }
897        }
898        TypeRef::Vec(_) | TypeRef::Map(_, _) => "array".to_string(),
899        TypeRef::Named(name) => name.clone(),
900        TypeRef::Unit => "void".to_string(),
901        TypeRef::Duration => "float".to_string(),
902    }
903}