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