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