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, HttpExpectedResponse, HttpFixture, HttpRequest,
12};
13use alef_core::backend::GeneratedFile;
14use alef_core::config::AlefConfig;
15use alef_core::hash::{self, CommentStyle};
16use alef_core::template_versions as tv;
17use anyhow::Result;
18use heck::{ToSnakeCase, ToUpperCamelCase};
19use std::collections::HashMap;
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24
25/// PHP e2e code generator.
26pub struct PhpCodegen;
27
28impl E2eCodegen for PhpCodegen {
29    fn generate(
30        &self,
31        groups: &[FixtureGroup],
32        e2e_config: &E2eConfig,
33        alef_config: &AlefConfig,
34    ) -> Result<Vec<GeneratedFile>> {
35        let lang = self.language_name();
36        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38        let mut files = Vec::new();
39
40        // Resolve top-level call config to derive class/namespace/factory — these are
41        // shared across all categories. Per-fixture call routing (function name, args)
42        // is resolved inside render_test_method via e2e_config.resolve_call().
43        let call = &e2e_config.call;
44        let overrides = call.overrides.get(lang);
45        let extension_name = alef_config.php_extension_name();
46        let class_name = overrides
47            .and_then(|o| o.class.as_ref())
48            .cloned()
49            .unwrap_or_else(|| extension_name.to_upper_camel_case());
50        let namespace = overrides.and_then(|o| o.module.as_ref()).cloned().unwrap_or_else(|| {
51            if extension_name.contains('_') {
52                extension_name
53                    .split('_')
54                    .map(|p| p.to_upper_camel_case())
55                    .collect::<Vec<_>>()
56                    .join("\\")
57            } else {
58                extension_name.to_upper_camel_case()
59            }
60        });
61        let empty_enum_fields = HashMap::new();
62        let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
63        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
64        let php_client_factory = overrides.and_then(|o| o.php_client_factory.as_deref());
65        let options_via = overrides.and_then(|o| o.options_via.as_deref()).unwrap_or("array");
66
67        // Resolve package config.
68        let php_pkg = e2e_config.resolve_package("php");
69        let pkg_name = php_pkg
70            .as_ref()
71            .and_then(|p| p.name.as_ref())
72            .cloned()
73            .unwrap_or_else(|| {
74                // Derive `<org>/<module>` from the configured repository URL —
75                // alef is vendor-neutral, so we don't fall back to a fixed org.
76                let org = alef_config
77                    .try_github_repo()
78                    .ok()
79                    .as_deref()
80                    .and_then(alef_core::config::derive_repo_org)
81                    .unwrap_or_else(|| alef_config.crate_config.name.clone());
82                format!("{org}/{}", call.module.replace('_', "-"))
83            });
84        let pkg_path = php_pkg
85            .as_ref()
86            .and_then(|p| p.path.as_ref())
87            .cloned()
88            .unwrap_or_else(|| "../../packages/php".to_string());
89        let pkg_version = php_pkg
90            .as_ref()
91            .and_then(|p| p.version.as_ref())
92            .cloned()
93            .unwrap_or_else(|| "0.1.0".to_string());
94
95        // Derive the e2e composer project metadata from the consumer-binding
96        // pkg_name (`<vendor>/<crate>`) and the configured PHP autoload
97        // namespace — alef is vendor-neutral, so we don't fall back to a
98        // fixed "kreuzberg" string.
99        let e2e_vendor = pkg_name.split('/').next().unwrap_or(&pkg_name).to_string();
100        let e2e_pkg_name = format!("{e2e_vendor}/e2e-php");
101        // PSR-4 autoload keys appear inside a JSON document, so each PHP
102        // namespace separator must be JSON-escaped (`\` → `\\`). The trailing
103        // pair represents the PHP-mandated trailing `\` (which itself escapes
104        // to `\\` in JSON).
105        let php_namespace_escaped = alef_config.php_autoload_namespace().replace('\\', "\\\\");
106        let e2e_autoload_ns = format!("{php_namespace_escaped}\\\\E2e\\\\");
107
108        // Generate composer.json.
109        files.push(GeneratedFile {
110            path: output_base.join("composer.json"),
111            content: render_composer_json(
112                &e2e_pkg_name,
113                &e2e_autoload_ns,
114                &pkg_name,
115                &pkg_path,
116                &pkg_version,
117                e2e_config.dep_mode,
118            ),
119            generated_header: false,
120        });
121
122        // Generate phpunit.xml.
123        files.push(GeneratedFile {
124            path: output_base.join("phpunit.xml"),
125            content: render_phpunit_xml(),
126            generated_header: false,
127        });
128
129        // Check if any fixture is an HTTP test (needs mock server bootstrap).
130        let has_http_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| f.is_http_test());
131
132        // Generate bootstrap.php that loads both autoloaders and optionally starts the mock server.
133        files.push(GeneratedFile {
134            path: output_base.join("bootstrap.php"),
135            content: render_bootstrap(&pkg_path, has_http_fixtures),
136            generated_header: true,
137        });
138
139        // Generate test files per category.
140        let tests_base = output_base.join("tests");
141        let field_resolver = FieldResolver::new(
142            &e2e_config.fields,
143            &e2e_config.fields_optional,
144            &e2e_config.result_fields,
145            &e2e_config.fields_array,
146        );
147
148        for group in groups {
149            let active: Vec<&Fixture> = group
150                .fixtures
151                .iter()
152                .filter(|f| f.skip.as_ref().is_none_or(|s| !s.should_skip(lang)))
153                .collect();
154
155            if active.is_empty() {
156                continue;
157            }
158
159            let test_class = format!("{}Test", sanitize_filename(&group.category).to_upper_camel_case());
160            let filename = format!("{test_class}.php");
161            let content = render_test_file(
162                &group.category,
163                &active,
164                e2e_config,
165                lang,
166                &namespace,
167                &class_name,
168                &test_class,
169                &field_resolver,
170                enum_fields,
171                result_is_simple,
172                php_client_factory,
173                options_via,
174            );
175            files.push(GeneratedFile {
176                path: tests_base.join(filename),
177                content,
178                generated_header: true,
179            });
180        }
181
182        Ok(files)
183    }
184
185    fn language_name(&self) -> &'static str {
186        "php"
187    }
188}
189
190// ---------------------------------------------------------------------------
191// Rendering
192// ---------------------------------------------------------------------------
193
194fn render_composer_json(
195    e2e_pkg_name: &str,
196    e2e_autoload_ns: &str,
197    pkg_name: &str,
198    _pkg_path: &str,
199    pkg_version: &str,
200    dep_mode: crate::config::DependencyMode,
201) -> String {
202    let require_section = match dep_mode {
203        crate::config::DependencyMode::Registry => {
204            format!(
205                r#"  "require": {{
206    "{pkg_name}": "{pkg_version}"
207  }},
208  "require-dev": {{
209    "phpunit/phpunit": "{phpunit}",
210    "guzzlehttp/guzzle": "{guzzle}"
211  }},"#,
212                phpunit = tv::packagist::PHPUNIT,
213                guzzle = tv::packagist::GUZZLE,
214            )
215        }
216        crate::config::DependencyMode::Local => format!(
217            r#"  "require-dev": {{
218    "phpunit/phpunit": "{phpunit}",
219    "guzzlehttp/guzzle": "{guzzle}"
220  }},"#,
221            phpunit = tv::packagist::PHPUNIT,
222            guzzle = tv::packagist::GUZZLE,
223        ),
224    };
225
226    format!(
227        r#"{{
228  "name": "{e2e_pkg_name}",
229  "description": "E2e tests for PHP bindings",
230  "type": "project",
231{require_section}
232  "autoload-dev": {{
233    "psr-4": {{
234      "{e2e_autoload_ns}": "tests/"
235    }}
236  }}
237}}
238"#
239    )
240}
241
242fn render_phpunit_xml() -> String {
243    r#"<?xml version="1.0" encoding="UTF-8"?>
244<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
245         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/13.1/phpunit.xsd"
246         bootstrap="bootstrap.php"
247         colors="true"
248         failOnRisky="true"
249         failOnWarning="true">
250    <testsuites>
251        <testsuite name="e2e">
252            <directory>tests</directory>
253        </testsuite>
254    </testsuites>
255</phpunit>
256"#
257    .to_string()
258}
259
260fn render_bootstrap(pkg_path: &str, has_http_fixtures: bool) -> String {
261    let header = hash::header(CommentStyle::DoubleSlash);
262    let mock_server_block = if has_http_fixtures {
263        r#"
264// Spawn the mock HTTP server binary for HTTP fixture tests.
265$mockServerBin = __DIR__ . '/../rust/target/release/mock-server';
266$fixturesDir = __DIR__ . '/../../fixtures';
267if (file_exists($mockServerBin)) {
268    $descriptors = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => STDERR];
269    $proc = proc_open([$mockServerBin, $fixturesDir], $descriptors, $pipes);
270    if (is_resource($proc)) {
271        $line = fgets($pipes[1]);
272        if ($line !== false && str_starts_with($line, 'MOCK_SERVER_URL=')) {
273            putenv(trim($line));
274            $_ENV['MOCK_SERVER_URL'] = trim(substr(trim($line), strlen('MOCK_SERVER_URL=')));
275        }
276        // Drain stdout in background thread is not possible in PHP; keep pipe open.
277        register_shutdown_function(static function () use ($proc, $pipes): void {
278            fclose($pipes[0]);
279            proc_close($proc);
280        });
281    }
282}
283"#
284    } else {
285        ""
286    };
287    format!(
288        r#"<?php
289{header}
290declare(strict_types=1);
291
292// Load the e2e project autoloader (PHPUnit, test helpers).
293require_once __DIR__ . '/vendor/autoload.php';
294
295// Load the PHP binding package classes via its Composer autoloader.
296// The package's autoloader is separate from the e2e project's autoloader
297// since the php-ext type prevents direct composer path dependency.
298$pkgAutoloader = __DIR__ . '/{pkg_path}/vendor/autoload.php';
299if (file_exists($pkgAutoloader)) {{
300    require_once $pkgAutoloader;
301}}{mock_server_block}
302"#
303    )
304}
305
306#[allow(clippy::too_many_arguments)]
307fn render_test_file(
308    category: &str,
309    fixtures: &[&Fixture],
310    e2e_config: &E2eConfig,
311    lang: &str,
312    namespace: &str,
313    class_name: &str,
314    test_class: &str,
315    field_resolver: &FieldResolver,
316    enum_fields: &HashMap<String, String>,
317    result_is_simple: bool,
318    php_client_factory: Option<&str>,
319    options_via: &str,
320) -> String {
321    let mut out = String::new();
322    let _ = writeln!(out, "<?php");
323    out.push_str(&hash::header(CommentStyle::DoubleSlash));
324    let _ = writeln!(out);
325    let _ = writeln!(out, "declare(strict_types=1);");
326    let _ = writeln!(out);
327    let _ = writeln!(out, "namespace Kreuzberg\\E2e;");
328    let _ = writeln!(out);
329
330    // Determine if any handle arg has a non-null config (needs CrawlConfig import).
331    let needs_crawl_config_import = fixtures.iter().any(|f| {
332        let call = e2e_config.resolve_call(f.call.as_deref());
333        call.args.iter().filter(|a| a.arg_type == "handle").any(|a| {
334            let v = f.input.get(&a.field).unwrap_or(&serde_json::Value::Null);
335            !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
336        })
337    });
338
339    // Determine if any fixture is an HTTP test (needs GuzzleHttp).
340    let has_http_tests = fixtures.iter().any(|f| f.is_http_test());
341
342    let _ = writeln!(out, "use PHPUnit\\Framework\\TestCase;");
343    let _ = writeln!(out, "use {namespace}\\{class_name};");
344    if needs_crawl_config_import {
345        let _ = writeln!(out, "use {namespace}\\CrawlConfig;");
346    }
347    if has_http_tests {
348        let _ = writeln!(out, "use GuzzleHttp\\Client;");
349    }
350    let _ = writeln!(out);
351    let _ = writeln!(out, "/** E2e tests for category: {category}. */");
352    let _ = writeln!(out, "final class {test_class} extends TestCase");
353    let _ = writeln!(out, "{{");
354
355    // Emit a shared HTTP client property when there are HTTP tests.
356    if has_http_tests {
357        let _ = writeln!(out, "    private Client $httpClient;");
358        let _ = writeln!(out);
359        let _ = writeln!(out, "    protected function setUp(): void");
360        let _ = writeln!(out, "    {{");
361        let _ = writeln!(out, "        parent::setUp();");
362        let _ = writeln!(
363            out,
364            "        $baseUrl = (string)(getenv('MOCK_SERVER_URL') ?: 'http://localhost:8080');"
365        );
366        let _ = writeln!(
367            out,
368            "        $this->httpClient = new Client(['base_uri' => $baseUrl, 'http_errors' => false, 'decode_content' => false]);"
369        );
370        let _ = writeln!(out, "    }}");
371        let _ = writeln!(out);
372    }
373
374    for (i, fixture) in fixtures.iter().enumerate() {
375        if fixture.is_http_test() {
376            render_http_test_method(&mut out, fixture, fixture.http.as_ref().unwrap());
377        } else {
378            render_test_method(
379                &mut out,
380                fixture,
381                e2e_config,
382                lang,
383                namespace,
384                class_name,
385                field_resolver,
386                enum_fields,
387                result_is_simple,
388                php_client_factory,
389                options_via,
390            );
391        }
392        if i + 1 < fixtures.len() {
393            let _ = writeln!(out);
394        }
395    }
396
397    let _ = writeln!(out, "}}");
398    out
399}
400
401// ---------------------------------------------------------------------------
402// HTTP test rendering
403// ---------------------------------------------------------------------------
404
405/// Render a PHPUnit test method for an HTTP server test fixture.
406fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
407    let method_name = sanitize_filename(&fixture.id);
408    let description = &fixture.description;
409    let fixture_id = &fixture.id;
410
411    // Determine if body assertions will be generated (so we know whether to
412    // call json_decode — skipping it avoids JsonException on empty/non-JSON bodies.
413    // A body value of "" (empty string) means the response has no body — skip decode.
414    let has_explicit_body =
415        matches!(&http.expected_response.body, Some(v) if !(v.is_null() || v.is_string() && v.as_str() == Some("")));
416    let needs_json_body = has_explicit_body || http.expected_response.body_partial.is_some();
417    // validation_errors requires json_decode but should not throw when body is empty
418    let _needs_body_for_validation = http.expected_response.validation_errors.is_some() && !has_explicit_body;
419
420    let _ = writeln!(out, "    /** {description} */");
421    let _ = writeln!(out, "    public function test_{method_name}(): void");
422    let _ = writeln!(out, "    {{");
423
424    // Build request targeting the mock server's /fixtures/<id> endpoint.
425    render_php_http_request(out, &http.request, fixture_id, needs_json_body);
426
427    // Assert status code.
428    let status = http.expected_response.status_code;
429    let _ = writeln!(
430        out,
431        "        $this->assertEquals({status}, $response->getStatusCode());"
432    );
433
434    // Assert response body.
435    render_php_body_assertions(out, &http.expected_response, needs_json_body);
436
437    // Assert response headers.
438    render_php_header_assertions(out, &http.expected_response);
439
440    let _ = writeln!(out, "    }}");
441}
442
443/// Emit Guzzle request lines inside a PHPUnit test method.
444/// `needs_json_body` controls whether a `$body = json_decode(...)` line is emitted.
445/// Skip it for responses with no body (204, 304, HEAD, etc.) to avoid JsonException.
446fn render_php_http_request(out: &mut String, req: &HttpRequest, fixture_id: &str, needs_json_body: bool) {
447    let method = req.method.to_uppercase();
448
449    // Build options array.
450    let mut opts: Vec<String> = Vec::new();
451
452    if let Some(body) = &req.body {
453        let php_body = json_to_php(body);
454        opts.push(format!("'json' => {php_body}"));
455    }
456
457    if !req.headers.is_empty() {
458        let header_pairs: Vec<String> = req
459            .headers
460            .iter()
461            .map(|(k, v)| format!("\"{}\" => \"{}\"", escape_php(k), escape_php(v)))
462            .collect();
463        opts.push(format!("'headers' => [{}]", header_pairs.join(", ")));
464    }
465
466    if !req.cookies.is_empty() {
467        let cookie_str = req
468            .cookies
469            .iter()
470            .map(|(k, v)| format!("{}={}", k, v))
471            .collect::<Vec<_>>()
472            .join("; ");
473        opts.push(format!("'headers' => ['Cookie' => \"{}\"]", escape_php(&cookie_str)));
474    }
475
476    if !req.query_params.is_empty() {
477        let pairs: Vec<String> = req
478            .query_params
479            .iter()
480            .map(|(k, v)| {
481                let val_str = match v {
482                    serde_json::Value::String(s) => s.clone(),
483                    other => other.to_string(),
484                };
485                format!("\"{}\" => \"{}\"", escape_php(k), escape_php(&val_str))
486            })
487            .collect();
488        opts.push(format!("'query' => [{}]", pairs.join(", ")));
489    }
490
491    // Use the mock server's /fixtures/<id> endpoint.
492    let path_lit = format!("\"/fixtures/{}\"", escape_php(fixture_id));
493    if opts.is_empty() {
494        let _ = writeln!(
495            out,
496            "        $response = $this->httpClient->request('{method}', {path_lit});"
497        );
498    } else {
499        let _ = writeln!(
500            out,
501            "        $response = $this->httpClient->request('{method}', {path_lit}, ["
502        );
503        for opt in &opts {
504            let _ = writeln!(out, "            {opt},");
505        }
506        let _ = writeln!(out, "        ]);");
507    }
508
509    // Decode JSON body for assertions only when body assertions are expected.
510    // Omitting json_decode for empty-body responses (204, 304, HEAD, etc.)
511    // prevents JsonException on non-JSON or empty response bodies.
512    if needs_json_body {
513        let _ = writeln!(
514            out,
515            "        $body = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);"
516        );
517    }
518}
519
520/// Emit body assertions for an HTTP expected response.
521/// `body_was_decoded` indicates whether `$body` is already in scope from a json_decode call.
522fn render_php_body_assertions(out: &mut String, expected: &HttpExpectedResponse, body_was_decoded: bool) {
523    if let Some(body) = &expected.body {
524        // Skip assertion when body is the empty-string sentinel (means no body expected).
525        if !(body.is_string() && body.as_str() == Some("")) {
526            let php_val = json_to_php(body);
527            let _ = writeln!(out, "        $this->assertEquals({php_val}, $body);");
528        }
529    }
530    if let Some(partial) = &expected.body_partial {
531        if let Some(obj) = partial.as_object() {
532            for (key, val) in obj {
533                let php_key = format!("\"{}\"", escape_php(key));
534                let php_val = json_to_php(val);
535                let _ = writeln!(out, "        $this->assertEquals({php_val}, $body[{php_key}]);");
536            }
537        }
538    }
539    if let Some(errors) = &expected.validation_errors {
540        // Ensure $body is available even when it wasn't json_decoded earlier.
541        if !body_was_decoded {
542            let _ = writeln!(out, "        $body = json_decode((string) $response->getBody(), true);");
543        }
544        for err in errors {
545            let msg_lit = format!("\"{}\"", escape_php(&err.msg));
546            let _ = writeln!(
547                out,
548                "        $this->assertStringContainsString({msg_lit}, json_encode($body));"
549            );
550        }
551    }
552}
553
554/// Emit header assertions for an HTTP expected response.
555///
556/// Special tokens:
557/// - `"<<present>>"` — assert the header exists
558/// - `"<<absent>>"` — assert the header is absent
559/// - `"<<uuid>>"` — assert the header matches a UUID regex
560fn render_php_header_assertions(out: &mut String, expected: &HttpExpectedResponse) {
561    for (name, value) in &expected.headers {
562        let header_key = name.to_lowercase();
563        let header_key_lit = format!("\"{}\"", escape_php(&header_key));
564        match value.as_str() {
565            "<<present>>" => {
566                let _ = writeln!(
567                    out,
568                    "        $this->assertTrue($response->hasHeader({header_key_lit}));"
569                );
570            }
571            "<<absent>>" => {
572                let _ = writeln!(
573                    out,
574                    "        $this->assertFalse($response->hasHeader({header_key_lit}));"
575                );
576            }
577            "<<uuid>>" => {
578                let _ = writeln!(
579                    out,
580                    "        $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}));"
581                );
582            }
583            literal => {
584                let val_lit = format!("\"{}\"", escape_php(literal));
585                let _ = writeln!(
586                    out,
587                    "        $this->assertEquals({val_lit}, $response->getHeaderLine({header_key_lit}));"
588                );
589            }
590        }
591    }
592}
593
594// ---------------------------------------------------------------------------
595// Function-call test rendering
596// ---------------------------------------------------------------------------
597
598#[allow(clippy::too_many_arguments)]
599fn render_test_method(
600    out: &mut String,
601    fixture: &Fixture,
602    e2e_config: &E2eConfig,
603    lang: &str,
604    namespace: &str,
605    class_name: &str,
606    field_resolver: &FieldResolver,
607    enum_fields: &HashMap<String, String>,
608    result_is_simple: bool,
609    php_client_factory: Option<&str>,
610    options_via: &str,
611) {
612    // Resolve per-fixture call config: supports named calls via fixture.call field.
613    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
614    let call_overrides = call_config.overrides.get(lang);
615    let mut function_name = call_overrides
616        .and_then(|o| o.function.as_ref())
617        .cloned()
618        .unwrap_or_else(|| call_config.function.clone());
619    // PHP ext-php-rs async methods have an _async suffix.
620    if call_config.r#async {
621        function_name = format!("{function_name}_async");
622    }
623    let result_var = &call_config.result_var;
624    let args = &call_config.args;
625
626    let method_name = sanitize_filename(&fixture.id);
627    let description = &fixture.description;
628    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
629
630    let (mut setup_lines, args_str) =
631        build_args_and_setup(&fixture.input, args, class_name, enum_fields, &fixture.id, options_via);
632
633    // Build visitor if present and add to setup
634    let mut visitor_arg = String::new();
635    if let Some(visitor_spec) = &fixture.visitor {
636        visitor_arg = build_php_visitor(&mut setup_lines, visitor_spec);
637    }
638
639    let final_args = if visitor_arg.is_empty() {
640        args_str
641    } else if args_str.is_empty() {
642        visitor_arg
643    } else {
644        format!("{args_str}, {visitor_arg}")
645    };
646
647    let call_expr = if php_client_factory.is_some() {
648        format!("$client->{function_name}({final_args})")
649    } else {
650        format!("{class_name}::{function_name}({final_args})")
651    };
652
653    let _ = writeln!(out, "    /** {description} */");
654    let _ = writeln!(out, "    public function test_{method_name}(): void");
655    let _ = writeln!(out, "    {{");
656
657    if let Some(factory) = php_client_factory {
658        let _ = writeln!(
659            out,
660            "        $client = \\{namespace}\\{class_name}::{factory}('test-key');"
661        );
662    }
663
664    for line in &setup_lines {
665        let _ = writeln!(out, "        {line}");
666    }
667
668    if expects_error {
669        let _ = writeln!(out, "        $this->expectException(\\Exception::class);");
670        let _ = writeln!(out, "        {call_expr};");
671        let _ = writeln!(out, "    }}");
672        return;
673    }
674
675    // Non-HTTP fixture with no assertions: generate a skipped placeholder so
676    // PHPUnit does not try to call a method that may not exist on the binding.
677    if fixture.assertions.is_empty() {
678        let _ = writeln!(
679            out,
680            "        $this->markTestSkipped('no assertions configured for this fixture in php e2e');"
681        );
682        let _ = writeln!(out, "    }}");
683        return;
684    }
685
686    // If no assertion will actually produce a PHPUnit assert call, mark the test
687    // as intentionally assertion-free so PHPUnit does not flag it as risky.
688    let has_usable = fixture.assertions.iter().any(|a| {
689        if a.assertion_type == "error" || a.assertion_type == "not_error" {
690            return false;
691        }
692        match &a.field {
693            Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
694            _ => true,
695        }
696    });
697    if !has_usable {
698        let _ = writeln!(out, "        $this->expectNotToPerformAssertions();");
699    }
700
701    let _ = writeln!(out, "        ${result_var} = {call_expr};");
702
703    for assertion in &fixture.assertions {
704        render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
705    }
706
707    let _ = writeln!(out, "    }}");
708}
709
710/// Build setup lines (e.g. handle creation) and the argument list for the function call.
711///
712/// `options_via` controls how `json_object` args are passed:
713/// - `"array"` (default): PHP array literal `["key" => value, ...]`
714/// - `"json"`: JSON string via `json_encode([...])` — use when the Rust method accepts `Option<String>`
715///
716/// Returns `(setup_lines, args_string)`.
717fn build_args_and_setup(
718    input: &serde_json::Value,
719    args: &[crate::config::ArgMapping],
720    class_name: &str,
721    enum_fields: &HashMap<String, String>,
722    fixture_id: &str,
723    options_via: &str,
724) -> (Vec<String>, String) {
725    if args.is_empty() {
726        // No args configuration: pass the whole input only if it's non-empty.
727        // Functions with no parameters (e.g. list_models) have empty input and get no args.
728        let is_empty_input = match input {
729            serde_json::Value::Null => true,
730            serde_json::Value::Object(m) => m.is_empty(),
731            _ => false,
732        };
733        if is_empty_input {
734            return (Vec::new(), String::new());
735        }
736        return (Vec::new(), json_to_php(input));
737    }
738
739    let mut setup_lines: Vec<String> = Vec::new();
740    let mut parts: Vec<String> = Vec::new();
741
742    for arg in args {
743        if arg.arg_type == "mock_url" {
744            setup_lines.push(format!(
745                "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
746                arg.name,
747            ));
748            parts.push(format!("${}", arg.name));
749            continue;
750        }
751
752        if arg.arg_type == "handle" {
753            // Generate a createEngine (or equivalent) call and pass the variable.
754            let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
755            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
756            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
757            if config_value.is_null()
758                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
759            {
760                setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
761            } else {
762                let name = &arg.name;
763                // Build a CrawlConfig object and set its fields via property assignment.
764                // The PHP binding accepts `?CrawlConfig $config` — there is no JSON string
765                // variant. Object and array config values are expressed as PHP array literals.
766                setup_lines.push(format!("${name}_config = CrawlConfig::default();"));
767                if let Some(obj) = config_value.as_object() {
768                    for (key, val) in obj {
769                        let php_val = json_to_php(val);
770                        setup_lines.push(format!("${name}_config->{key} = {php_val};"));
771                    }
772                }
773                setup_lines.push(format!(
774                    "${} = {class_name}::{constructor_name}(${name}_config);",
775                    arg.name,
776                ));
777            }
778            parts.push(format!("${}", arg.name));
779            continue;
780        }
781
782        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
783        let val = input.get(field);
784        match val {
785            None | Some(serde_json::Value::Null) if arg.optional => {
786                // Optional arg with no fixture value: skip entirely.
787                continue;
788            }
789            None | Some(serde_json::Value::Null) => {
790                // Required arg with no fixture value: pass a language-appropriate default.
791                let default_val = match arg.arg_type.as_str() {
792                    "string" => "\"\"".to_string(),
793                    "int" | "integer" => "0".to_string(),
794                    "float" | "number" => "0.0".to_string(),
795                    "bool" | "boolean" => "false".to_string(),
796                    "json_object" if options_via == "json" => "null".to_string(),
797                    _ => "null".to_string(),
798                };
799                parts.push(default_val);
800            }
801            Some(v) => {
802                if arg.arg_type == "json_object" && !v.is_null() {
803                    match options_via {
804                        "json" => {
805                            // Pass as JSON string via json_encode(); the Rust method accepts Option<String>.
806                            parts.push(format!("json_encode({})", json_to_php(v)));
807                            continue;
808                        }
809                        _ => {
810                            // Default: PHP array literal with snake_case keys.
811                            if let Some(obj) = v.as_object() {
812                                let items: Vec<String> = obj
813                                    .iter()
814                                    .map(|(k, vv)| {
815                                        let snake_key = k.to_snake_case();
816                                        let php_val = if enum_fields.contains_key(k) {
817                                            if let Some(s) = vv.as_str() {
818                                                let snake_val = s.to_snake_case();
819                                                format!("\"{}\"", escape_php(&snake_val))
820                                            } else {
821                                                json_to_php(vv)
822                                            }
823                                        } else {
824                                            json_to_php(vv)
825                                        };
826                                        format!("\"{}\" => {}", escape_php(&snake_key), php_val)
827                                    })
828                                    .collect();
829                                parts.push(format!("[{}]", items.join(", ")));
830                                continue;
831                            }
832                        }
833                    }
834                }
835                parts.push(json_to_php(v));
836            }
837        }
838    }
839
840    (setup_lines, parts.join(", "))
841}
842
843fn render_assertion(
844    out: &mut String,
845    assertion: &Assertion,
846    result_var: &str,
847    field_resolver: &FieldResolver,
848    result_is_simple: bool,
849) {
850    // Skip assertions on fields that don't exist on the result type.
851    if let Some(f) = &assertion.field {
852        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
853            let _ = writeln!(out, "        // skipped: field '{f}' not available on result type");
854            return;
855        }
856    }
857
858    // When result_is_simple, skip assertions that reference non-content fields
859    // (e.g., metadata, document, structure) since the binding returns a plain value.
860    if result_is_simple {
861        if let Some(f) = &assertion.field {
862            let f_lower = f.to_lowercase();
863            if !f.is_empty()
864                && f_lower != "content"
865                && (f_lower.starts_with("metadata")
866                    || f_lower.starts_with("document")
867                    || f_lower.starts_with("structure"))
868            {
869                let _ = writeln!(
870                    out,
871                    "        // skipped: result_is_simple, field '{f}' not on simple result type"
872                );
873                return;
874            }
875        }
876    }
877
878    let field_expr = if result_is_simple {
879        format!("${result_var}")
880    } else {
881        match &assertion.field {
882            Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
883            _ => format!("${result_var}"),
884        }
885    };
886
887    // For string equality, trim trailing whitespace to handle trailing newlines.
888    let trimmed_field_expr = if result_is_simple {
889        format!("trim(${result_var})")
890    } else {
891        field_expr.clone()
892    };
893
894    match assertion.assertion_type.as_str() {
895        "equals" => {
896            if let Some(expected) = &assertion.value {
897                let php_val = json_to_php(expected);
898                let _ = writeln!(out, "        $this->assertEquals({php_val}, {trimmed_field_expr});");
899            }
900        }
901        "contains" => {
902            if let Some(expected) = &assertion.value {
903                let php_val = json_to_php(expected);
904                let _ = writeln!(
905                    out,
906                    "        $this->assertStringContainsString({php_val}, {field_expr});"
907                );
908            }
909        }
910        "contains_all" => {
911            if let Some(values) = &assertion.values {
912                for val in values {
913                    let php_val = json_to_php(val);
914                    let _ = writeln!(
915                        out,
916                        "        $this->assertStringContainsString({php_val}, {field_expr});"
917                    );
918                }
919            }
920        }
921        "not_contains" => {
922            if let Some(expected) = &assertion.value {
923                let php_val = json_to_php(expected);
924                let _ = writeln!(
925                    out,
926                    "        $this->assertStringNotContainsString({php_val}, {field_expr});"
927                );
928            }
929        }
930        "not_empty" => {
931            let _ = writeln!(out, "        $this->assertNotEmpty({field_expr});");
932        }
933        "is_empty" => {
934            let _ = writeln!(out, "        $this->assertEmpty({trimmed_field_expr});");
935        }
936        "contains_any" => {
937            if let Some(values) = &assertion.values {
938                let _ = writeln!(out, "        $found = false;");
939                for val in values {
940                    let php_val = json_to_php(val);
941                    let _ = writeln!(
942                        out,
943                        "        if (str_contains({field_expr}, {php_val})) {{ $found = true; }}"
944                    );
945                }
946                let _ = writeln!(
947                    out,
948                    "        $this->assertTrue($found, 'expected to contain at least one of the specified values');"
949                );
950            }
951        }
952        "greater_than" => {
953            if let Some(val) = &assertion.value {
954                let php_val = json_to_php(val);
955                let _ = writeln!(out, "        $this->assertGreaterThan({php_val}, {field_expr});");
956            }
957        }
958        "less_than" => {
959            if let Some(val) = &assertion.value {
960                let php_val = json_to_php(val);
961                let _ = writeln!(out, "        $this->assertLessThan({php_val}, {field_expr});");
962            }
963        }
964        "greater_than_or_equal" => {
965            if let Some(val) = &assertion.value {
966                let php_val = json_to_php(val);
967                let _ = writeln!(out, "        $this->assertGreaterThanOrEqual({php_val}, {field_expr});");
968            }
969        }
970        "less_than_or_equal" => {
971            if let Some(val) = &assertion.value {
972                let php_val = json_to_php(val);
973                let _ = writeln!(out, "        $this->assertLessThanOrEqual({php_val}, {field_expr});");
974            }
975        }
976        "starts_with" => {
977            if let Some(expected) = &assertion.value {
978                let php_val = json_to_php(expected);
979                let _ = writeln!(out, "        $this->assertStringStartsWith({php_val}, {field_expr});");
980            }
981        }
982        "ends_with" => {
983            if let Some(expected) = &assertion.value {
984                let php_val = json_to_php(expected);
985                let _ = writeln!(out, "        $this->assertStringEndsWith({php_val}, {field_expr});");
986            }
987        }
988        "min_length" => {
989            if let Some(val) = &assertion.value {
990                if let Some(n) = val.as_u64() {
991                    let _ = writeln!(
992                        out,
993                        "        $this->assertGreaterThanOrEqual({n}, strlen({field_expr}));"
994                    );
995                }
996            }
997        }
998        "max_length" => {
999            if let Some(val) = &assertion.value {
1000                if let Some(n) = val.as_u64() {
1001                    let _ = writeln!(out, "        $this->assertLessThanOrEqual({n}, strlen({field_expr}));");
1002                }
1003            }
1004        }
1005        "count_min" => {
1006            if let Some(val) = &assertion.value {
1007                if let Some(n) = val.as_u64() {
1008                    let _ = writeln!(
1009                        out,
1010                        "        $this->assertGreaterThanOrEqual({n}, count({field_expr}));"
1011                    );
1012                }
1013            }
1014        }
1015        "count_equals" => {
1016            if let Some(val) = &assertion.value {
1017                if let Some(n) = val.as_u64() {
1018                    let _ = writeln!(out, "        $this->assertCount({n}, {field_expr});");
1019                }
1020            }
1021        }
1022        "is_true" => {
1023            let _ = writeln!(out, "        $this->assertTrue({field_expr});");
1024        }
1025        "is_false" => {
1026            let _ = writeln!(out, "        $this->assertFalse({field_expr});");
1027        }
1028        "method_result" => {
1029            if let Some(method_name) = &assertion.method {
1030                let call_expr = build_php_method_call(result_var, method_name, assertion.args.as_ref());
1031                let check = assertion.check.as_deref().unwrap_or("is_true");
1032                match check {
1033                    "equals" => {
1034                        if let Some(val) = &assertion.value {
1035                            if val.is_boolean() {
1036                                if val.as_bool() == Some(true) {
1037                                    let _ = writeln!(out, "        $this->assertTrue({call_expr});");
1038                                } else {
1039                                    let _ = writeln!(out, "        $this->assertFalse({call_expr});");
1040                                }
1041                            } else {
1042                                let expected = json_to_php(val);
1043                                let _ = writeln!(out, "        $this->assertEquals({expected}, {call_expr});");
1044                            }
1045                        }
1046                    }
1047                    "is_true" => {
1048                        let _ = writeln!(out, "        $this->assertTrue({call_expr});");
1049                    }
1050                    "is_false" => {
1051                        let _ = writeln!(out, "        $this->assertFalse({call_expr});");
1052                    }
1053                    "greater_than_or_equal" => {
1054                        if let Some(val) = &assertion.value {
1055                            let n = val.as_u64().unwrap_or(0);
1056                            let _ = writeln!(out, "        $this->assertGreaterThanOrEqual({n}, {call_expr});");
1057                        }
1058                    }
1059                    "count_min" => {
1060                        if let Some(val) = &assertion.value {
1061                            let n = val.as_u64().unwrap_or(0);
1062                            let _ = writeln!(out, "        $this->assertGreaterThanOrEqual({n}, count({call_expr}));");
1063                        }
1064                    }
1065                    "is_error" => {
1066                        let _ = writeln!(out, "        $this->expectException(\\Exception::class);");
1067                        let _ = writeln!(out, "        {call_expr};");
1068                    }
1069                    "contains" => {
1070                        if let Some(val) = &assertion.value {
1071                            let expected = json_to_php(val);
1072                            let _ = writeln!(
1073                                out,
1074                                "        $this->assertStringContainsString({expected}, {call_expr});"
1075                            );
1076                        }
1077                    }
1078                    other_check => {
1079                        panic!("PHP e2e generator: unsupported method_result check type: {other_check}");
1080                    }
1081                }
1082            } else {
1083                panic!("PHP e2e generator: method_result assertion missing 'method' field");
1084            }
1085        }
1086        "matches_regex" => {
1087            if let Some(expected) = &assertion.value {
1088                let php_val = json_to_php(expected);
1089                let _ = writeln!(
1090                    out,
1091                    "        $this->assertMatchesRegularExpression({php_val}, {field_expr});"
1092                );
1093            }
1094        }
1095        "not_error" => {
1096            // Already handled by the call succeeding without exception.
1097        }
1098        "error" => {
1099            // Handled at the test method level.
1100        }
1101        other => {
1102            panic!("PHP e2e generator: unsupported assertion type: {other}");
1103        }
1104    }
1105}
1106
1107/// Build a PHP call expression for a `method_result` assertion on a tree-sitter `Tree`.
1108///
1109/// Maps method names to the appropriate PHP static function calls on the
1110/// `TreeSitterLanguagePack` class (using the ext-php-rs snake_case method names).
1111fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1112    match method_name {
1113        "root_child_count" => {
1114            format!("count(TreeSitterLanguagePack::named_children_info(${result_var}))")
1115        }
1116        "root_node_type" => {
1117            format!("TreeSitterLanguagePack::root_node_info(${result_var})->kind")
1118        }
1119        "named_children_count" => {
1120            format!("count(TreeSitterLanguagePack::named_children_info(${result_var}))")
1121        }
1122        "has_error_nodes" => {
1123            format!("TreeSitterLanguagePack::tree_has_error_nodes(${result_var})")
1124        }
1125        "error_count" | "tree_error_count" => {
1126            format!("TreeSitterLanguagePack::tree_error_count(${result_var})")
1127        }
1128        "tree_to_sexp" => {
1129            format!("TreeSitterLanguagePack::tree_to_sexp(${result_var})")
1130        }
1131        "contains_node_type" => {
1132            let node_type = args
1133                .and_then(|a| a.get("node_type"))
1134                .and_then(|v| v.as_str())
1135                .unwrap_or("");
1136            format!("TreeSitterLanguagePack::tree_contains_node_type(${result_var}, \"{node_type}\")")
1137        }
1138        "find_nodes_by_type" => {
1139            let node_type = args
1140                .and_then(|a| a.get("node_type"))
1141                .and_then(|v| v.as_str())
1142                .unwrap_or("");
1143            format!("TreeSitterLanguagePack::find_nodes_by_type(${result_var}, \"{node_type}\")")
1144        }
1145        "run_query" => {
1146            let query_source = args
1147                .and_then(|a| a.get("query_source"))
1148                .and_then(|v| v.as_str())
1149                .unwrap_or("");
1150            let language = args
1151                .and_then(|a| a.get("language"))
1152                .and_then(|v| v.as_str())
1153                .unwrap_or("");
1154            format!("TreeSitterLanguagePack::run_query(${result_var}, \"{language}\", \"{query_source}\", $source)")
1155        }
1156        _ => {
1157            format!("${result_var}->{method_name}()")
1158        }
1159    }
1160}
1161
1162/// Convert a `serde_json::Value` to a PHP literal string.
1163fn json_to_php(value: &serde_json::Value) -> String {
1164    match value {
1165        serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1166        serde_json::Value::Bool(true) => "true".to_string(),
1167        serde_json::Value::Bool(false) => "false".to_string(),
1168        serde_json::Value::Number(n) => n.to_string(),
1169        serde_json::Value::Null => "null".to_string(),
1170        serde_json::Value::Array(arr) => {
1171            let items: Vec<String> = arr.iter().map(json_to_php).collect();
1172            format!("[{}]", items.join(", "))
1173        }
1174        serde_json::Value::Object(map) => {
1175            let items: Vec<String> = map
1176                .iter()
1177                .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1178                .collect();
1179            format!("[{}]", items.join(", "))
1180        }
1181    }
1182}
1183
1184// ---------------------------------------------------------------------------
1185// Visitor generation
1186// ---------------------------------------------------------------------------
1187
1188/// Build a PHP visitor object and add setup lines. Returns the visitor expression.
1189fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
1190    setup_lines.push("$visitor = new class {".to_string());
1191    for (method_name, action) in &visitor_spec.callbacks {
1192        emit_php_visitor_method(setup_lines, method_name, action);
1193    }
1194    setup_lines.push("};".to_string());
1195    "$visitor".to_string()
1196}
1197
1198/// Emit a PHP visitor method for a callback action.
1199fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1200    let snake_method = method_name;
1201    let params = match method_name {
1202        "visit_link" => "$ctx, $href, $text, $title",
1203        "visit_image" => "$ctx, $src, $alt, $title",
1204        "visit_heading" => "$ctx, $level, $text, $id",
1205        "visit_code_block" => "$ctx, $lang, $code",
1206        "visit_code_inline"
1207        | "visit_strong"
1208        | "visit_emphasis"
1209        | "visit_strikethrough"
1210        | "visit_underline"
1211        | "visit_subscript"
1212        | "visit_superscript"
1213        | "visit_mark"
1214        | "visit_button"
1215        | "visit_summary"
1216        | "visit_figcaption"
1217        | "visit_definition_term"
1218        | "visit_definition_description" => "$ctx, $text",
1219        "visit_text" => "$ctx, $text",
1220        "visit_list_item" => "$ctx, $ordered, $marker, $text",
1221        "visit_blockquote" => "$ctx, $content, $depth",
1222        "visit_table_row" => "$ctx, $cells, $isHeader",
1223        "visit_custom_element" => "$ctx, $tagName, $html",
1224        "visit_form" => "$ctx, $actionUrl, $method",
1225        "visit_input" => "$ctx, $inputType, $name, $value",
1226        "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1227        "visit_details" => "$ctx, $isOpen",
1228        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1229        "visit_list_start" => "$ctx, $ordered",
1230        "visit_list_end" => "$ctx, $ordered, $output",
1231        _ => "$ctx",
1232    };
1233
1234    setup_lines.push(format!("    public function {snake_method}({params}) {{"));
1235    match action {
1236        CallbackAction::Skip => {
1237            setup_lines.push("        return 'skip';".to_string());
1238        }
1239        CallbackAction::Continue => {
1240            setup_lines.push("        return 'continue';".to_string());
1241        }
1242        CallbackAction::PreserveHtml => {
1243            setup_lines.push("        return 'preserve_html';".to_string());
1244        }
1245        CallbackAction::Custom { output } => {
1246            let escaped = escape_php(output);
1247            setup_lines.push(format!("        return ['custom' => {escaped}];"));
1248        }
1249        CallbackAction::CustomTemplate { template } => {
1250            let escaped = escape_php(template);
1251            setup_lines.push(format!("        return ['custom' => {escaped}];"));
1252        }
1253    }
1254    setup_lines.push("    }".to_string());
1255}