Skip to main content

alef_e2e/codegen/
php.rs

1//! PHP e2e test generator using PHPUnit.
2//!
3//! Generates `e2e/php/composer.json`, `e2e/php/phpunit.xml`, and
4//! `tests/{Category}Test.php` files from JSON fixtures, driven entirely by
5//! `E2eConfig` and `CallConfig`.
6
7use crate::config::E2eConfig;
8use crate::escape::{escape_php, sanitize_filename};
9use crate::field_access::{FieldResolver, PhpGetterMap};
10use crate::fixture::{
11    Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture, TemplateReturnForm, ValidationErrorExpectation,
12};
13use alef_backend_php::naming::php_autoload_namespace;
14use alef_core::backend::GeneratedFile;
15use alef_core::config::ResolvedCrateConfig;
16use alef_core::hash::{self, CommentStyle};
17use alef_core::ir::TypeRef;
18use alef_core::template_versions as tv;
19use anyhow::Result;
20use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
21use std::collections::{HashMap, HashSet};
22use std::fmt::Write as FmtWrite;
23use std::path::PathBuf;
24
25use super::E2eCodegen;
26use super::client;
27
28/// PHP e2e code generator.
29pub struct PhpCodegen;
30
31impl E2eCodegen for PhpCodegen {
32    fn generate(
33        &self,
34        groups: &[FixtureGroup],
35        e2e_config: &E2eConfig,
36        config: &ResolvedCrateConfig,
37        type_defs: &[alef_core::ir::TypeDef],
38        enums: &[alef_core::ir::EnumDef],
39    ) -> Result<Vec<GeneratedFile>> {
40        let lang = self.language_name();
41        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
42
43        let mut files = Vec::new();
44
45        // Resolve top-level call config to derive class/namespace/factory — these are
46        // shared across all categories. Per-fixture call routing (function name, args)
47        // is resolved inside render_test_method via e2e_config.resolve_call().
48        let call = &e2e_config.call;
49        let overrides = call.overrides.get(lang);
50        let extension_name = config.php_extension_name();
51        let class_name = overrides
52            .and_then(|o| o.class.as_ref())
53            .cloned()
54            .map(|cn| cn.split('\\').next_back().unwrap_or(&cn).to_string())
55            .unwrap_or_else(|| extension_name.to_upper_camel_case());
56        let namespace = overrides.and_then(|o| o.module.as_ref()).cloned().unwrap_or_else(|| {
57            if extension_name.contains('_') {
58                extension_name
59                    .split('_')
60                    .map(|p| p.to_upper_camel_case())
61                    .collect::<Vec<_>>()
62                    .join("\\")
63            } else {
64                extension_name.to_upper_camel_case()
65            }
66        });
67        let empty_enum_fields = HashMap::new();
68        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
69        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
70        let php_client_factory = overrides.and_then(|o| o.php_client_factory.as_deref());
71        let options_via = overrides.and_then(|o| o.options_via.as_deref()).unwrap_or("array");
72
73        // Resolve package config.
74        let php_pkg = e2e_config.resolve_package("php");
75        let pkg_name = php_pkg
76            .as_ref()
77            .and_then(|p| p.name.as_ref())
78            .cloned()
79            .unwrap_or_else(|| {
80                // Derive `<org>/<module>` from the configured repository URL —
81                // alef is vendor-neutral, so we don't fall back to a fixed org.
82                let org = config
83                    .try_github_repo()
84                    .ok()
85                    .as_deref()
86                    .and_then(alef_core::config::derive_repo_org)
87                    .unwrap_or_else(|| config.name.clone());
88                format!("{org}/{}", call.module.replace('_', "-"))
89            });
90        let pkg_path = php_pkg
91            .as_ref()
92            .and_then(|p| p.path.as_ref())
93            .cloned()
94            .unwrap_or_else(|| "../../packages/php".to_string());
95        let pkg_version = php_pkg
96            .as_ref()
97            .and_then(|p| p.version.as_ref())
98            .cloned()
99            .or_else(|| config.resolved_version())
100            .unwrap_or_else(|| "0.1.0".to_string());
101
102        // Derive the e2e composer project metadata from the consumer-binding
103        // pkg_name (`<vendor>/<crate>`) and the configured PHP autoload
104        // namespace — alef is vendor-neutral, so we don't fall back to a
105        // fixed "kreuzberg" string.
106        let e2e_vendor = pkg_name.split('/').next().unwrap_or(&pkg_name).to_string();
107        let e2e_pkg_name = format!("{e2e_vendor}/e2e-php");
108        // PSR-4 autoload keys appear inside a JSON document, so each PHP
109        // namespace separator must be JSON-escaped (`\` → `\\`). The trailing
110        // pair represents the PHP-mandated trailing `\` (which itself escapes
111        // to `\\` in JSON).
112        let php_namespace_escaped = php_autoload_namespace(config).replace('\\', "\\\\");
113        let e2e_autoload_ns = format!("{php_namespace_escaped}\\\\E2e\\\\");
114
115        // Generate composer.json.
116        files.push(GeneratedFile {
117            path: output_base.join("composer.json"),
118            content: render_composer_json(
119                &e2e_pkg_name,
120                &e2e_autoload_ns,
121                &pkg_name,
122                &pkg_path,
123                &pkg_version,
124                e2e_config.dep_mode,
125            ),
126            generated_header: false,
127        });
128
129        // Generate phpunit.xml.
130        files.push(GeneratedFile {
131            path: output_base.join("phpunit.xml"),
132            content: render_phpunit_xml(),
133            generated_header: false,
134        });
135
136        // Check if any fixture needs a mock HTTP server (either http-shape or
137        // liter-llm mock_response-shape) so bootstrap.php spawns it.
138        let has_http_fixtures = groups
139            .iter()
140            .flat_map(|g| g.fixtures.iter())
141            .any(|f| f.needs_mock_server());
142
143        // Check if any fixture uses file_path or bytes args (needs chdir to test_documents).
144        let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
145            let cc = e2e_config.resolve_call_for_fixture(
146                f.call.as_deref(),
147                &f.id,
148                &f.resolved_category(),
149                &f.tags,
150                &f.input,
151            );
152            cc.args
153                .iter()
154                .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
155        });
156
157        // Generate bootstrap.php that loads both autoloaders and optionally starts the mock server.
158        files.push(GeneratedFile {
159            path: output_base.join("bootstrap.php"),
160            content: render_bootstrap(
161                &pkg_path,
162                has_http_fixtures,
163                has_file_fixtures,
164                &e2e_config.test_documents_relative_from(0),
165            ),
166            generated_header: true,
167        });
168
169        // Generate run_tests.php that loads the extension and invokes phpunit.
170        files.push(GeneratedFile {
171            path: output_base.join("run_tests.php"),
172            content: render_run_tests_php(&extension_name, config.php_cargo_crate_name()),
173            generated_header: true,
174        });
175
176        // Generate test files per category.
177        let tests_base = output_base.join("tests");
178
179        // Compute per-(type, field) getter classification for PHP.
180        // ext-php-rs 0.15.x exposes scalar fields as PHP properties via `#[php(prop)]`,
181        // but non-scalar fields (Named structs, Vec<Named>, Map, etc.) need a
182        // `#[php(getter)]` method because `get_method_props` is `todo!()` in
183        // ext-php-rs-derive 0.11.7. E2e assertions must call `->getCamelCase()` for those.
184        //
185        // The classification MUST be keyed by (owner_type, field_name) rather than
186        // bare field_name: two unrelated types can declare the same field name with
187        // different scalarness (e.g. `CrawlConfig.content: ContentConfig` vs
188        // `MarkdownResult.content: String`). A bare-name union would force every
189        // `->content` access to `->getContent()` even on types where it is a scalar
190        // property — see kreuzcrawl regression where `MarkdownResult::getContent()`
191        // does not exist.
192        let php_enum_names: HashSet<String> = enums.iter().map(|e| e.name.clone()).collect();
193
194        for group in groups {
195            let active: Vec<&Fixture> = group
196                .fixtures
197                .iter()
198                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
199                .collect();
200
201            if active.is_empty() {
202                continue;
203            }
204
205            let test_class = format!("{}Test", sanitize_filename(&group.category).to_upper_camel_case());
206            let filename = format!("{test_class}.php");
207            let content = render_test_file(
208                &group.category,
209                &active,
210                e2e_config,
211                lang,
212                &namespace,
213                &class_name,
214                &test_class,
215                type_defs,
216                &php_enum_names,
217                enum_fields,
218                result_is_simple,
219                php_client_factory,
220                options_via,
221                &config.adapters,
222            );
223            files.push(GeneratedFile {
224                path: tests_base.join(filename),
225                content,
226                generated_header: true,
227            });
228        }
229
230        Ok(files)
231    }
232
233    fn language_name(&self) -> &'static str {
234        "php"
235    }
236}
237
238// ---------------------------------------------------------------------------
239// PHP scalar-type predicate
240// ---------------------------------------------------------------------------
241
242/// Returns true when a type is scalar-compatible for ext-php-rs `#[php(prop)]` —
243/// that is, the mapped Rust type implements `IntoZval` + `FromZval` automatically
244/// without a manual getter. Mirrors `is_php_prop_scalar_with_enums` from
245/// `alef-backend-php/src/gen_bindings/types.rs`.
246///
247/// Scalar-compatible: primitives, String, Char, Duration (→ u64), Path (→ String),
248/// Option<scalar>, Vec<primitive|String|Char>, unit-variant enums (mapped to String).
249/// Non-scalar: Named struct, Map, nested Vec<Named>, Json, Bytes.
250/// Build a per-`(owner_type, field_name)` PHP getter classification plus chain-resolution
251/// metadata from the IR's `TypeDef`s.
252///
253/// For each type, marks fields as needing getter syntax when their mapped Rust type
254/// is non-scalar in PHP (Named struct, Vec<Named>, Map, Json, Bytes). Also records each
255/// field's referenced `Named` inner type so the resolver can advance the current-type
256/// cursor as it walks multi-segment paths like `outer.inner.content`.
257///
258/// `root_type` is derived (best-effort) from a `result_type` override on any backend
259/// (`c`, `csharp`, `java`, `kotlin`, `go`, `php`) and otherwise inferred by matching
260/// `result_fields` against `TypeDef.fields`. When no root can be determined, chain
261/// resolution falls back to the legacy bare-name union (sound only when no field names
262/// collide across types).
263fn build_php_getter_map(
264    type_defs: &[alef_core::ir::TypeDef],
265    enum_names: &HashSet<String>,
266    call: &alef_core::config::e2e::CallConfig,
267    result_fields: &HashSet<String>,
268) -> PhpGetterMap {
269    let mut getters: HashMap<String, HashSet<String>> = HashMap::new();
270    let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
271    let mut all_fields: HashMap<String, HashSet<String>> = HashMap::new();
272    for td in type_defs {
273        let mut getter_fields: HashSet<String> = HashSet::new();
274        let mut field_type_map: HashMap<String, String> = HashMap::new();
275        let mut td_all_fields: HashSet<String> = HashSet::new();
276        for f in &td.fields {
277            td_all_fields.insert(f.name.clone());
278            if !is_php_scalar(&f.ty, enum_names) {
279                getter_fields.insert(f.name.clone());
280            }
281            if let Some(named) = inner_named(&f.ty) {
282                field_type_map.insert(f.name.clone(), named);
283            }
284        }
285        getters.insert(td.name.clone(), getter_fields);
286        all_fields.insert(td.name.clone(), td_all_fields);
287        if !field_type_map.is_empty() {
288            field_types.insert(td.name.clone(), field_type_map);
289        }
290    }
291    let root_type = derive_root_type(call, type_defs, result_fields);
292    PhpGetterMap {
293        getters,
294        field_types,
295        root_type,
296        all_fields,
297    }
298}
299
300/// Unwrap `Option<T>` / `Vec<T>` to the innermost `Named` type name, if any.
301/// Returns `None` for primitives, scalars, Map, Json, Bytes, and Unit.
302fn inner_named(ty: &TypeRef) -> Option<String> {
303    match ty {
304        TypeRef::Named(n) => Some(n.clone()),
305        TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
306        _ => None,
307    }
308}
309
310/// Derive the IR type name backing the result variable in PHP-generated assertions.
311///
312/// Lookup order:
313/// 1. `call.overrides[<lang>].result_type` for any of `php`, `c`, `csharp`, `java`,
314///    `kotlin`, `go` (first non-empty wins).
315/// 2. Type-defs whose field names form a superset of `result_fields` (when exactly
316///    one matches).
317///
318/// Returns `None` when neither yields a definitive answer; callers fall back to the
319/// legacy bare-name union behaviour.
320fn derive_root_type(
321    call: &alef_core::config::e2e::CallConfig,
322    type_defs: &[alef_core::ir::TypeDef],
323    result_fields: &HashSet<String>,
324) -> Option<String> {
325    const LOOKUP_LANGS: &[&str] = &["php", "c", "csharp", "java", "kotlin", "go"];
326    for lang in LOOKUP_LANGS {
327        if let Some(o) = call.overrides.get(*lang)
328            && let Some(rt) = o.result_type.as_deref()
329            && !rt.is_empty()
330            && type_defs.iter().any(|td| td.name == rt)
331        {
332            return Some(rt.to_string());
333        }
334    }
335    if result_fields.is_empty() {
336        return None;
337    }
338    let matches: Vec<&alef_core::ir::TypeDef> = type_defs
339        .iter()
340        .filter(|td| {
341            let names: HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
342            result_fields.iter().all(|rf| names.contains(rf.as_str()))
343        })
344        .collect();
345    if matches.len() == 1 {
346        return Some(matches[0].name.clone());
347    }
348    None
349}
350
351fn is_php_scalar(ty: &TypeRef, enum_names: &HashSet<String>) -> bool {
352    match ty {
353        TypeRef::Primitive(_) | TypeRef::String | TypeRef::Char | TypeRef::Duration | TypeRef::Path => true,
354        TypeRef::Optional(inner) => is_php_scalar(inner, enum_names),
355        TypeRef::Vec(inner) => {
356            matches!(inner.as_ref(), TypeRef::Primitive(_) | TypeRef::String | TypeRef::Char)
357                || matches!(inner.as_ref(), TypeRef::Named(n) if enum_names.contains(n))
358        }
359        TypeRef::Named(n) if enum_names.contains(n) => true,
360        TypeRef::Named(_) | TypeRef::Map(_, _) | TypeRef::Json | TypeRef::Bytes | TypeRef::Unit => false,
361    }
362}
363
364// ---------------------------------------------------------------------------
365// Rendering
366// ---------------------------------------------------------------------------
367
368fn render_composer_json(
369    e2e_pkg_name: &str,
370    e2e_autoload_ns: &str,
371    pkg_name: &str,
372    pkg_path: &str,
373    pkg_version: &str,
374    dep_mode: crate::config::DependencyMode,
375) -> String {
376    let (require_section, autoload_section) = match dep_mode {
377        crate::config::DependencyMode::Registry => {
378            let require = format!(
379                r#"  "require": {{
380    "{pkg_name}": "{pkg_version}"
381  }},
382  "require-dev": {{
383    "phpunit/phpunit": "{phpunit}",
384    "guzzlehttp/guzzle": "{guzzle}"
385  }},"#,
386                phpunit = tv::packagist::PHPUNIT,
387                guzzle = tv::packagist::GUZZLE,
388            );
389            (require, String::new())
390        }
391        crate::config::DependencyMode::Local => {
392            let require = format!(
393                r#"  "require-dev": {{
394    "phpunit/phpunit": "{phpunit}",
395    "guzzlehttp/guzzle": "{guzzle}"
396  }},"#,
397                phpunit = tv::packagist::PHPUNIT,
398                guzzle = tv::packagist::GUZZLE,
399            );
400            // For local mode, add autoload for the local package source.
401            // Extract the namespace from pkg_name (org/module) and map it to src/.
402            let pkg_namespace = pkg_name
403                .split('/')
404                .nth(1)
405                .unwrap_or(pkg_name)
406                .split('-')
407                .map(heck::ToUpperCamelCase::to_upper_camel_case)
408                .collect::<Vec<_>>()
409                .join("\\");
410            let autoload = format!(
411                r#"
412  "autoload": {{
413    "psr-4": {{
414      "{}\\": "{}/src/"
415    }}
416  }},"#,
417                pkg_namespace.replace('\\', "\\\\"),
418                pkg_path
419            );
420            (require, autoload)
421        }
422    };
423
424    crate::template_env::render(
425        "php/composer.json.jinja",
426        minijinja::context! {
427            e2e_pkg_name => e2e_pkg_name,
428            e2e_autoload_ns => e2e_autoload_ns,
429            require_section => require_section,
430            autoload_section => autoload_section,
431        },
432    )
433}
434
435fn render_phpunit_xml() -> String {
436    crate::template_env::render("php/phpunit.xml.jinja", minijinja::context! {})
437}
438
439fn render_bootstrap(
440    pkg_path: &str,
441    has_http_fixtures: bool,
442    has_file_fixtures: bool,
443    test_documents_path: &str,
444) -> String {
445    let header = hash::header(CommentStyle::DoubleSlash);
446    crate::template_env::render(
447        "php/bootstrap.php.jinja",
448        minijinja::context! {
449            header => header,
450            pkg_path => pkg_path,
451            has_http_fixtures => has_http_fixtures,
452            has_file_fixtures => has_file_fixtures,
453            test_documents_path => test_documents_path,
454        },
455    )
456}
457
458fn render_run_tests_php(extension_name: &str, cargo_crate_name: Option<&str>) -> String {
459    let header = hash::header(CommentStyle::DoubleSlash);
460    let ext_lib_name = if let Some(crate_name) = cargo_crate_name {
461        // Cargo replaces hyphens with underscores for lib names, and the crate name
462        // already includes the _php suffix.
463        format!("lib{}", crate_name.replace('-', "_"))
464    } else {
465        format!("lib{extension_name}_php")
466    };
467    format!(
468        r#"#!/usr/bin/env php
469<?php
470{header}
471declare(strict_types=1);
472
473// Determine platform-specific extension suffix.
474$extSuffix = match (PHP_OS_FAMILY) {{
475    'Darwin' => '.dylib',
476    default => '.so',
477}};
478$extPath = __DIR__ . '/../../target/release/{ext_lib_name}' . $extSuffix;
479
480// If the locally-built extension exists and we have not already restarted with it,
481// re-exec PHP with no system ini (-n) to avoid conflicts with any system-installed
482// version of the extension, then load the local build explicitly.
483if (file_exists($extPath) && !getenv('ALEF_PHP_LOCAL_EXT_LOADED')) {{
484    putenv('ALEF_PHP_LOCAL_EXT_LOADED=1');
485    $php = PHP_BINARY;
486    $phpunitPath = __DIR__ . '/vendor/bin/phpunit';
487
488    $cmd = array_merge(
489        [$php, '-n', '-d', 'extension=' . $extPath],
490        [$phpunitPath],
491        array_slice($GLOBALS['argv'], 1)
492    );
493
494    passthru(implode(' ', array_map('escapeshellarg', $cmd)), $exitCode);
495    exit($exitCode);
496}}
497
498// Extension is now loaded (via the restart above with -n flag).
499// Invoke PHPUnit normally.
500$phpunitPath = __DIR__ . '/vendor/bin/phpunit';
501if (!file_exists($phpunitPath)) {{
502    echo "PHPUnit not found at $phpunitPath. Run 'composer install' first.\n";
503    exit(1);
504}}
505
506require $phpunitPath;
507"#
508    )
509}
510
511#[allow(clippy::too_many_arguments)]
512fn render_test_file(
513    category: &str,
514    fixtures: &[&Fixture],
515    e2e_config: &E2eConfig,
516    lang: &str,
517    namespace: &str,
518    class_name: &str,
519    test_class: &str,
520    type_defs: &[alef_core::ir::TypeDef],
521    php_enum_names: &HashSet<String>,
522    enum_fields: &HashMap<String, String>,
523    result_is_simple: bool,
524    php_client_factory: Option<&str>,
525    options_via: &str,
526    adapters: &[alef_core::config::extras::AdapterConfig],
527) -> String {
528    let header = hash::header(CommentStyle::DoubleSlash);
529
530    // Determine if any handle arg has a non-null config (needs CrawlConfig import).
531    let needs_crawl_config_import = fixtures.iter().any(|f| {
532        let call =
533            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
534        call.args.iter().filter(|a| a.arg_type == "handle").any(|a| {
535            let v = f.input.get(&a.field).unwrap_or(&serde_json::Value::Null);
536            !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
537        })
538    });
539
540    // Determine if any fixture is an HTTP test (needs GuzzleHttp).
541    let has_http_tests = fixtures.iter().any(|f| f.is_http_test());
542
543    // Collect options_type class names that need `use` imports (one import per unique name).
544    let mut options_type_imports: Vec<String> = fixtures
545        .iter()
546        .flat_map(|f| {
547            let call = e2e_config.resolve_call_for_fixture(
548                f.call.as_deref(),
549                &f.id,
550                &f.resolved_category(),
551                &f.tags,
552                &f.input,
553            );
554            let php_override = call.overrides.get(lang);
555            let opt_type = php_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
556                e2e_config
557                    .call
558                    .overrides
559                    .get(lang)
560                    .and_then(|o| o.options_type.as_deref())
561            });
562            let element_types: Vec<String> = call
563                .args
564                .iter()
565                .filter_map(|a| a.element_type.as_ref().map(|t| t.to_string()))
566                .filter(|t| !is_php_reserved_type(t))
567                .collect();
568            opt_type.map(|t| t.to_string()).into_iter().chain(element_types)
569        })
570        .collect::<std::collections::HashSet<_>>()
571        .into_iter()
572        .collect();
573    options_type_imports.sort();
574
575    // Build imports_use list
576    let mut imports_use: Vec<String> = Vec::new();
577    if needs_crawl_config_import {
578        imports_use.push(format!("use {namespace}\\CrawlConfig;"));
579    }
580    for type_name in &options_type_imports {
581        if type_name != class_name {
582            imports_use.push(format!("use {namespace}\\{type_name};"));
583        }
584    }
585
586    // Render all test methods
587    let mut fixtures_body = String::new();
588    for (i, fixture) in fixtures.iter().enumerate() {
589        if fixture.is_http_test() {
590            render_http_test_method(&mut fixtures_body, fixture, fixture.http.as_ref().unwrap());
591        } else {
592            render_test_method(
593                &mut fixtures_body,
594                fixture,
595                e2e_config,
596                lang,
597                namespace,
598                class_name,
599                type_defs,
600                php_enum_names,
601                enum_fields,
602                result_is_simple,
603                php_client_factory,
604                options_via,
605                adapters,
606            );
607        }
608        if i + 1 < fixtures.len() {
609            fixtures_body.push('\n');
610        }
611    }
612
613    crate::template_env::render(
614        "php/test_file.jinja",
615        minijinja::context! {
616            header => header,
617            namespace => namespace,
618            class_name => class_name,
619            test_class => test_class,
620            category => category,
621            imports_use => imports_use,
622            has_http_tests => has_http_tests,
623            fixtures_body => fixtures_body,
624        },
625    )
626}
627
628// ---------------------------------------------------------------------------
629// HTTP test rendering — shared-driver integration
630// ---------------------------------------------------------------------------
631
632/// Thin renderer that emits PHPUnit test methods targeting a mock server via
633/// Guzzle. Satisfies [`client::TestClientRenderer`] so the shared
634/// [`client::http_call::render_http_test`] driver drives the call sequence.
635struct PhpTestClientRenderer;
636
637impl client::TestClientRenderer for PhpTestClientRenderer {
638    fn language_name(&self) -> &'static str {
639        "php"
640    }
641
642    /// Convert a fixture id to a PHP-valid identifier (snake_case via `sanitize_filename`).
643    fn sanitize_test_name(&self, id: &str) -> String {
644        sanitize_filename(id)
645    }
646
647    /// Emit `/** {description} */ public function test_{fn_name}(): void {`.
648    ///
649    /// When `skip_reason` is `Some`, emits a `markTestSkipped(...)` body and the
650    /// shared driver calls `render_test_close` immediately after, so the closing
651    /// brace is emitted symmetrically.
652    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
653        let escaped_reason = skip_reason.map(escape_php);
654        let rendered = crate::template_env::render(
655            "php/http_test_open.jinja",
656            minijinja::context! {
657                fn_name => fn_name,
658                description => description,
659                skip_reason => escaped_reason,
660            },
661        );
662        out.push_str(&rendered);
663    }
664
665    /// Emit the closing `}` for a test method.
666    fn render_test_close(&self, out: &mut String) {
667        let rendered = crate::template_env::render("php/http_test_close.jinja", minijinja::context! {});
668        out.push_str(&rendered);
669    }
670
671    /// Emit a Guzzle request to the mock server's `/fixtures/<fixture_id>` endpoint.
672    ///
673    /// The fixture id is extracted from the path (which the mock server routes as
674    /// `/fixtures/<id>`). `$response` is bound for subsequent assertion methods.
675    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
676        let method = ctx.method.to_uppercase();
677
678        // Build Guzzle options array.
679        let mut opts: Vec<String> = Vec::new();
680
681        if let Some(body) = ctx.body {
682            let php_body = json_to_php(body);
683            opts.push(format!("'json' => {php_body}"));
684        }
685
686        // Merge explicit headers and content_type hint.
687        let mut header_pairs: Vec<String> = Vec::new();
688        if let Some(ct) = ctx.content_type {
689            // Only emit if not already in ctx.headers (avoid duplicate Content-Type).
690            if !ctx.headers.keys().any(|k| k.to_lowercase() == "content-type") {
691                header_pairs.push(format!("\"Content-Type\" => \"{}\"", escape_php(ct)));
692            }
693        }
694        for (k, v) in ctx.headers {
695            header_pairs.push(format!("\"{}\" => \"{}\"", escape_php(k), escape_php(v)));
696        }
697        if !header_pairs.is_empty() {
698            opts.push(format!("'headers' => [{}]", header_pairs.join(", ")));
699        }
700
701        if !ctx.cookies.is_empty() {
702            let cookie_str = ctx
703                .cookies
704                .iter()
705                .map(|(k, v)| format!("{}={}", k, v))
706                .collect::<Vec<_>>()
707                .join("; ");
708            opts.push(format!("'headers' => ['Cookie' => \"{}\"]", escape_php(&cookie_str)));
709        }
710
711        if !ctx.query_params.is_empty() {
712            let pairs: Vec<String> = ctx
713                .query_params
714                .iter()
715                .map(|(k, v)| {
716                    let val_str = match v {
717                        serde_json::Value::String(s) => s.clone(),
718                        other => other.to_string(),
719                    };
720                    format!("\"{}\" => \"{}\"", escape_php(k), escape_php(&val_str))
721                })
722                .collect();
723            opts.push(format!("'query' => [{}]", pairs.join(", ")));
724        }
725
726        let path_lit = format!("\"{}\"", escape_php(ctx.path));
727
728        let rendered = crate::template_env::render(
729            "php/http_request.jinja",
730            minijinja::context! {
731                method => method,
732                path => path_lit,
733                opts => opts,
734                response_var => ctx.response_var,
735            },
736        );
737        out.push_str(&rendered);
738    }
739
740    /// Emit `$this->assertEquals(status, $response->getStatusCode())`.
741    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
742        let rendered = crate::template_env::render(
743            "php/http_assertions.jinja",
744            minijinja::context! {
745                response_var => "",
746                status_code => status,
747                headers => Vec::<std::collections::HashMap<&str, String>>::new(),
748                body_assertion => String::new(),
749                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
750                validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
751            },
752        );
753        out.push_str(&rendered);
754    }
755
756    /// Emit a header assertion using `$response->getHeaderLine(...)` or
757    /// `$response->hasHeader(...)`.
758    ///
759    /// Handles special tokens: `<<present>>`, `<<absent>>`, `<<uuid>>`.
760    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
761        let header_key = name.to_lowercase();
762        let header_key_lit = format!("\"{}\"", escape_php(&header_key));
763        let assertion_code = match expected {
764            "<<present>>" => {
765                format!("$this->assertTrue($response->hasHeader({header_key_lit}));")
766            }
767            "<<absent>>" => {
768                format!("$this->assertFalse($response->hasHeader({header_key_lit}));")
769            }
770            "<<uuid>>" => {
771                format!(
772                    "$this->assertMatchesRegularExpression('/^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$/i', $response->getHeaderLine({header_key_lit}));"
773                )
774            }
775            literal => {
776                let val_lit = format!("\"{}\"", escape_php(literal));
777                format!("$this->assertEquals({val_lit}, $response->getHeaderLine({header_key_lit}));")
778            }
779        };
780
781        let mut headers = vec![std::collections::HashMap::new()];
782        headers[0].insert("assertion_code", assertion_code);
783
784        let rendered = crate::template_env::render(
785            "php/http_assertions.jinja",
786            minijinja::context! {
787                response_var => "",
788                status_code => 0u16,
789                headers => headers,
790                body_assertion => String::new(),
791                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
792                validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
793            },
794        );
795        out.push_str(&rendered);
796    }
797
798    /// Emit a JSON body equality assertion.
799    ///
800    /// Plain string bodies are compared against `(string) $response->getBody()` directly;
801    /// structured bodies (objects, arrays, booleans, numbers) are decoded via `json_decode`
802    /// and compared with `assertEquals`.
803    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
804        let body_assertion = match expected {
805            serde_json::Value::String(s) if !s.is_empty() => {
806                let php_val = format!("\"{}\"", escape_php(s));
807                format!("$this->assertEquals({php_val}, (string) $response->getBody());")
808            }
809            _ => {
810                let php_val = json_to_php(expected);
811                format!(
812                    "$body = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);\n        $this->assertEquals({php_val}, $body);"
813                )
814            }
815        };
816
817        let rendered = crate::template_env::render(
818            "php/http_assertions.jinja",
819            minijinja::context! {
820                response_var => "",
821                status_code => 0u16,
822                headers => Vec::<std::collections::HashMap<&str, String>>::new(),
823                body_assertion => body_assertion,
824                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
825                validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
826            },
827        );
828        out.push_str(&rendered);
829    }
830
831    /// Emit partial body assertions: one `assertEquals` per field in `expected`.
832    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
833        if let Some(obj) = expected.as_object() {
834            let mut partial_body: Vec<std::collections::HashMap<&str, String>> = Vec::new();
835            for (key, val) in obj {
836                let php_key = format!("\"{}\"", escape_php(key));
837                let php_val = json_to_php(val);
838                let assertion_code = format!("$this->assertEquals({php_val}, $body[{php_key}]);");
839                let mut entry = std::collections::HashMap::new();
840                entry.insert("assertion_code", assertion_code);
841                partial_body.push(entry);
842            }
843
844            let rendered = crate::template_env::render(
845                "php/http_assertions.jinja",
846                minijinja::context! {
847                    response_var => "",
848                    status_code => 0u16,
849                    headers => Vec::<std::collections::HashMap<&str, String>>::new(),
850                    body_assertion => String::new(),
851                    partial_body => partial_body,
852                    validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
853                },
854            );
855            out.push_str(&rendered);
856        }
857    }
858
859    /// Emit validation-error assertions, checking each expected `msg` against the
860    /// JSON-encoded body string (PHP binding returns ProblemDetails with `errors` array).
861    fn render_assert_validation_errors(
862        &self,
863        out: &mut String,
864        _response_var: &str,
865        errors: &[ValidationErrorExpectation],
866    ) {
867        let mut validation_errors: Vec<std::collections::HashMap<&str, String>> = Vec::new();
868        for err in errors {
869            let msg_lit = format!("\"{}\"", escape_php(&err.msg));
870            let assertion_code =
871                format!("$this->assertStringContainsString({msg_lit}, json_encode($body, JSON_UNESCAPED_SLASHES));");
872            let mut entry = std::collections::HashMap::new();
873            entry.insert("assertion_code", assertion_code);
874            validation_errors.push(entry);
875        }
876
877        let rendered = crate::template_env::render(
878            "php/http_assertions.jinja",
879            minijinja::context! {
880                response_var => "",
881                status_code => 0u16,
882                headers => Vec::<std::collections::HashMap<&str, String>>::new(),
883                body_assertion => String::new(),
884                partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
885                validation_errors => validation_errors,
886            },
887        );
888        out.push_str(&rendered);
889    }
890}
891
892/// Render a PHPUnit test method for an HTTP server test fixture via the shared driver.
893///
894/// Handles the one PHP-specific pre-condition: HTTP 101 (WebSocket upgrade) causes
895/// cURL/Guzzle to fail; it is emitted as a `markTestSkipped` stub directly.
896fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
897    // HTTP 101 (WebSocket upgrade) causes cURL to treat the connection as an upgrade
898    // and fail with "empty reply from server". Skip these tests in the PHP e2e suite
899    // since Guzzle cannot assert on WebSocket upgrade responses via regular HTTP.
900    if http.expected_response.status_code == 101 {
901        let method_name = sanitize_filename(&fixture.id);
902        let description = &fixture.description;
903        out.push_str(&crate::template_env::render(
904            "php/http_test_skip_101.jinja",
905            minijinja::context! {
906                method_name => method_name,
907                description => description,
908            },
909        ));
910        return;
911    }
912
913    client::http_call::render_http_test(out, &PhpTestClientRenderer, fixture);
914}
915
916// ---------------------------------------------------------------------------
917// Function-call test rendering
918// ---------------------------------------------------------------------------
919
920#[allow(clippy::too_many_arguments)]
921fn render_test_method(
922    out: &mut String,
923    fixture: &Fixture,
924    e2e_config: &E2eConfig,
925    lang: &str,
926    namespace: &str,
927    class_name: &str,
928    type_defs: &[alef_core::ir::TypeDef],
929    php_enum_names: &HashSet<String>,
930    enum_fields: &HashMap<String, String>,
931    result_is_simple: bool,
932    php_client_factory: Option<&str>,
933    options_via: &str,
934    adapters: &[alef_core::config::extras::AdapterConfig],
935) {
936    // Resolve per-fixture call config: supports named calls via fixture.call field.
937    let call_config = e2e_config.resolve_call_for_fixture(
938        fixture.call.as_deref(),
939        &fixture.id,
940        &fixture.resolved_category(),
941        &fixture.tags,
942        &fixture.input,
943    );
944    // Build per-call PHP getter map and field resolver using the effective field sets.
945    let per_call_getter_map = build_php_getter_map(
946        type_defs,
947        php_enum_names,
948        call_config,
949        e2e_config.effective_result_fields(call_config),
950    );
951    let call_field_resolver = FieldResolver::new_with_php_getters(
952        e2e_config.effective_fields(call_config),
953        e2e_config.effective_fields_optional(call_config),
954        e2e_config.effective_result_fields(call_config),
955        e2e_config.effective_fields_array(call_config),
956        &HashSet::new(),
957        &HashMap::new(),
958        per_call_getter_map,
959    );
960    let field_resolver = &call_field_resolver;
961    let call_overrides = call_config.overrides.get(lang);
962    let has_override = call_overrides.is_some_and(|o| o.function.is_some());
963    // Per-call result_is_simple override wins over the language-level default,
964    // so calls like `speech` (returns Vec<u8>) can be marked simple even if
965    // chat/embed are not.
966    let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || result_is_simple;
967    let mut function_name = call_overrides
968        .and_then(|o| o.function.as_ref())
969        .cloned()
970        .unwrap_or_else(|| call_config.function.clone());
971    // The PHP facade exposes async Rust methods under their bare name (no `_async`
972    // suffix) — PHP has no surface-level async, so the facade picks the async
973    // implementation as the default and delegates to `*Async` on the native class.
974    // The `*_sync` variants stay explicit (e.g. `extract_bytes_sync` → `extractBytesSync`).
975    if !has_override {
976        function_name = function_name.to_lower_camel_case();
977    }
978    let result_var = &call_config.result_var;
979    let args = &call_config.args;
980
981    let method_name = sanitize_filename(&fixture.id);
982    let description = &fixture.description;
983    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
984
985    // Resolve options_type for this call's PHP override, with fallback to the top-level call override.
986    let call_options_type = call_overrides.and_then(|o| o.options_type.as_deref()).or_else(|| {
987        e2e_config
988            .call
989            .overrides
990            .get(lang)
991            .and_then(|o| o.options_type.as_deref())
992    });
993
994    let adapter_request_type: Option<String> = adapters
995        .iter()
996        .find(|a| a.name == call_config.function.as_str())
997        .and_then(|a| a.request_type.as_deref())
998        .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
999    let (mut setup_lines, args_str) = build_args_and_setup(
1000        &fixture.input,
1001        args,
1002        class_name,
1003        enum_fields,
1004        fixture,
1005        options_via,
1006        call_options_type,
1007        adapter_request_type.as_deref(),
1008    );
1009
1010    // Check for skip_languages early
1011    let skip_test = call_config.skip_languages.iter().any(|l| l == "php");
1012    if skip_test {
1013        let rendered = crate::template_env::render(
1014            "php/test_method.jinja",
1015            minijinja::context! {
1016                method_name => method_name,
1017                description => description,
1018                client_factory => String::new(),
1019                setup_lines => Vec::<String>::new(),
1020                expects_error => false,
1021                skip_test => true,
1022                has_usable_assertions => false,
1023                call_expr => String::new(),
1024                result_var => result_var,
1025                assertions_body => String::new(),
1026            },
1027        );
1028        out.push_str(&rendered);
1029        return;
1030    }
1031
1032    // Build visitor if present and add to setup
1033    let mut options_already_created = !args_str.is_empty() && args_str == "$options";
1034    if let Some(visitor_spec) = &fixture.visitor {
1035        build_php_visitor(&mut setup_lines, visitor_spec);
1036        if !options_already_created {
1037            let options_type = call_options_type.unwrap_or("ConversionOptions");
1038            setup_lines.push(format!("$builder = \\{namespace}\\{options_type}::builder();"));
1039            setup_lines.push("$options = $builder->visitor($visitor)->build();".to_string());
1040            options_already_created = true;
1041        }
1042    }
1043
1044    let final_args = if options_already_created {
1045        if args_str.is_empty() || args_str == "$options" {
1046            "$options".to_string()
1047        } else {
1048            format!("{args_str}, $options")
1049        }
1050    } else {
1051        args_str
1052    };
1053
1054    let call_expr = if php_client_factory.is_some() {
1055        format!("$client->{function_name}({final_args})")
1056    } else {
1057        format!("{class_name}::{function_name}({final_args})")
1058    };
1059
1060    let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1061    let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1062    let client_factory = if let Some(factory) = php_client_factory {
1063        let fixture_id = &fixture.id;
1064        if let Some(var) = api_key_var.filter(|_| has_mock) {
1065            format!(
1066                "$apiKey = getenv('{var}');\n        $baseUrl = ($apiKey !== false && $apiKey !== '') ? null : getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';\n        fwrite(STDERR, \"{fixture_id}: \" . ($baseUrl === null ? 'using real API ({var} is set)' : 'using mock server ({var} not set)') . \"\\n\");\n        $client = \\{namespace}\\{class_name}::{factory}($baseUrl === null ? $apiKey : 'test-key', $baseUrl);"
1067            )
1068        } else if has_mock {
1069            let base_url_expr = if fixture.has_host_root_route() {
1070                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1071                format!("(getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}')")
1072            } else {
1073                format!("getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}'")
1074            };
1075            format!("$client = \\{namespace}\\{class_name}::{factory}('test-key', {base_url_expr});")
1076        } else if let Some(var) = api_key_var {
1077            format!(
1078                "$apiKey = getenv('{var}');\n        if (!$apiKey) {{ $this->markTestSkipped('{var} not set'); return; }}\n        $client = \\{namespace}\\{class_name}::{factory}($apiKey);"
1079            )
1080        } else {
1081            format!("$client = \\{namespace}\\{class_name}::{factory}('test-key');")
1082        }
1083    } else {
1084        String::new()
1085    };
1086
1087    // Streaming detection (call-level `streaming` opt-out is honored).
1088    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
1089
1090    // Determine if there are usable assertions.
1091    // For streaming fixtures: streaming virtual fields count as usable.
1092    let has_usable_assertions = fixture.assertions.iter().any(|a| {
1093        if a.assertion_type == "error" || a.assertion_type == "not_error" {
1094            return false;
1095        }
1096        match &a.field {
1097            Some(f) if !f.is_empty() => {
1098                if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1099                    return true;
1100                }
1101                field_resolver.is_valid_for_result(f)
1102            }
1103            _ => true,
1104        }
1105    });
1106
1107    // For streaming fixtures, emit collect snippet after the result assignment.
1108    let collect_snippet = if is_streaming {
1109        crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("php", result_var, "chunks")
1110            .unwrap_or_default()
1111    } else {
1112        String::new()
1113    };
1114
1115    // Render assertions_body
1116    let mut assertions_body = String::new();
1117    for assertion in &fixture.assertions {
1118        render_assertion(
1119            &mut assertions_body,
1120            assertion,
1121            result_var,
1122            field_resolver,
1123            result_is_simple,
1124            call_config.result_is_array,
1125        );
1126    }
1127
1128    // Streaming fixtures whose only assertion is `not_error` produce an empty
1129    // assertions_body even though the stream was drained successfully.  PHPUnit
1130    // flags such tests as "risky" (no assertions performed).  Emit a minimal
1131    // structural assertion against the drained chunk list so the test records
1132    // success without false-positive reliance on `expectNotToPerformAssertions`.
1133    if is_streaming && !expects_error && assertions_body.trim().is_empty() {
1134        assertions_body.push_str("        $this->assertTrue(is_array($chunks), 'expected drained chunks list');\n");
1135    }
1136
1137    let rendered = crate::template_env::render(
1138        "php/test_method.jinja",
1139        minijinja::context! {
1140            method_name => method_name,
1141            description => description,
1142            client_factory => client_factory,
1143            setup_lines => setup_lines,
1144            expects_error => expects_error,
1145            skip_test => fixture.assertions.is_empty(),
1146            has_usable_assertions => has_usable_assertions || is_streaming,
1147            call_expr => call_expr,
1148            result_var => result_var,
1149            collect_snippet => collect_snippet,
1150            assertions_body => assertions_body,
1151        },
1152    );
1153    out.push_str(&rendered);
1154}
1155
1156/// Build setup lines (e.g. handle creation) and the argument list for the function call.
1157///
1158/// `options_via` controls how `json_object` args are passed:
1159/// - `"array"` (default): PHP array literal `["key" => value, ...]`
1160/// - `"json"`: JSON string via `json_encode([...])` — use when the Rust method accepts `Option<String>`
1161///
1162/// `options_type` is the PHP class name (e.g. `"ProcessConfig"`) used when constructing options
1163/// via `ClassName::from_json(json_encode([...]))`. Required when `options_via` is not `"json"` and
1164/// the binding accepts a typed config object.
1165///
1166/// Returns `(setup_lines, args_string)`.
1167/// Emit PHP batch item array constructors for BatchBytesItem or BatchFileItem arrays.
1168fn emit_php_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1169    if let Some(items) = arr.as_array() {
1170        let item_strs: Vec<String> = items
1171            .iter()
1172            .filter_map(|item| {
1173                if let Some(obj) = item.as_object() {
1174                    match elem_type {
1175                        "BatchBytesItem" => {
1176                            let content = obj.get("content").and_then(|v| v.as_array());
1177                            let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1178                            let content_code = if let Some(arr) = content {
1179                                let bytes: Vec<String> = arr
1180                                    .iter()
1181                                    .filter_map(|v| v.as_u64())
1182                                    .map(|n| format!("\\x{:02x}", n))
1183                                    .collect();
1184                                format!("\"{}\"", bytes.join(""))
1185                            } else {
1186                                "\"\"".to_string()
1187                            };
1188                            Some(format!(
1189                                "new {}(content: {}, mimeType: \"{}\")",
1190                                elem_type, content_code, mime_type
1191                            ))
1192                        }
1193                        "BatchFileItem" => {
1194                            let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1195                            Some(format!("new {}(path: \"{}\")", elem_type, path))
1196                        }
1197                        _ => None,
1198                    }
1199                } else {
1200                    None
1201                }
1202            })
1203            .collect();
1204        format!("[{}]", item_strs.join(", "))
1205    } else {
1206        "[]".to_string()
1207    }
1208}
1209
1210#[allow(clippy::too_many_arguments)]
1211fn build_args_and_setup(
1212    input: &serde_json::Value,
1213    args: &[crate::config::ArgMapping],
1214    class_name: &str,
1215    _enum_fields: &HashMap<String, String>,
1216    fixture: &crate::fixture::Fixture,
1217    options_via: &str,
1218    options_type: Option<&str>,
1219    adapter_request_type: Option<&str>,
1220) -> (Vec<String>, String) {
1221    let fixture_id = &fixture.id;
1222    if args.is_empty() {
1223        // No args configuration: pass the whole input only if it's non-empty.
1224        // Functions with no parameters (e.g. list_models) have empty input and get no args.
1225        let is_empty_input = match input {
1226            serde_json::Value::Null => true,
1227            serde_json::Value::Object(m) => m.is_empty(),
1228            _ => false,
1229        };
1230        if is_empty_input {
1231            return (Vec::new(), String::new());
1232        }
1233        return (Vec::new(), json_to_php(input));
1234    }
1235
1236    let mut setup_lines: Vec<String> = Vec::new();
1237    let mut parts: Vec<String> = Vec::new();
1238
1239    // True when any arg after `from_idx` has a fixture value (or has no fixture
1240    // value but is required — i.e. would emit *something*). Used to decide
1241    // whether a missing optional middle arg must emit `null` to preserve the
1242    // positional argument layout, or can be safely dropped.
1243    let arg_has_emission = |arg: &crate::config::ArgMapping| -> bool {
1244        let val = if arg.field == "input" {
1245            Some(input)
1246        } else {
1247            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1248            input.get(field)
1249        };
1250        match val {
1251            None | Some(serde_json::Value::Null) => !arg.optional,
1252            Some(_) => true,
1253        }
1254    };
1255    let any_later_has_emission = |from_idx: usize| -> bool { args[from_idx..].iter().any(arg_has_emission) };
1256
1257    for (idx, arg) in args.iter().enumerate() {
1258        if arg.arg_type == "mock_url" {
1259            if fixture.has_host_root_route() {
1260                let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1261                setup_lines.push(format!(
1262                    "${} = getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1263                    arg.name,
1264                ));
1265            } else {
1266                setup_lines.push(format!(
1267                    "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1268                    arg.name,
1269                ));
1270            }
1271            if let Some(req_type) = adapter_request_type {
1272                let req_var = format!("${}_req", arg.name);
1273                setup_lines.push(format!("{req_var} = new {req_type}(${});", arg.name));
1274                parts.push(req_var);
1275            } else {
1276                parts.push(format!("${}", arg.name));
1277            }
1278            continue;
1279        }
1280
1281        if arg.arg_type == "handle" {
1282            // Generate a createEngine (or equivalent) call and pass the variable.
1283            let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1284            let config_value = if arg.field == "input" {
1285                input
1286            } else {
1287                let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1288                input.get(field).unwrap_or(&serde_json::Value::Null)
1289            };
1290            if config_value.is_null()
1291                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1292            {
1293                setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
1294            } else {
1295                let name = &arg.name;
1296                // Use CrawlConfig::from_json() instead of direct property assignment.
1297                // ext-php-rs doesn't support writable #[php(prop)] fields for complex types,
1298                // so serialize the config to JSON and use from_json() to construct it.
1299                // Filter out empty string enum values before passing to from_json().
1300                let filtered_config = filter_empty_enum_strings(config_value);
1301                setup_lines.push(format!(
1302                    "${name}_config = CrawlConfig::from_json(json_encode({}));",
1303                    json_to_php_camel_keys(&filtered_config)
1304                ));
1305                setup_lines.push(format!(
1306                    "${} = {class_name}::{constructor_name}(${name}_config);",
1307                    arg.name,
1308                ));
1309            }
1310            parts.push(format!("${}", arg.name));
1311            continue;
1312        }
1313
1314        let val = if arg.field == "input" {
1315            Some(input)
1316        } else {
1317            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1318            input.get(field)
1319        };
1320
1321        // Bytes args: fixture stores either a fixture-relative path string (load
1322        // with file_get_contents at runtime, mirroring the go/python convention)
1323        // or an inline byte array (encode as a "\xNN" escape string).
1324        if arg.arg_type == "bytes" {
1325            match val {
1326                None | Some(serde_json::Value::Null) => {
1327                    if arg.optional {
1328                        parts.push("null".to_string());
1329                    } else {
1330                        parts.push("\"\"".to_string());
1331                    }
1332                }
1333                Some(serde_json::Value::String(s)) => {
1334                    let var_name = format!("{}Bytes", arg.name);
1335                    setup_lines.push(format!(
1336                        "${var_name} = file_get_contents(\"{path}\");\n        if (${var_name} === false) {{ $this->fail(\"failed to read fixture: {path}\"); }}",
1337                        path = s.replace('"', "\\\"")
1338                    ));
1339                    parts.push(format!("${var_name}"));
1340                }
1341                Some(serde_json::Value::Array(arr)) => {
1342                    let bytes: String = arr
1343                        .iter()
1344                        .filter_map(|v| v.as_u64())
1345                        .map(|n| format!("\\x{:02x}", n))
1346                        .collect();
1347                    parts.push(format!("\"{bytes}\""));
1348                }
1349                Some(other) => {
1350                    parts.push(json_to_php(other));
1351                }
1352            }
1353            continue;
1354        }
1355
1356        match val {
1357            None | Some(serde_json::Value::Null) if arg.arg_type == "json_object" && arg.name == "config" => {
1358                // Special case: ExtractionConfig and similar config objects with no fixture value
1359                // should default to an empty instance (e.g., ExtractionConfig::from_json('{}'))
1360                // to satisfy required parameters. This check happens BEFORE the optional check
1361                // so that config args are always provided, even if marked optional in alef.toml.
1362                // Infer the type name from the arg name and capitalize it (e.g., "config" -> "ExtractionConfig").
1363                let type_name = if arg.name == "config" {
1364                    "ExtractionConfig".to_string()
1365                } else {
1366                    format!("{}Config", arg.name.to_upper_camel_case())
1367                };
1368                parts.push(format!("{type_name}::from_json('{{}}')"));
1369                continue;
1370            }
1371            None | Some(serde_json::Value::Null) if arg.optional => {
1372                // Optional arg with no fixture value. If a later arg WILL emit
1373                // something, we must keep this slot in place by passing `null`
1374                // so the positional argument layout matches the PHP signature.
1375                // Otherwise drop the trailing optional argument entirely.
1376                if any_later_has_emission(idx + 1) {
1377                    parts.push("null".to_string());
1378                }
1379                continue;
1380            }
1381            None | Some(serde_json::Value::Null) => {
1382                // Required arg with no fixture value: pass a language-appropriate default.
1383                let default_val = match arg.arg_type.as_str() {
1384                    "string" => "\"\"".to_string(),
1385                    "int" | "integer" => "0".to_string(),
1386                    "float" | "number" => "0.0".to_string(),
1387                    "bool" | "boolean" => "false".to_string(),
1388                    "json_object" if options_via == "json" => "null".to_string(),
1389                    _ => "null".to_string(),
1390                };
1391                parts.push(default_val);
1392            }
1393            Some(v) => {
1394                if arg.arg_type == "json_object" && !v.is_null() {
1395                    // Check for batch item arrays first
1396                    if let Some(elem_type) = &arg.element_type {
1397                        if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1398                            parts.push(emit_php_batch_item_array(v, elem_type));
1399                            continue;
1400                        }
1401                        // When element_type is a scalar/primitive and value is an array,
1402                        // pass it directly as a PHP array (e.g. ["python"]) rather than
1403                        // wrapping in a typed config constructor.
1404                        if v.is_array() && is_php_reserved_type(elem_type) {
1405                            parts.push(json_to_php(v));
1406                            continue;
1407                        }
1408                    }
1409                    match options_via {
1410                        "json" => {
1411                            // Pass as JSON string via json_encode(); the Rust method accepts Option<String>.
1412                            // Filter out empty string enum values.
1413                            let filtered_v = filter_empty_enum_strings(v);
1414
1415                            // If the config is empty after filtering, pass null instead.
1416                            if let serde_json::Value::Object(obj) = &filtered_v {
1417                                if obj.is_empty() {
1418                                    parts.push("null".to_string());
1419                                    continue;
1420                                }
1421                            }
1422
1423                            parts.push(format!("json_encode({})", json_to_php_camel_keys(&filtered_v)));
1424                            continue;
1425                        }
1426                        _ => {
1427                            if let Some(type_name) = options_type {
1428                                // Use TypeName::from_json(json_encode([...])) to construct the
1429                                // typed config object. ext-php-rs structs expose a from_json()
1430                                // static method that accepts a JSON string.
1431                                // Filter out empty string enum values before passing to from_json().
1432                                let filtered_v = filter_empty_enum_strings(v);
1433
1434                                // For empty objects, construct with from_json('{}') to get the
1435                                // type's defaults rather than passing null (which fails for non-optional params).
1436                                if let serde_json::Value::Object(obj) = &filtered_v {
1437                                    if obj.is_empty() {
1438                                        let arg_var = format!("${}", arg.name);
1439                                        setup_lines.push(format!("{arg_var} = {type_name}::from_json('{{}}');"));
1440                                        parts.push(arg_var);
1441                                        continue;
1442                                    }
1443                                }
1444
1445                                let arg_var = format!("${}", arg.name);
1446                                // PHP binding's serde wrapper applies `rename_all` per the per-language
1447                                // wire-case registry (`ResolvedCrateConfig::serde_rename_all_for_language`),
1448                                // which is camelCase for PHP — emit camelCase keys to match.
1449                                setup_lines.push(format!(
1450                                    "{arg_var} = {type_name}::from_json(json_encode({}));",
1451                                    json_to_php_camel_keys(&filtered_v)
1452                                ));
1453                                parts.push(arg_var);
1454                                continue;
1455                            }
1456                            // Fallback: builder pattern when no options_type is configured.
1457                            // This path is kept for backwards compatibility with projects
1458                            // that use a builder-style API without from_json().
1459                            if let Some(obj) = v.as_object() {
1460                                setup_lines.push("$builder = $this->createDefaultOptionsBuilder();".to_string());
1461                                for (k, vv) in obj {
1462                                    let snake_key = k.to_snake_case();
1463                                    if snake_key == "preprocessing" {
1464                                        if let Some(prep_obj) = vv.as_object() {
1465                                            let enabled =
1466                                                prep_obj.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);
1467                                            let preset =
1468                                                prep_obj.get("preset").and_then(|v| v.as_str()).unwrap_or("Minimal");
1469                                            let remove_navigation = prep_obj
1470                                                .get("remove_navigation")
1471                                                .and_then(|v| v.as_bool())
1472                                                .unwrap_or(true);
1473                                            let remove_forms =
1474                                                prep_obj.get("remove_forms").and_then(|v| v.as_bool()).unwrap_or(true);
1475                                            setup_lines.push(format!(
1476                                                "$preprocessing = $this->createPreprocessingOptions({}, {}, {}, {});",
1477                                                if enabled { "true" } else { "false" },
1478                                                json_to_php(&serde_json::Value::String(preset.to_string())),
1479                                                if remove_navigation { "true" } else { "false" },
1480                                                if remove_forms { "true" } else { "false" }
1481                                            ));
1482                                            setup_lines.push(
1483                                                "$builder = $builder->preprocessing($preprocessing);".to_string(),
1484                                            );
1485                                        }
1486                                    }
1487                                }
1488                                setup_lines.push("$options = $builder->build();".to_string());
1489                                parts.push("$options".to_string());
1490                                continue;
1491                            }
1492                        }
1493                    }
1494                }
1495                parts.push(json_to_php(v));
1496            }
1497        }
1498    }
1499
1500    (setup_lines, parts.join(", "))
1501}
1502
1503fn render_assertion(
1504    out: &mut String,
1505    assertion: &Assertion,
1506    result_var: &str,
1507    field_resolver: &FieldResolver,
1508    result_is_simple: bool,
1509    result_is_array: bool,
1510) {
1511    // Handle synthetic / derived fields before the is_valid_for_result check
1512    // so they are never treated as struct property accesses on the result.
1513    if let Some(f) = &assertion.field {
1514        match f.as_str() {
1515            "chunks_have_content" => {
1516                let pred = format!(
1517                    "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->content), true)"
1518                );
1519                out.push_str(&crate::template_env::render(
1520                    "php/synthetic_assertion.jinja",
1521                    minijinja::context! {
1522                        assertion_kind => "chunks_content",
1523                        assertion_type => assertion.assertion_type.as_str(),
1524                        pred => pred,
1525                        field_name => f,
1526                    },
1527                ));
1528                return;
1529            }
1530            "chunks_have_embeddings" => {
1531                let pred = format!(
1532                    "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->embedding), true)"
1533                );
1534                out.push_str(&crate::template_env::render(
1535                    "php/synthetic_assertion.jinja",
1536                    minijinja::context! {
1537                        assertion_kind => "chunks_embeddings",
1538                        assertion_type => assertion.assertion_type.as_str(),
1539                        pred => pred,
1540                        field_name => f,
1541                    },
1542                ));
1543                return;
1544            }
1545            // ---- EmbedResponse virtual fields ----
1546            // embed_texts returns array<array<float>> in PHP — no wrapper object.
1547            // $result_var is the embedding matrix; use it directly.
1548            "embeddings" => {
1549                let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1550                out.push_str(&crate::template_env::render(
1551                    "php/synthetic_assertion.jinja",
1552                    minijinja::context! {
1553                        assertion_kind => "embeddings",
1554                        assertion_type => assertion.assertion_type.as_str(),
1555                        php_val => php_val,
1556                        result_var => result_var,
1557                    },
1558                ));
1559                return;
1560            }
1561            "embedding_dimensions" => {
1562                let expr = format!("(empty(${result_var}) ? 0 : count(${result_var}[0]))");
1563                let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1564                out.push_str(&crate::template_env::render(
1565                    "php/synthetic_assertion.jinja",
1566                    minijinja::context! {
1567                        assertion_kind => "embedding_dimensions",
1568                        assertion_type => assertion.assertion_type.as_str(),
1569                        expr => expr,
1570                        php_val => php_val,
1571                    },
1572                ));
1573                return;
1574            }
1575            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1576                let pred = match f.as_str() {
1577                    "embeddings_valid" => {
1578                        format!("array_reduce(${result_var}, fn($carry, $e) => $carry && count($e) > 0, true)")
1579                    }
1580                    "embeddings_finite" => {
1581                        format!(
1582                            "array_reduce(${result_var}, fn($carry, $e) => $carry && array_reduce($e, fn($c, $v) => $c && is_finite($v), true), true)"
1583                        )
1584                    }
1585                    "embeddings_non_zero" => {
1586                        format!(
1587                            "array_reduce(${result_var}, fn($carry, $e) => $carry && count(array_filter($e, fn($v) => $v !== 0.0)) > 0, true)"
1588                        )
1589                    }
1590                    "embeddings_normalized" => {
1591                        format!(
1592                            "array_reduce(${result_var}, fn($carry, $e) => $carry && abs(array_sum(array_map(fn($v) => $v * $v, $e)) - 1.0) < 1e-3, true)"
1593                        )
1594                    }
1595                    _ => unreachable!(),
1596                };
1597                let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1598                out.push_str(&crate::template_env::render(
1599                    "php/synthetic_assertion.jinja",
1600                    minijinja::context! {
1601                        assertion_kind => assertion_kind,
1602                        assertion_type => assertion.assertion_type.as_str(),
1603                        pred => pred,
1604                        field_name => f,
1605                    },
1606                ));
1607                return;
1608            }
1609            // ---- keywords / keywords_count ----
1610            // PHP ExtractionResult does not expose extracted_keywords; skip.
1611            "keywords" | "keywords_count" => {
1612                out.push_str(&crate::template_env::render(
1613                    "php/synthetic_assertion.jinja",
1614                    minijinja::context! {
1615                        assertion_kind => "keywords",
1616                        field_name => f,
1617                    },
1618                ));
1619                return;
1620            }
1621            _ => {}
1622        }
1623    }
1624
1625    // Streaming virtual fields: intercept before is_valid_for_result so they are
1626    // never skipped.  These fields resolve against the `$chunks` collected-list variable.
1627    if let Some(f) = &assertion.field {
1628        if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1629            if let Some(expr) =
1630                crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "php", "chunks")
1631            {
1632                let line = match assertion.assertion_type.as_str() {
1633                    "count_min" => {
1634                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1635                            format!(
1636                                "        $this->assertGreaterThanOrEqual({n}, count({expr}), 'expected >= {n} chunks');\n"
1637                            )
1638                        } else {
1639                            String::new()
1640                        }
1641                    }
1642                    "count_equals" => {
1643                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1644                            format!("        $this->assertCount({n}, {expr});\n")
1645                        } else {
1646                            String::new()
1647                        }
1648                    }
1649                    "equals" => {
1650                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1651                            let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1652                            format!("        $this->assertEquals('{escaped}', {expr});\n")
1653                        } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1654                            format!("        $this->assertEquals({n}, {expr});\n")
1655                        } else {
1656                            String::new()
1657                        }
1658                    }
1659                    "not_empty" => format!("        $this->assertNotEmpty({expr});\n"),
1660                    "is_empty" => format!("        $this->assertEmpty({expr});\n"),
1661                    "is_true" => format!("        $this->assertTrue({expr});\n"),
1662                    "is_false" => format!("        $this->assertFalse({expr});\n"),
1663                    "greater_than" => {
1664                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1665                            format!("        $this->assertGreaterThan({n}, {expr});\n")
1666                        } else {
1667                            String::new()
1668                        }
1669                    }
1670                    "greater_than_or_equal" => {
1671                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1672                            format!("        $this->assertGreaterThanOrEqual({n}, {expr});\n")
1673                        } else {
1674                            String::new()
1675                        }
1676                    }
1677                    "contains" => {
1678                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1679                            let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1680                            format!("        $this->assertStringContainsString('{escaped}', {expr});\n")
1681                        } else {
1682                            String::new()
1683                        }
1684                    }
1685                    _ => format!(
1686                        "        // streaming field '{f}': assertion type '{}' not rendered\n",
1687                        assertion.assertion_type
1688                    ),
1689                };
1690                if !line.is_empty() {
1691                    out.push_str(&line);
1692                }
1693            }
1694            return;
1695        }
1696    }
1697
1698    // Skip assertions on fields that don't exist on the result type.
1699    if let Some(f) = &assertion.field {
1700        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1701            out.push_str(&crate::template_env::render(
1702                "php/synthetic_assertion.jinja",
1703                minijinja::context! {
1704                    assertion_kind => "skipped",
1705                    field_name => f,
1706                },
1707            ));
1708            return;
1709        }
1710    }
1711
1712    // When result_is_simple, skip assertions that reference non-content fields
1713    // (e.g., metadata, document, structure) since the binding returns a plain value.
1714    if result_is_simple {
1715        if let Some(f) = &assertion.field {
1716            let f_lower = f.to_lowercase();
1717            if !f.is_empty()
1718                && f_lower != "content"
1719                && (f_lower.starts_with("metadata")
1720                    || f_lower.starts_with("document")
1721                    || f_lower.starts_with("structure"))
1722            {
1723                out.push_str(&crate::template_env::render(
1724                    "php/synthetic_assertion.jinja",
1725                    minijinja::context! {
1726                        assertion_kind => "result_is_simple",
1727                        field_name => f,
1728                    },
1729                ));
1730                return;
1731            }
1732        }
1733    }
1734
1735    let field_expr = match &assertion.field {
1736        // When result_is_simple, the result is a scalar (bytes/string/etc.) — any
1737        // field access on it would fail. Treat all assertions as referring to the
1738        // result itself.
1739        _ if result_is_simple => format!("${result_var}"),
1740        Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
1741        _ => format!("${result_var}"),
1742    };
1743
1744    // Detect if this field is an array type
1745    // When there's no field, default to result_is_array (the result itself is the array)
1746    let field_is_array = assertion.field.as_ref().map_or(result_is_array, |f| {
1747        if f.is_empty() {
1748            result_is_array
1749        } else {
1750            field_resolver.is_array(f)
1751        }
1752    });
1753
1754    // For string equality, trim trailing whitespace to handle trailing newlines.
1755    // Only apply trim() when the expected value is a string — calling trim() on int/bool
1756    // throws TypeError in PHP 8.4+.
1757    let trimmed_field_expr_for = |expected: &serde_json::Value| -> String {
1758        if expected.is_string() {
1759            format!("trim({})", field_expr)
1760        } else {
1761            field_expr.clone()
1762        }
1763    };
1764
1765    // Prepare template context.
1766    let assertion_type = assertion.assertion_type.as_str();
1767    let has_php_val = assertion.value.is_some();
1768    // serde collapses `"value": null` to `None`, but `equals` against null is a real
1769    // assertion (e.g. `result.message.content == null`). Default to PHP `null` in that
1770    // case so the rendered code compiles instead of producing `assertEquals(, ...)`.
1771    let php_val = match assertion.value.as_ref() {
1772        Some(v) => json_to_php(v),
1773        None if assertion_type == "equals" => "null".to_string(),
1774        None => String::new(),
1775    };
1776    let trimmed_field_expr = trimmed_field_expr_for(assertion.value.as_ref().unwrap_or(&serde_json::Value::Null));
1777    let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1778    // values_php is consumed by `contains`, `contains_all`, and `not_contains` loops.
1779    // Fall back to wrapping the singular `value` so single-entry fixtures still emit one
1780    // assertion call per value instead of an empty loop.
1781    let values_php: Vec<String> = assertion
1782        .values
1783        .as_ref()
1784        .map(|vals| vals.iter().map(json_to_php).collect::<Vec<_>>())
1785        .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_php(v)]))
1786        .unwrap_or_default();
1787    let contains_any_checks: Vec<String> = assertion
1788        .values
1789        .as_ref()
1790        .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1791    let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1792
1793    // For method_result assertions.
1794    let call_expr = if let Some(method_name) = &assertion.method {
1795        build_php_method_call(result_var, method_name, assertion.args.as_ref())
1796    } else {
1797        String::new()
1798    };
1799    let check = assertion.check.as_deref().unwrap_or("is_true");
1800    let has_php_check_val = matches!(assertion.assertion_type.as_str(), "method_result") && assertion.value.is_some();
1801    let php_check_val = if matches!(assertion.assertion_type.as_str(), "method_result") {
1802        assertion.value.as_ref().map(json_to_php).unwrap_or_default()
1803    } else {
1804        String::new()
1805    };
1806    let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1807    let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1808    let bool_is_true = assertion.value.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
1809
1810    // Early returns for non-template-renderable assertions.
1811    if matches!(assertion_type, "not_error" | "error") {
1812        if assertion_type == "not_error" {
1813            // Already handled by the call succeeding without exception.
1814        }
1815        // "error" is handled at the test method level.
1816        return;
1817    }
1818
1819    let rendered = crate::template_env::render(
1820        "php/assertion.jinja",
1821        minijinja::context! {
1822            assertion_type => assertion_type,
1823            field_expr => field_expr,
1824            php_val => php_val,
1825            has_php_val => has_php_val,
1826            trimmed_field_expr => trimmed_field_expr,
1827            is_string_val => is_string_val,
1828            field_is_array => field_is_array,
1829            values_php => values_php,
1830            contains_any_checks => contains_any_checks,
1831            n => n,
1832            call_expr => call_expr,
1833            check => check,
1834            php_check_val => php_check_val,
1835            has_php_check_val => has_php_check_val,
1836            check_n => check_n,
1837            is_bool_val => is_bool_val,
1838            bool_is_true => bool_is_true,
1839        },
1840    );
1841    let _ = write!(out, "        {}", rendered);
1842}
1843
1844/// Build a PHP call expression for a `method_result` assertion.
1845///
1846/// Uses generic instance method dispatch: `$result_var->method_name(args...)`.
1847/// Args from the fixture JSON object are emitted as positional PHP arguments in
1848/// insertion order, using best-effort type conversion (strings → PHP string literals,
1849/// numbers and booleans → verbatim literals).
1850fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1851    let extra_args = if let Some(args_val) = args {
1852        args_val
1853            .as_object()
1854            .map(|obj| {
1855                obj.values()
1856                    .map(|v| match v {
1857                        serde_json::Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1858                        serde_json::Value::Bool(true) => "true".to_string(),
1859                        serde_json::Value::Bool(false) => "false".to_string(),
1860                        serde_json::Value::Number(n) => n.to_string(),
1861                        serde_json::Value::Null => "null".to_string(),
1862                        other => format!("\"{}\"", other.to_string().replace('\\', "\\\\").replace('"', "\\\"")),
1863                    })
1864                    .collect::<Vec<_>>()
1865                    .join(", ")
1866            })
1867            .unwrap_or_default()
1868    } else {
1869        String::new()
1870    };
1871
1872    if extra_args.is_empty() {
1873        format!("${result_var}->{method_name}()")
1874    } else {
1875        format!("${result_var}->{method_name}({extra_args})")
1876    }
1877}
1878
1879/// Filters out empty string enum values from JSON objects before rendering.
1880/// When a field has an empty string value, it's treated as a missing/null enum field
1881/// and should not be included in the PHP array.
1882fn filter_empty_enum_strings(value: &serde_json::Value) -> serde_json::Value {
1883    match value {
1884        serde_json::Value::Object(map) => {
1885            let filtered: serde_json::Map<String, serde_json::Value> = map
1886                .iter()
1887                .filter_map(|(k, v)| {
1888                    // Skip empty string values (typically represent missing enum variants)
1889                    if let serde_json::Value::String(s) = v {
1890                        if s.is_empty() {
1891                            return None;
1892                        }
1893                    }
1894                    // Recursively filter nested objects and arrays
1895                    Some((k.clone(), filter_empty_enum_strings(v)))
1896                })
1897                .collect();
1898            serde_json::Value::Object(filtered)
1899        }
1900        serde_json::Value::Array(arr) => {
1901            let filtered: Vec<serde_json::Value> = arr.iter().map(filter_empty_enum_strings).collect();
1902            serde_json::Value::Array(filtered)
1903        }
1904        other => other.clone(),
1905    }
1906}
1907
1908/// Convert a `serde_json::Value` to a PHP literal string.
1909fn json_to_php(value: &serde_json::Value) -> String {
1910    match value {
1911        serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1912        serde_json::Value::Bool(true) => "true".to_string(),
1913        serde_json::Value::Bool(false) => "false".to_string(),
1914        serde_json::Value::Number(n) => n.to_string(),
1915        serde_json::Value::Null => "null".to_string(),
1916        serde_json::Value::Array(arr) => {
1917            let items: Vec<String> = arr.iter().map(json_to_php).collect();
1918            format!("[{}]", items.join(", "))
1919        }
1920        serde_json::Value::Object(map) => {
1921            let items: Vec<String> = map
1922                .iter()
1923                .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1924                .collect();
1925            format!("[{}]", items.join(", "))
1926        }
1927    }
1928}
1929
1930/// Like `json_to_php` but recursively converts all object keys to lowerCamelCase.
1931/// Used when generating PHP option arrays passed to `from_json()` — the PHP binding
1932/// structs use `#[serde(rename_all = "camelCase")]` so snake_case fixture keys
1933/// (e.g. `remove_forms`) must become `removeForms` in the generated test code.
1934fn json_to_php_camel_keys(value: &serde_json::Value) -> String {
1935    match value {
1936        serde_json::Value::Object(map) => {
1937            let items: Vec<String> = map
1938                .iter()
1939                .map(|(k, v)| {
1940                    let camel_key = k.to_lower_camel_case();
1941                    format!("\"{}\" => {}", escape_php(&camel_key), json_to_php_camel_keys(v))
1942                })
1943                .collect();
1944            format!("[{}]", items.join(", "))
1945        }
1946        serde_json::Value::Array(arr) => {
1947            let items: Vec<String> = arr.iter().map(json_to_php_camel_keys).collect();
1948            format!("[{}]", items.join(", "))
1949        }
1950        _ => json_to_php(value),
1951    }
1952}
1953
1954// ---------------------------------------------------------------------------
1955// Visitor generation
1956// ---------------------------------------------------------------------------
1957
1958/// Build a PHP visitor object and add setup lines. The visitor is assigned to $visitor variable.
1959fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1960    setup_lines.push("$visitor = new class {".to_string());
1961    for (method_name, action) in &visitor_spec.callbacks {
1962        emit_php_visitor_method(setup_lines, method_name, action);
1963    }
1964    setup_lines.push("};".to_string());
1965}
1966
1967/// Emit a PHP visitor method for a callback action.
1968fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1969    let params = match method_name {
1970        "visit_link" => "$ctx, $href, $text, $title",
1971        "visit_image" => "$ctx, $src, $alt, $title",
1972        "visit_heading" => "$ctx, $level, $text, $id",
1973        "visit_code_block" => "$ctx, $lang, $code",
1974        "visit_code_inline"
1975        | "visit_strong"
1976        | "visit_emphasis"
1977        | "visit_strikethrough"
1978        | "visit_underline"
1979        | "visit_subscript"
1980        | "visit_superscript"
1981        | "visit_mark"
1982        | "visit_button"
1983        | "visit_summary"
1984        | "visit_figcaption"
1985        | "visit_definition_term"
1986        | "visit_definition_description" => "$ctx, $text",
1987        "visit_text" => "$ctx, $text",
1988        "visit_list_item" => "$ctx, $ordered, $marker, $text",
1989        "visit_blockquote" => "$ctx, $content, $depth",
1990        "visit_table_row" => "$ctx, $cells, $isHeader",
1991        "visit_custom_element" => "$ctx, $tagName, $html",
1992        "visit_form" => "$ctx, $actionUrl, $method",
1993        "visit_input" => "$ctx, $input_type, $name, $value",
1994        "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1995        "visit_details" => "$ctx, $isOpen",
1996        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1997        "visit_list_start" => "$ctx, $ordered",
1998        "visit_list_end" => "$ctx, $ordered, $output",
1999        _ => "$ctx",
2000    };
2001
2002    let (action_type, action_value, return_form) = match action {
2003        CallbackAction::Skip => ("skip", String::new(), "dict"),
2004        CallbackAction::Continue => ("continue", String::new(), "dict"),
2005        CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2006        CallbackAction::Custom { output } => ("custom", escape_php(output), "dict"),
2007        CallbackAction::CustomTemplate { template, return_form } => {
2008            let form = match return_form {
2009                TemplateReturnForm::Dict => "dict",
2010                TemplateReturnForm::BareString => "bare_string",
2011            };
2012            ("custom_template", escape_php(template), form)
2013        }
2014    };
2015
2016    let rendered = crate::template_env::render(
2017        "php/visitor_method.jinja",
2018        minijinja::context! {
2019            method_name => method_name,
2020            params => params,
2021            action_type => action_type,
2022            action_value => action_value,
2023            return_form => return_form,
2024        },
2025    );
2026    for line in rendered.lines() {
2027        setup_lines.push(line.to_string());
2028    }
2029}
2030
2031/// Returns true if the type name is a PHP reserved/primitive type that cannot be imported.
2032fn is_php_reserved_type(name: &str) -> bool {
2033    matches!(
2034        name.to_ascii_lowercase().as_str(),
2035        "string"
2036            | "int"
2037            | "integer"
2038            | "float"
2039            | "double"
2040            | "bool"
2041            | "boolean"
2042            | "array"
2043            | "object"
2044            | "null"
2045            | "void"
2046            | "callable"
2047            | "iterable"
2048            | "never"
2049            | "self"
2050            | "parent"
2051            | "static"
2052            | "true"
2053            | "false"
2054            | "mixed"
2055    )
2056}