1use 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
25pub 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 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 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 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 let e2e_vendor = pkg_name.split('/').next().unwrap_or(&pkg_name).to_string();
100 let e2e_pkg_name = format!("{e2e_vendor}/e2e-php");
101 let php_namespace_escaped = alef_config.php_autoload_namespace().replace('\\', "\\\\");
106 let e2e_autoload_ns = format!("{php_namespace_escaped}\\\\E2e\\\\");
107
108 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 files.push(GeneratedFile {
124 path: output_base.join("phpunit.xml"),
125 content: render_phpunit_xml(),
126 generated_header: false,
127 });
128
129 let has_http_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| f.is_http_test());
131
132 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 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
190fn 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 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 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 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]);"
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
401fn 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 let _ = writeln!(out, " /** {description} */");
412 let _ = writeln!(out, " public function test_{method_name}(): void");
413 let _ = writeln!(out, " {{");
414
415 render_php_http_request(out, &http.request, fixture_id);
417
418 let status = http.expected_response.status_code;
420 let _ = writeln!(
421 out,
422 " $this->assertEquals({status}, $response->getStatusCode());"
423 );
424
425 render_php_body_assertions(out, &http.expected_response);
427
428 render_php_header_assertions(out, &http.expected_response);
430
431 let _ = writeln!(out, " }}");
432}
433
434fn render_php_http_request(out: &mut String, req: &HttpRequest, fixture_id: &str) {
436 let method = req.method.to_uppercase();
437
438 let mut opts: Vec<String> = Vec::new();
440
441 if let Some(body) = &req.body {
442 let php_body = json_to_php(body);
443 opts.push(format!("'json' => {php_body}"));
444 }
445
446 if !req.headers.is_empty() {
447 let header_pairs: Vec<String> = req
448 .headers
449 .iter()
450 .map(|(k, v)| format!("\"{}\" => \"{}\"", escape_php(k), escape_php(v)))
451 .collect();
452 opts.push(format!("'headers' => [{}]", header_pairs.join(", ")));
453 }
454
455 if !req.cookies.is_empty() {
456 let cookie_str = req
457 .cookies
458 .iter()
459 .map(|(k, v)| format!("{}={}", k, v))
460 .collect::<Vec<_>>()
461 .join("; ");
462 opts.push(format!("'headers' => ['Cookie' => \"{}\"]", escape_php(&cookie_str)));
463 }
464
465 if !req.query_params.is_empty() {
466 let pairs: Vec<String> = req
467 .query_params
468 .iter()
469 .map(|(k, v)| {
470 let val_str = match v {
471 serde_json::Value::String(s) => s.clone(),
472 other => other.to_string(),
473 };
474 format!("\"{}\" => \"{}\"", escape_php(k), escape_php(&val_str))
475 })
476 .collect();
477 opts.push(format!("'query' => [{}]", pairs.join(", ")));
478 }
479
480 let path_lit = format!("\"/fixtures/{}\"", escape_php(fixture_id));
482 if opts.is_empty() {
483 let _ = writeln!(
484 out,
485 " $response = $this->httpClient->request('{method}', {path_lit});"
486 );
487 } else {
488 let _ = writeln!(
489 out,
490 " $response = $this->httpClient->request('{method}', {path_lit}, ["
491 );
492 for opt in &opts {
493 let _ = writeln!(out, " {opt},");
494 }
495 let _ = writeln!(out, " ]);");
496 }
497
498 let _ = writeln!(
500 out,
501 " $body = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);"
502 );
503}
504
505fn render_php_body_assertions(out: &mut String, expected: &HttpExpectedResponse) {
507 if let Some(body) = &expected.body {
508 let php_val = json_to_php(body);
509 let _ = writeln!(out, " $this->assertEquals({php_val}, $body);");
510 }
511 if let Some(partial) = &expected.body_partial {
512 if let Some(obj) = partial.as_object() {
513 for (key, val) in obj {
514 let php_key = format!("\"{}\"", escape_php(key));
515 let php_val = json_to_php(val);
516 let _ = writeln!(out, " $this->assertEquals({php_val}, $body[{php_key}]);");
517 }
518 }
519 }
520 if let Some(errors) = &expected.validation_errors {
521 for err in errors {
522 let msg_lit = format!("\"{}\"", escape_php(&err.msg));
523 let _ = writeln!(
524 out,
525 " $this->assertStringContainsString({msg_lit}, json_encode($body));"
526 );
527 }
528 }
529}
530
531fn render_php_header_assertions(out: &mut String, expected: &HttpExpectedResponse) {
538 for (name, value) in &expected.headers {
539 let header_key = name.to_lowercase();
540 let header_key_lit = format!("\"{}\"", escape_php(&header_key));
541 match value.as_str() {
542 "<<present>>" => {
543 let _ = writeln!(
544 out,
545 " $this->assertTrue($response->hasHeader({header_key_lit}));"
546 );
547 }
548 "<<absent>>" => {
549 let _ = writeln!(
550 out,
551 " $this->assertFalse($response->hasHeader({header_key_lit}));"
552 );
553 }
554 "<<uuid>>" => {
555 let _ = writeln!(
556 out,
557 " $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}));"
558 );
559 }
560 literal => {
561 let val_lit = format!("\"{}\"", escape_php(literal));
562 let _ = writeln!(
563 out,
564 " $this->assertEquals({val_lit}, $response->getHeaderLine({header_key_lit}));"
565 );
566 }
567 }
568 }
569}
570
571#[allow(clippy::too_many_arguments)]
576fn render_test_method(
577 out: &mut String,
578 fixture: &Fixture,
579 e2e_config: &E2eConfig,
580 lang: &str,
581 namespace: &str,
582 class_name: &str,
583 field_resolver: &FieldResolver,
584 enum_fields: &HashMap<String, String>,
585 result_is_simple: bool,
586 php_client_factory: Option<&str>,
587 options_via: &str,
588) {
589 let call_config = e2e_config.resolve_call(fixture.call.as_deref());
591 let call_overrides = call_config.overrides.get(lang);
592 let mut function_name = call_overrides
593 .and_then(|o| o.function.as_ref())
594 .cloned()
595 .unwrap_or_else(|| call_config.function.clone());
596 if call_config.r#async {
598 function_name = format!("{function_name}_async");
599 }
600 let result_var = &call_config.result_var;
601 let args = &call_config.args;
602
603 let method_name = sanitize_filename(&fixture.id);
604 let description = &fixture.description;
605 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
606
607 let (mut setup_lines, args_str) =
608 build_args_and_setup(&fixture.input, args, class_name, enum_fields, &fixture.id, options_via);
609
610 let mut visitor_arg = String::new();
612 if let Some(visitor_spec) = &fixture.visitor {
613 visitor_arg = build_php_visitor(&mut setup_lines, visitor_spec);
614 }
615
616 let final_args = if visitor_arg.is_empty() {
617 args_str
618 } else if args_str.is_empty() {
619 visitor_arg
620 } else {
621 format!("{args_str}, {visitor_arg}")
622 };
623
624 let call_expr = if php_client_factory.is_some() {
625 format!("$client->{function_name}({final_args})")
626 } else {
627 format!("{class_name}::{function_name}({final_args})")
628 };
629
630 let _ = writeln!(out, " /** {description} */");
631 let _ = writeln!(out, " public function test_{method_name}(): void");
632 let _ = writeln!(out, " {{");
633
634 if let Some(factory) = php_client_factory {
635 let _ = writeln!(
636 out,
637 " $client = \\{namespace}\\{class_name}::{factory}('test-key');"
638 );
639 }
640
641 for line in &setup_lines {
642 let _ = writeln!(out, " {line}");
643 }
644
645 if expects_error {
646 let _ = writeln!(out, " $this->expectException(\\Exception::class);");
647 let _ = writeln!(out, " {call_expr};");
648 let _ = writeln!(out, " }}");
649 return;
650 }
651
652 let has_usable = fixture.assertions.iter().any(|a| {
655 if a.assertion_type == "error" || a.assertion_type == "not_error" {
656 return false;
657 }
658 match &a.field {
659 Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
660 _ => true,
661 }
662 });
663 if !has_usable {
664 let _ = writeln!(out, " $this->expectNotToPerformAssertions();");
665 }
666
667 let _ = writeln!(out, " ${result_var} = {call_expr};");
668
669 for assertion in &fixture.assertions {
670 render_assertion(out, assertion, result_var, field_resolver, result_is_simple);
671 }
672
673 let _ = writeln!(out, " }}");
674}
675
676fn build_args_and_setup(
684 input: &serde_json::Value,
685 args: &[crate::config::ArgMapping],
686 class_name: &str,
687 enum_fields: &HashMap<String, String>,
688 fixture_id: &str,
689 options_via: &str,
690) -> (Vec<String>, String) {
691 if args.is_empty() {
692 let is_empty_input = match input {
695 serde_json::Value::Null => true,
696 serde_json::Value::Object(m) => m.is_empty(),
697 _ => false,
698 };
699 if is_empty_input {
700 return (Vec::new(), String::new());
701 }
702 return (Vec::new(), json_to_php(input));
703 }
704
705 let mut setup_lines: Vec<String> = Vec::new();
706 let mut parts: Vec<String> = Vec::new();
707
708 for arg in args {
709 if arg.arg_type == "mock_url" {
710 setup_lines.push(format!(
711 "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
712 arg.name,
713 ));
714 parts.push(format!("${}", arg.name));
715 continue;
716 }
717
718 if arg.arg_type == "handle" {
719 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
721 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
722 let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
723 if config_value.is_null()
724 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
725 {
726 setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
727 } else {
728 let name = &arg.name;
729 setup_lines.push(format!("${name}_config = CrawlConfig::default();"));
733 if let Some(obj) = config_value.as_object() {
734 for (key, val) in obj {
735 let php_val = json_to_php(val);
736 setup_lines.push(format!("${name}_config->{key} = {php_val};"));
737 }
738 }
739 setup_lines.push(format!(
740 "${} = {class_name}::{constructor_name}(${name}_config);",
741 arg.name,
742 ));
743 }
744 parts.push(format!("${}", arg.name));
745 continue;
746 }
747
748 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
749 let val = input.get(field);
750 match val {
751 None | Some(serde_json::Value::Null) if arg.optional => {
752 continue;
754 }
755 None | Some(serde_json::Value::Null) => {
756 let default_val = match arg.arg_type.as_str() {
758 "string" => "\"\"".to_string(),
759 "int" | "integer" => "0".to_string(),
760 "float" | "number" => "0.0".to_string(),
761 "bool" | "boolean" => "false".to_string(),
762 "json_object" if options_via == "json" => "null".to_string(),
763 _ => "null".to_string(),
764 };
765 parts.push(default_val);
766 }
767 Some(v) => {
768 if arg.arg_type == "json_object" && !v.is_null() {
769 match options_via {
770 "json" => {
771 parts.push(format!("json_encode({})", json_to_php(v)));
773 continue;
774 }
775 _ => {
776 if let Some(obj) = v.as_object() {
778 let items: Vec<String> = obj
779 .iter()
780 .map(|(k, vv)| {
781 let snake_key = k.to_snake_case();
782 let php_val = if enum_fields.contains_key(k) {
783 if let Some(s) = vv.as_str() {
784 let snake_val = s.to_snake_case();
785 format!("\"{}\"", escape_php(&snake_val))
786 } else {
787 json_to_php(vv)
788 }
789 } else {
790 json_to_php(vv)
791 };
792 format!("\"{}\" => {}", escape_php(&snake_key), php_val)
793 })
794 .collect();
795 parts.push(format!("[{}]", items.join(", ")));
796 continue;
797 }
798 }
799 }
800 }
801 parts.push(json_to_php(v));
802 }
803 }
804 }
805
806 (setup_lines, parts.join(", "))
807}
808
809fn render_assertion(
810 out: &mut String,
811 assertion: &Assertion,
812 result_var: &str,
813 field_resolver: &FieldResolver,
814 result_is_simple: bool,
815) {
816 if let Some(f) = &assertion.field {
818 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
819 let _ = writeln!(out, " // skipped: field '{f}' not available on result type");
820 return;
821 }
822 }
823
824 if result_is_simple {
827 if let Some(f) = &assertion.field {
828 let f_lower = f.to_lowercase();
829 if !f.is_empty()
830 && f_lower != "content"
831 && (f_lower.starts_with("metadata")
832 || f_lower.starts_with("document")
833 || f_lower.starts_with("structure"))
834 {
835 let _ = writeln!(
836 out,
837 " // skipped: result_is_simple, field '{f}' not on simple result type"
838 );
839 return;
840 }
841 }
842 }
843
844 let field_expr = if result_is_simple {
845 format!("${result_var}")
846 } else {
847 match &assertion.field {
848 Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
849 _ => format!("${result_var}"),
850 }
851 };
852
853 let trimmed_field_expr = if result_is_simple {
855 format!("trim(${result_var})")
856 } else {
857 field_expr.clone()
858 };
859
860 match assertion.assertion_type.as_str() {
861 "equals" => {
862 if let Some(expected) = &assertion.value {
863 let php_val = json_to_php(expected);
864 let _ = writeln!(out, " $this->assertEquals({php_val}, {trimmed_field_expr});");
865 }
866 }
867 "contains" => {
868 if let Some(expected) = &assertion.value {
869 let php_val = json_to_php(expected);
870 let _ = writeln!(
871 out,
872 " $this->assertStringContainsString({php_val}, {field_expr});"
873 );
874 }
875 }
876 "contains_all" => {
877 if let Some(values) = &assertion.values {
878 for val in values {
879 let php_val = json_to_php(val);
880 let _ = writeln!(
881 out,
882 " $this->assertStringContainsString({php_val}, {field_expr});"
883 );
884 }
885 }
886 }
887 "not_contains" => {
888 if let Some(expected) = &assertion.value {
889 let php_val = json_to_php(expected);
890 let _ = writeln!(
891 out,
892 " $this->assertStringNotContainsString({php_val}, {field_expr});"
893 );
894 }
895 }
896 "not_empty" => {
897 let _ = writeln!(out, " $this->assertNotEmpty({field_expr});");
898 }
899 "is_empty" => {
900 let _ = writeln!(out, " $this->assertEmpty({trimmed_field_expr});");
901 }
902 "contains_any" => {
903 if let Some(values) = &assertion.values {
904 let _ = writeln!(out, " $found = false;");
905 for val in values {
906 let php_val = json_to_php(val);
907 let _ = writeln!(
908 out,
909 " if (str_contains({field_expr}, {php_val})) {{ $found = true; }}"
910 );
911 }
912 let _ = writeln!(
913 out,
914 " $this->assertTrue($found, 'expected to contain at least one of the specified values');"
915 );
916 }
917 }
918 "greater_than" => {
919 if let Some(val) = &assertion.value {
920 let php_val = json_to_php(val);
921 let _ = writeln!(out, " $this->assertGreaterThan({php_val}, {field_expr});");
922 }
923 }
924 "less_than" => {
925 if let Some(val) = &assertion.value {
926 let php_val = json_to_php(val);
927 let _ = writeln!(out, " $this->assertLessThan({php_val}, {field_expr});");
928 }
929 }
930 "greater_than_or_equal" => {
931 if let Some(val) = &assertion.value {
932 let php_val = json_to_php(val);
933 let _ = writeln!(out, " $this->assertGreaterThanOrEqual({php_val}, {field_expr});");
934 }
935 }
936 "less_than_or_equal" => {
937 if let Some(val) = &assertion.value {
938 let php_val = json_to_php(val);
939 let _ = writeln!(out, " $this->assertLessThanOrEqual({php_val}, {field_expr});");
940 }
941 }
942 "starts_with" => {
943 if let Some(expected) = &assertion.value {
944 let php_val = json_to_php(expected);
945 let _ = writeln!(out, " $this->assertStringStartsWith({php_val}, {field_expr});");
946 }
947 }
948 "ends_with" => {
949 if let Some(expected) = &assertion.value {
950 let php_val = json_to_php(expected);
951 let _ = writeln!(out, " $this->assertStringEndsWith({php_val}, {field_expr});");
952 }
953 }
954 "min_length" => {
955 if let Some(val) = &assertion.value {
956 if let Some(n) = val.as_u64() {
957 let _ = writeln!(
958 out,
959 " $this->assertGreaterThanOrEqual({n}, strlen({field_expr}));"
960 );
961 }
962 }
963 }
964 "max_length" => {
965 if let Some(val) = &assertion.value {
966 if let Some(n) = val.as_u64() {
967 let _ = writeln!(out, " $this->assertLessThanOrEqual({n}, strlen({field_expr}));");
968 }
969 }
970 }
971 "count_min" => {
972 if let Some(val) = &assertion.value {
973 if let Some(n) = val.as_u64() {
974 let _ = writeln!(
975 out,
976 " $this->assertGreaterThanOrEqual({n}, count({field_expr}));"
977 );
978 }
979 }
980 }
981 "count_equals" => {
982 if let Some(val) = &assertion.value {
983 if let Some(n) = val.as_u64() {
984 let _ = writeln!(out, " $this->assertCount({n}, {field_expr});");
985 }
986 }
987 }
988 "is_true" => {
989 let _ = writeln!(out, " $this->assertTrue({field_expr});");
990 }
991 "is_false" => {
992 let _ = writeln!(out, " $this->assertFalse({field_expr});");
993 }
994 "method_result" => {
995 if let Some(method_name) = &assertion.method {
996 let call_expr = build_php_method_call(result_var, method_name, assertion.args.as_ref());
997 let check = assertion.check.as_deref().unwrap_or("is_true");
998 match check {
999 "equals" => {
1000 if let Some(val) = &assertion.value {
1001 if val.is_boolean() {
1002 if val.as_bool() == Some(true) {
1003 let _ = writeln!(out, " $this->assertTrue({call_expr});");
1004 } else {
1005 let _ = writeln!(out, " $this->assertFalse({call_expr});");
1006 }
1007 } else {
1008 let expected = json_to_php(val);
1009 let _ = writeln!(out, " $this->assertEquals({expected}, {call_expr});");
1010 }
1011 }
1012 }
1013 "is_true" => {
1014 let _ = writeln!(out, " $this->assertTrue({call_expr});");
1015 }
1016 "is_false" => {
1017 let _ = writeln!(out, " $this->assertFalse({call_expr});");
1018 }
1019 "greater_than_or_equal" => {
1020 if let Some(val) = &assertion.value {
1021 let n = val.as_u64().unwrap_or(0);
1022 let _ = writeln!(out, " $this->assertGreaterThanOrEqual({n}, {call_expr});");
1023 }
1024 }
1025 "count_min" => {
1026 if let Some(val) = &assertion.value {
1027 let n = val.as_u64().unwrap_or(0);
1028 let _ = writeln!(out, " $this->assertGreaterThanOrEqual({n}, count({call_expr}));");
1029 }
1030 }
1031 "is_error" => {
1032 let _ = writeln!(out, " $this->expectException(\\Exception::class);");
1033 let _ = writeln!(out, " {call_expr};");
1034 }
1035 "contains" => {
1036 if let Some(val) = &assertion.value {
1037 let expected = json_to_php(val);
1038 let _ = writeln!(
1039 out,
1040 " $this->assertStringContainsString({expected}, {call_expr});"
1041 );
1042 }
1043 }
1044 other_check => {
1045 panic!("PHP e2e generator: unsupported method_result check type: {other_check}");
1046 }
1047 }
1048 } else {
1049 panic!("PHP e2e generator: method_result assertion missing 'method' field");
1050 }
1051 }
1052 "matches_regex" => {
1053 if let Some(expected) = &assertion.value {
1054 let php_val = json_to_php(expected);
1055 let _ = writeln!(
1056 out,
1057 " $this->assertMatchesRegularExpression({php_val}, {field_expr});"
1058 );
1059 }
1060 }
1061 "not_error" => {
1062 }
1064 "error" => {
1065 }
1067 other => {
1068 panic!("PHP e2e generator: unsupported assertion type: {other}");
1069 }
1070 }
1071}
1072
1073fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1078 match method_name {
1079 "root_child_count" => {
1080 format!("count(TreeSitterLanguagePack::named_children_info(${result_var}))")
1081 }
1082 "root_node_type" => {
1083 format!("TreeSitterLanguagePack::root_node_info(${result_var})->kind")
1084 }
1085 "named_children_count" => {
1086 format!("count(TreeSitterLanguagePack::named_children_info(${result_var}))")
1087 }
1088 "has_error_nodes" => {
1089 format!("TreeSitterLanguagePack::tree_has_error_nodes(${result_var})")
1090 }
1091 "error_count" | "tree_error_count" => {
1092 format!("TreeSitterLanguagePack::tree_error_count(${result_var})")
1093 }
1094 "tree_to_sexp" => {
1095 format!("TreeSitterLanguagePack::tree_to_sexp(${result_var})")
1096 }
1097 "contains_node_type" => {
1098 let node_type = args
1099 .and_then(|a| a.get("node_type"))
1100 .and_then(|v| v.as_str())
1101 .unwrap_or("");
1102 format!("TreeSitterLanguagePack::tree_contains_node_type(${result_var}, \"{node_type}\")")
1103 }
1104 "find_nodes_by_type" => {
1105 let node_type = args
1106 .and_then(|a| a.get("node_type"))
1107 .and_then(|v| v.as_str())
1108 .unwrap_or("");
1109 format!("TreeSitterLanguagePack::find_nodes_by_type(${result_var}, \"{node_type}\")")
1110 }
1111 "run_query" => {
1112 let query_source = args
1113 .and_then(|a| a.get("query_source"))
1114 .and_then(|v| v.as_str())
1115 .unwrap_or("");
1116 let language = args
1117 .and_then(|a| a.get("language"))
1118 .and_then(|v| v.as_str())
1119 .unwrap_or("");
1120 format!("TreeSitterLanguagePack::run_query(${result_var}, \"{language}\", \"{query_source}\", $source)")
1121 }
1122 _ => {
1123 format!("${result_var}->{method_name}()")
1124 }
1125 }
1126}
1127
1128fn json_to_php(value: &serde_json::Value) -> String {
1130 match value {
1131 serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1132 serde_json::Value::Bool(true) => "true".to_string(),
1133 serde_json::Value::Bool(false) => "false".to_string(),
1134 serde_json::Value::Number(n) => n.to_string(),
1135 serde_json::Value::Null => "null".to_string(),
1136 serde_json::Value::Array(arr) => {
1137 let items: Vec<String> = arr.iter().map(json_to_php).collect();
1138 format!("[{}]", items.join(", "))
1139 }
1140 serde_json::Value::Object(map) => {
1141 let items: Vec<String> = map
1142 .iter()
1143 .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1144 .collect();
1145 format!("[{}]", items.join(", "))
1146 }
1147 }
1148}
1149
1150fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) -> String {
1156 setup_lines.push("$visitor = new class {".to_string());
1157 for (method_name, action) in &visitor_spec.callbacks {
1158 emit_php_visitor_method(setup_lines, method_name, action);
1159 }
1160 setup_lines.push("};".to_string());
1161 "$visitor".to_string()
1162}
1163
1164fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1166 let snake_method = method_name;
1167 let params = match method_name {
1168 "visit_link" => "$ctx, $href, $text, $title",
1169 "visit_image" => "$ctx, $src, $alt, $title",
1170 "visit_heading" => "$ctx, $level, $text, $id",
1171 "visit_code_block" => "$ctx, $lang, $code",
1172 "visit_code_inline"
1173 | "visit_strong"
1174 | "visit_emphasis"
1175 | "visit_strikethrough"
1176 | "visit_underline"
1177 | "visit_subscript"
1178 | "visit_superscript"
1179 | "visit_mark"
1180 | "visit_button"
1181 | "visit_summary"
1182 | "visit_figcaption"
1183 | "visit_definition_term"
1184 | "visit_definition_description" => "$ctx, $text",
1185 "visit_text" => "$ctx, $text",
1186 "visit_list_item" => "$ctx, $ordered, $marker, $text",
1187 "visit_blockquote" => "$ctx, $content, $depth",
1188 "visit_table_row" => "$ctx, $cells, $isHeader",
1189 "visit_custom_element" => "$ctx, $tagName, $html",
1190 "visit_form" => "$ctx, $actionUrl, $method",
1191 "visit_input" => "$ctx, $inputType, $name, $value",
1192 "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1193 "visit_details" => "$ctx, $isOpen",
1194 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1195 "visit_list_start" => "$ctx, $ordered",
1196 "visit_list_end" => "$ctx, $ordered, $output",
1197 _ => "$ctx",
1198 };
1199
1200 setup_lines.push(format!(" public function {snake_method}({params}) {{"));
1201 match action {
1202 CallbackAction::Skip => {
1203 setup_lines.push(" return 'skip';".to_string());
1204 }
1205 CallbackAction::Continue => {
1206 setup_lines.push(" return 'continue';".to_string());
1207 }
1208 CallbackAction::PreserveHtml => {
1209 setup_lines.push(" return 'preserve_html';".to_string());
1210 }
1211 CallbackAction::Custom { output } => {
1212 let escaped = escape_php(output);
1213 setup_lines.push(format!(" return ['custom' => {escaped}];"));
1214 }
1215 CallbackAction::CustomTemplate { template } => {
1216 let escaped = escape_php(template);
1217 setup_lines.push(format!(" return ['custom' => {escaped}];"));
1218 }
1219 }
1220 setup_lines.push(" }".to_string());
1221}