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