1use 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
27pub 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 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 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 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 let e2e_vendor = pkg_name.split('/').next().unwrap_or(&pkg_name).to_string();
105 let e2e_pkg_name = format!("{e2e_vendor}/e2e-php");
106 let php_namespace_escaped = php_autoload_namespace(config).replace('\\', "\\\\");
111 let e2e_autoload_ns = format!("{php_namespace_escaped}\\\\E2e\\\\");
112
113 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 files.push(GeneratedFile {
129 path: output_base.join("phpunit.xml"),
130 content: render_phpunit_xml(),
131 generated_header: false,
132 });
133
134 let has_http_fixtures = groups
137 .iter()
138 .flat_map(|g| g.fixtures.iter())
139 .any(|f| f.needs_mock_server());
140
141 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 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 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 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
220fn 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 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 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 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 let has_http_tests = fixtures.iter().any(|f| f.is_http_test());
395
396 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 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 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
473struct PhpTestClientRenderer;
481
482impl client::TestClientRenderer for PhpTestClientRenderer {
483 fn language_name(&self) -> &'static str {
484 "php"
485 }
486
487 fn sanitize_test_name(&self, id: &str) -> String {
489 sanitize_filename(id)
490 }
491
492 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 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 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
521 let method = ctx.method.to_uppercase();
522
523 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 let mut header_pairs: Vec<String> = Vec::new();
533 if let Some(ct) = ctx.content_type {
534 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 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 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 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 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 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
737fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
742 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#[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 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 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 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 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 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 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 let is_streaming = fixture.is_streaming_mock();
903
904 let has_usable_assertions = fixture.assertions.iter().any(|a| {
907 if a.assertion_type == "error" || a.assertion_type == "not_error" {
908 return false;
909 }
910 match &a.field {
911 Some(f) if !f.is_empty() => {
912 if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
913 return true;
914 }
915 field_resolver.is_valid_for_result(f)
916 }
917 _ => true,
918 }
919 });
920
921 let collect_snippet = if is_streaming {
923 crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("php", result_var, "chunks")
924 .unwrap_or_default()
925 } else {
926 String::new()
927 };
928
929 let mut assertions_body = String::new();
931 for assertion in &fixture.assertions {
932 render_assertion(
933 &mut assertions_body,
934 assertion,
935 result_var,
936 field_resolver,
937 result_is_simple,
938 call_config.result_is_array,
939 );
940 }
941
942 let rendered = crate::template_env::render(
943 "php/test_method.jinja",
944 minijinja::context! {
945 method_name => method_name,
946 description => description,
947 client_factory => client_factory,
948 setup_lines => setup_lines,
949 expects_error => expects_error,
950 skip_test => fixture.assertions.is_empty(),
951 has_usable_assertions => has_usable_assertions || is_streaming,
952 call_expr => call_expr,
953 result_var => result_var,
954 collect_snippet => collect_snippet,
955 assertions_body => assertions_body,
956 },
957 );
958 out.push_str(&rendered);
959}
960
961fn emit_php_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
974 if let Some(items) = arr.as_array() {
975 let item_strs: Vec<String> = items
976 .iter()
977 .filter_map(|item| {
978 if let Some(obj) = item.as_object() {
979 match elem_type {
980 "BatchBytesItem" => {
981 let content = obj.get("content").and_then(|v| v.as_array());
982 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
983 let content_code = if let Some(arr) = content {
984 let bytes: Vec<String> = arr
985 .iter()
986 .filter_map(|v| v.as_u64())
987 .map(|n| format!("\\x{:02x}", n))
988 .collect();
989 format!("\"{}\"", bytes.join(""))
990 } else {
991 "\"\"".to_string()
992 };
993 Some(format!(
994 "new {}(content: {}, mimeType: \"{}\")",
995 elem_type, content_code, mime_type
996 ))
997 }
998 "BatchFileItem" => {
999 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1000 Some(format!("new {}(path: \"{}\")", elem_type, path))
1001 }
1002 _ => None,
1003 }
1004 } else {
1005 None
1006 }
1007 })
1008 .collect();
1009 format!("[{}]", item_strs.join(", "))
1010 } else {
1011 "[]".to_string()
1012 }
1013}
1014
1015fn build_args_and_setup(
1016 input: &serde_json::Value,
1017 args: &[crate::config::ArgMapping],
1018 class_name: &str,
1019 _enum_fields: &HashMap<String, String>,
1020 fixture: &crate::fixture::Fixture,
1021 options_via: &str,
1022 options_type: Option<&str>,
1023) -> (Vec<String>, String) {
1024 let fixture_id = &fixture.id;
1025 if args.is_empty() {
1026 let is_empty_input = match input {
1029 serde_json::Value::Null => true,
1030 serde_json::Value::Object(m) => m.is_empty(),
1031 _ => false,
1032 };
1033 if is_empty_input {
1034 return (Vec::new(), String::new());
1035 }
1036 return (Vec::new(), json_to_php(input));
1037 }
1038
1039 let mut setup_lines: Vec<String> = Vec::new();
1040 let mut parts: Vec<String> = Vec::new();
1041
1042 let arg_has_emission = |arg: &crate::config::ArgMapping| -> bool {
1047 let val = if arg.field == "input" {
1048 Some(input)
1049 } else {
1050 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1051 input.get(field)
1052 };
1053 match val {
1054 None | Some(serde_json::Value::Null) => !arg.optional,
1055 Some(_) => true,
1056 }
1057 };
1058 let any_later_has_emission = |from_idx: usize| -> bool { args[from_idx..].iter().any(arg_has_emission) };
1059
1060 for (idx, arg) in args.iter().enumerate() {
1061 if arg.arg_type == "mock_url" {
1062 if fixture.has_host_root_route() {
1063 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1064 setup_lines.push(format!(
1065 "${} = getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1066 arg.name,
1067 ));
1068 } else {
1069 setup_lines.push(format!(
1070 "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1071 arg.name,
1072 ));
1073 }
1074 parts.push(format!("${}", arg.name));
1075 continue;
1076 }
1077
1078 if arg.arg_type == "handle" {
1079 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1081 let config_value = if arg.field == "input" {
1082 input
1083 } else {
1084 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1085 input.get(field).unwrap_or(&serde_json::Value::Null)
1086 };
1087 if config_value.is_null()
1088 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1089 {
1090 setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
1091 } else {
1092 let name = &arg.name;
1093 let filtered_config = filter_empty_enum_strings(config_value);
1098 setup_lines.push(format!(
1099 "${name}_config = CrawlConfig::from_json(json_encode({}));",
1100 json_to_php(&filtered_config)
1101 ));
1102 setup_lines.push(format!(
1103 "${} = {class_name}::{constructor_name}(${name}_config);",
1104 arg.name,
1105 ));
1106 }
1107 parts.push(format!("${}", arg.name));
1108 continue;
1109 }
1110
1111 let val = if arg.field == "input" {
1112 Some(input)
1113 } else {
1114 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1115 input.get(field)
1116 };
1117
1118 if arg.arg_type == "bytes" {
1122 match val {
1123 None | Some(serde_json::Value::Null) => {
1124 if arg.optional {
1125 parts.push("null".to_string());
1126 } else {
1127 parts.push("\"\"".to_string());
1128 }
1129 }
1130 Some(serde_json::Value::String(s)) => {
1131 let var_name = format!("{}Bytes", arg.name);
1132 setup_lines.push(format!(
1133 "${var_name} = file_get_contents(\"{path}\");\n if (${var_name} === false) {{ $this->fail(\"failed to read fixture: {path}\"); }}",
1134 path = s.replace('"', "\\\"")
1135 ));
1136 parts.push(format!("${var_name}"));
1137 }
1138 Some(serde_json::Value::Array(arr)) => {
1139 let bytes: String = arr
1140 .iter()
1141 .filter_map(|v| v.as_u64())
1142 .map(|n| format!("\\x{:02x}", n))
1143 .collect();
1144 parts.push(format!("\"{bytes}\""));
1145 }
1146 Some(other) => {
1147 parts.push(json_to_php(other));
1148 }
1149 }
1150 continue;
1151 }
1152
1153 match val {
1154 None | Some(serde_json::Value::Null) if arg.arg_type == "json_object" && arg.name == "config" => {
1155 let type_name = if arg.name == "config" {
1161 "ExtractionConfig".to_string()
1162 } else {
1163 format!("{}Config", arg.name.to_upper_camel_case())
1164 };
1165 parts.push(format!("{type_name}::from_json('{{}}')"));
1166 continue;
1167 }
1168 None | Some(serde_json::Value::Null) if arg.optional => {
1169 if any_later_has_emission(idx + 1) {
1174 parts.push("null".to_string());
1175 }
1176 continue;
1177 }
1178 None | Some(serde_json::Value::Null) => {
1179 let default_val = match arg.arg_type.as_str() {
1181 "string" => "\"\"".to_string(),
1182 "int" | "integer" => "0".to_string(),
1183 "float" | "number" => "0.0".to_string(),
1184 "bool" | "boolean" => "false".to_string(),
1185 "json_object" if options_via == "json" => "null".to_string(),
1186 _ => "null".to_string(),
1187 };
1188 parts.push(default_val);
1189 }
1190 Some(v) => {
1191 if arg.arg_type == "json_object" && !v.is_null() {
1192 if let Some(elem_type) = &arg.element_type {
1194 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1195 parts.push(emit_php_batch_item_array(v, elem_type));
1196 continue;
1197 }
1198 if v.is_array() && is_php_reserved_type(elem_type) {
1202 parts.push(json_to_php(v));
1203 continue;
1204 }
1205 }
1206 match options_via {
1207 "json" => {
1208 let filtered_v = filter_empty_enum_strings(v);
1211
1212 if let serde_json::Value::Object(obj) = &filtered_v {
1214 if obj.is_empty() {
1215 parts.push("null".to_string());
1216 continue;
1217 }
1218 }
1219
1220 parts.push(format!("json_encode({})", json_to_php_camel_keys(&filtered_v)));
1221 continue;
1222 }
1223 _ => {
1224 if let Some(type_name) = options_type {
1225 let filtered_v = filter_empty_enum_strings(v);
1230
1231 if let serde_json::Value::Object(obj) = &filtered_v {
1234 if obj.is_empty() {
1235 let arg_var = format!("${}", arg.name);
1236 setup_lines.push(format!("{arg_var} = {type_name}::from_json('{{}}');"));
1237 parts.push(arg_var);
1238 continue;
1239 }
1240 }
1241
1242 let arg_var = format!("${}", arg.name);
1243 setup_lines.push(format!(
1247 "{arg_var} = {type_name}::from_json(json_encode({}));",
1248 json_to_php(&filtered_v)
1249 ));
1250 parts.push(arg_var);
1251 continue;
1252 }
1253 if let Some(obj) = v.as_object() {
1257 setup_lines.push("$builder = $this->createDefaultOptionsBuilder();".to_string());
1258 for (k, vv) in obj {
1259 let snake_key = k.to_snake_case();
1260 if snake_key == "preprocessing" {
1261 if let Some(prep_obj) = vv.as_object() {
1262 let enabled =
1263 prep_obj.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);
1264 let preset =
1265 prep_obj.get("preset").and_then(|v| v.as_str()).unwrap_or("Minimal");
1266 let remove_navigation = prep_obj
1267 .get("remove_navigation")
1268 .and_then(|v| v.as_bool())
1269 .unwrap_or(true);
1270 let remove_forms =
1271 prep_obj.get("remove_forms").and_then(|v| v.as_bool()).unwrap_or(true);
1272 setup_lines.push(format!(
1273 "$preprocessing = $this->createPreprocessingOptions({}, {}, {}, {});",
1274 if enabled { "true" } else { "false" },
1275 json_to_php(&serde_json::Value::String(preset.to_string())),
1276 if remove_navigation { "true" } else { "false" },
1277 if remove_forms { "true" } else { "false" }
1278 ));
1279 setup_lines.push(
1280 "$builder = $builder->preprocessing($preprocessing);".to_string(),
1281 );
1282 }
1283 }
1284 }
1285 setup_lines.push("$options = $builder->build();".to_string());
1286 parts.push("$options".to_string());
1287 continue;
1288 }
1289 }
1290 }
1291 }
1292 parts.push(json_to_php(v));
1293 }
1294 }
1295 }
1296
1297 (setup_lines, parts.join(", "))
1298}
1299
1300fn render_assertion(
1301 out: &mut String,
1302 assertion: &Assertion,
1303 result_var: &str,
1304 field_resolver: &FieldResolver,
1305 result_is_simple: bool,
1306 result_is_array: bool,
1307) {
1308 if let Some(f) = &assertion.field {
1311 match f.as_str() {
1312 "chunks_have_content" => {
1313 let pred = format!(
1314 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->content), true)"
1315 );
1316 out.push_str(&crate::template_env::render(
1317 "php/synthetic_assertion.jinja",
1318 minijinja::context! {
1319 assertion_kind => "chunks_content",
1320 assertion_type => assertion.assertion_type.as_str(),
1321 pred => pred,
1322 field_name => f,
1323 },
1324 ));
1325 return;
1326 }
1327 "chunks_have_embeddings" => {
1328 let pred = format!(
1329 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->embedding), true)"
1330 );
1331 out.push_str(&crate::template_env::render(
1332 "php/synthetic_assertion.jinja",
1333 minijinja::context! {
1334 assertion_kind => "chunks_embeddings",
1335 assertion_type => assertion.assertion_type.as_str(),
1336 pred => pred,
1337 field_name => f,
1338 },
1339 ));
1340 return;
1341 }
1342 "embeddings" => {
1346 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1347 out.push_str(&crate::template_env::render(
1348 "php/synthetic_assertion.jinja",
1349 minijinja::context! {
1350 assertion_kind => "embeddings",
1351 assertion_type => assertion.assertion_type.as_str(),
1352 php_val => php_val,
1353 result_var => result_var,
1354 },
1355 ));
1356 return;
1357 }
1358 "embedding_dimensions" => {
1359 let expr = format!("(empty(${result_var}) ? 0 : count(${result_var}[0]))");
1360 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1361 out.push_str(&crate::template_env::render(
1362 "php/synthetic_assertion.jinja",
1363 minijinja::context! {
1364 assertion_kind => "embedding_dimensions",
1365 assertion_type => assertion.assertion_type.as_str(),
1366 expr => expr,
1367 php_val => php_val,
1368 },
1369 ));
1370 return;
1371 }
1372 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1373 let pred = match f.as_str() {
1374 "embeddings_valid" => {
1375 format!("array_reduce(${result_var}, fn($carry, $e) => $carry && count($e) > 0, true)")
1376 }
1377 "embeddings_finite" => {
1378 format!(
1379 "array_reduce(${result_var}, fn($carry, $e) => $carry && array_reduce($e, fn($c, $v) => $c && is_finite($v), true), true)"
1380 )
1381 }
1382 "embeddings_non_zero" => {
1383 format!(
1384 "array_reduce(${result_var}, fn($carry, $e) => $carry && count(array_filter($e, fn($v) => $v !== 0.0)) > 0, true)"
1385 )
1386 }
1387 "embeddings_normalized" => {
1388 format!(
1389 "array_reduce(${result_var}, fn($carry, $e) => $carry && abs(array_sum(array_map(fn($v) => $v * $v, $e)) - 1.0) < 1e-3, true)"
1390 )
1391 }
1392 _ => unreachable!(),
1393 };
1394 let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1395 out.push_str(&crate::template_env::render(
1396 "php/synthetic_assertion.jinja",
1397 minijinja::context! {
1398 assertion_kind => assertion_kind,
1399 assertion_type => assertion.assertion_type.as_str(),
1400 pred => pred,
1401 field_name => f,
1402 },
1403 ));
1404 return;
1405 }
1406 "keywords" | "keywords_count" => {
1409 out.push_str(&crate::template_env::render(
1410 "php/synthetic_assertion.jinja",
1411 minijinja::context! {
1412 assertion_kind => "keywords",
1413 field_name => f,
1414 },
1415 ));
1416 return;
1417 }
1418 _ => {}
1419 }
1420 }
1421
1422 if let Some(f) = &assertion.field {
1425 if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1426 if let Some(expr) =
1427 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "php", "chunks")
1428 {
1429 let line = match assertion.assertion_type.as_str() {
1430 "count_min" => {
1431 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1432 format!(
1433 " $this->assertGreaterThanOrEqual({n}, count({expr}), 'expected >= {n} chunks');\n"
1434 )
1435 } else {
1436 String::new()
1437 }
1438 }
1439 "count_equals" => {
1440 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1441 format!(" $this->assertCount({n}, {expr});\n")
1442 } else {
1443 String::new()
1444 }
1445 }
1446 "equals" => {
1447 if let Some(serde_json::Value::String(s)) = &assertion.value {
1448 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1449 format!(" $this->assertEquals('{escaped}', {expr});\n")
1450 } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1451 format!(" $this->assertEquals({n}, {expr});\n")
1452 } else {
1453 String::new()
1454 }
1455 }
1456 "not_empty" => format!(" $this->assertNotEmpty({expr});\n"),
1457 "is_empty" => format!(" $this->assertEmpty({expr});\n"),
1458 "is_true" => format!(" $this->assertTrue({expr});\n"),
1459 "is_false" => format!(" $this->assertFalse({expr});\n"),
1460 "greater_than" => {
1461 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1462 format!(" $this->assertGreaterThan({n}, {expr});\n")
1463 } else {
1464 String::new()
1465 }
1466 }
1467 "greater_than_or_equal" => {
1468 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1469 format!(" $this->assertGreaterThanOrEqual({n}, {expr});\n")
1470 } else {
1471 String::new()
1472 }
1473 }
1474 "contains" => {
1475 if let Some(serde_json::Value::String(s)) = &assertion.value {
1476 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1477 format!(" $this->assertStringContainsString('{escaped}', {expr});\n")
1478 } else {
1479 String::new()
1480 }
1481 }
1482 _ => format!(
1483 " // streaming field '{f}': assertion type '{}' not rendered\n",
1484 assertion.assertion_type
1485 ),
1486 };
1487 if !line.is_empty() {
1488 out.push_str(&line);
1489 }
1490 }
1491 return;
1492 }
1493 }
1494
1495 if let Some(f) = &assertion.field {
1497 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1498 out.push_str(&crate::template_env::render(
1499 "php/synthetic_assertion.jinja",
1500 minijinja::context! {
1501 assertion_kind => "skipped",
1502 field_name => f,
1503 },
1504 ));
1505 return;
1506 }
1507 }
1508
1509 if result_is_simple {
1512 if let Some(f) = &assertion.field {
1513 let f_lower = f.to_lowercase();
1514 if !f.is_empty()
1515 && f_lower != "content"
1516 && (f_lower.starts_with("metadata")
1517 || f_lower.starts_with("document")
1518 || f_lower.starts_with("structure"))
1519 {
1520 out.push_str(&crate::template_env::render(
1521 "php/synthetic_assertion.jinja",
1522 minijinja::context! {
1523 assertion_kind => "result_is_simple",
1524 field_name => f,
1525 },
1526 ));
1527 return;
1528 }
1529 }
1530 }
1531
1532 let field_expr = match &assertion.field {
1533 _ if result_is_simple => format!("${result_var}"),
1537 Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
1538 _ => format!("${result_var}"),
1539 };
1540
1541 let field_is_array = assertion.field.as_ref().map_or(result_is_array, |f| {
1544 if f.is_empty() {
1545 result_is_array
1546 } else {
1547 field_resolver.is_array(f)
1548 }
1549 });
1550
1551 let trimmed_field_expr_for = |expected: &serde_json::Value| -> String {
1555 if expected.is_string() {
1556 format!("trim({})", field_expr)
1557 } else {
1558 field_expr.clone()
1559 }
1560 };
1561
1562 let assertion_type = assertion.assertion_type.as_str();
1564 let has_php_val = assertion.value.is_some();
1565 let php_val = match assertion.value.as_ref() {
1569 Some(v) => json_to_php(v),
1570 None if assertion_type == "equals" => "null".to_string(),
1571 None => String::new(),
1572 };
1573 let trimmed_field_expr = trimmed_field_expr_for(assertion.value.as_ref().unwrap_or(&serde_json::Value::Null));
1574 let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1575 let values_php: Vec<String> = assertion
1579 .values
1580 .as_ref()
1581 .map(|vals| vals.iter().map(json_to_php).collect::<Vec<_>>())
1582 .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_php(v)]))
1583 .unwrap_or_default();
1584 let contains_any_checks: Vec<String> = assertion
1585 .values
1586 .as_ref()
1587 .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1588 let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1589
1590 let call_expr = if let Some(method_name) = &assertion.method {
1592 build_php_method_call(result_var, method_name, assertion.args.as_ref())
1593 } else {
1594 String::new()
1595 };
1596 let check = assertion.check.as_deref().unwrap_or("is_true");
1597 let has_php_check_val = matches!(assertion.assertion_type.as_str(), "method_result") && assertion.value.is_some();
1598 let php_check_val = if matches!(assertion.assertion_type.as_str(), "method_result") {
1599 assertion.value.as_ref().map(json_to_php).unwrap_or_default()
1600 } else {
1601 String::new()
1602 };
1603 let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1604 let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1605 let bool_is_true = assertion.value.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
1606
1607 if matches!(assertion_type, "not_error" | "error") {
1609 if assertion_type == "not_error" {
1610 }
1612 return;
1614 }
1615
1616 let rendered = crate::template_env::render(
1617 "php/assertion.jinja",
1618 minijinja::context! {
1619 assertion_type => assertion_type,
1620 field_expr => field_expr,
1621 php_val => php_val,
1622 has_php_val => has_php_val,
1623 trimmed_field_expr => trimmed_field_expr,
1624 is_string_val => is_string_val,
1625 field_is_array => field_is_array,
1626 values_php => values_php,
1627 contains_any_checks => contains_any_checks,
1628 n => n,
1629 call_expr => call_expr,
1630 check => check,
1631 php_check_val => php_check_val,
1632 has_php_check_val => has_php_check_val,
1633 check_n => check_n,
1634 is_bool_val => is_bool_val,
1635 bool_is_true => bool_is_true,
1636 },
1637 );
1638 let _ = write!(out, " {}", rendered);
1639}
1640
1641fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1648 let extra_args = if let Some(args_val) = args {
1649 args_val
1650 .as_object()
1651 .map(|obj| {
1652 obj.values()
1653 .map(|v| match v {
1654 serde_json::Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1655 serde_json::Value::Bool(true) => "true".to_string(),
1656 serde_json::Value::Bool(false) => "false".to_string(),
1657 serde_json::Value::Number(n) => n.to_string(),
1658 serde_json::Value::Null => "null".to_string(),
1659 other => format!("\"{}\"", other.to_string().replace('\\', "\\\\").replace('"', "\\\"")),
1660 })
1661 .collect::<Vec<_>>()
1662 .join(", ")
1663 })
1664 .unwrap_or_default()
1665 } else {
1666 String::new()
1667 };
1668
1669 if extra_args.is_empty() {
1670 format!("${result_var}->{method_name}()")
1671 } else {
1672 format!("${result_var}->{method_name}({extra_args})")
1673 }
1674}
1675
1676fn filter_empty_enum_strings(value: &serde_json::Value) -> serde_json::Value {
1680 match value {
1681 serde_json::Value::Object(map) => {
1682 let filtered: serde_json::Map<String, serde_json::Value> = map
1683 .iter()
1684 .filter_map(|(k, v)| {
1685 if let serde_json::Value::String(s) = v {
1687 if s.is_empty() {
1688 return None;
1689 }
1690 }
1691 Some((k.clone(), filter_empty_enum_strings(v)))
1693 })
1694 .collect();
1695 serde_json::Value::Object(filtered)
1696 }
1697 serde_json::Value::Array(arr) => {
1698 let filtered: Vec<serde_json::Value> = arr.iter().map(filter_empty_enum_strings).collect();
1699 serde_json::Value::Array(filtered)
1700 }
1701 other => other.clone(),
1702 }
1703}
1704
1705fn json_to_php(value: &serde_json::Value) -> String {
1707 match value {
1708 serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1709 serde_json::Value::Bool(true) => "true".to_string(),
1710 serde_json::Value::Bool(false) => "false".to_string(),
1711 serde_json::Value::Number(n) => n.to_string(),
1712 serde_json::Value::Null => "null".to_string(),
1713 serde_json::Value::Array(arr) => {
1714 let items: Vec<String> = arr.iter().map(json_to_php).collect();
1715 format!("[{}]", items.join(", "))
1716 }
1717 serde_json::Value::Object(map) => {
1718 let items: Vec<String> = map
1719 .iter()
1720 .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1721 .collect();
1722 format!("[{}]", items.join(", "))
1723 }
1724 }
1725}
1726
1727fn json_to_php_camel_keys(value: &serde_json::Value) -> String {
1732 match value {
1733 serde_json::Value::Object(map) => {
1734 let items: Vec<String> = map
1735 .iter()
1736 .map(|(k, v)| {
1737 let camel_key = k.to_lower_camel_case();
1738 format!("\"{}\" => {}", escape_php(&camel_key), json_to_php_camel_keys(v))
1739 })
1740 .collect();
1741 format!("[{}]", items.join(", "))
1742 }
1743 serde_json::Value::Array(arr) => {
1744 let items: Vec<String> = arr.iter().map(json_to_php_camel_keys).collect();
1745 format!("[{}]", items.join(", "))
1746 }
1747 _ => json_to_php(value),
1748 }
1749}
1750
1751fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1757 setup_lines.push("$visitor = new class {".to_string());
1758 for (method_name, action) in &visitor_spec.callbacks {
1759 emit_php_visitor_method(setup_lines, method_name, action);
1760 }
1761 setup_lines.push("};".to_string());
1762}
1763
1764fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1766 let params = match method_name {
1767 "visit_link" => "$ctx, $href, $text, $title",
1768 "visit_image" => "$ctx, $src, $alt, $title",
1769 "visit_heading" => "$ctx, $level, $text, $id",
1770 "visit_code_block" => "$ctx, $lang, $code",
1771 "visit_code_inline"
1772 | "visit_strong"
1773 | "visit_emphasis"
1774 | "visit_strikethrough"
1775 | "visit_underline"
1776 | "visit_subscript"
1777 | "visit_superscript"
1778 | "visit_mark"
1779 | "visit_button"
1780 | "visit_summary"
1781 | "visit_figcaption"
1782 | "visit_definition_term"
1783 | "visit_definition_description" => "$ctx, $text",
1784 "visit_text" => "$ctx, $text",
1785 "visit_list_item" => "$ctx, $ordered, $marker, $text",
1786 "visit_blockquote" => "$ctx, $content, $depth",
1787 "visit_table_row" => "$ctx, $cells, $isHeader",
1788 "visit_custom_element" => "$ctx, $tagName, $html",
1789 "visit_form" => "$ctx, $actionUrl, $method",
1790 "visit_input" => "$ctx, $input_type, $name, $value",
1791 "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1792 "visit_details" => "$ctx, $isOpen",
1793 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1794 "visit_list_start" => "$ctx, $ordered",
1795 "visit_list_end" => "$ctx, $ordered, $output",
1796 _ => "$ctx",
1797 };
1798
1799 let (action_type, action_value, return_form) = match action {
1800 CallbackAction::Skip => ("skip", String::new(), "dict"),
1801 CallbackAction::Continue => ("continue", String::new(), "dict"),
1802 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
1803 CallbackAction::Custom { output } => ("custom", escape_php(output), "dict"),
1804 CallbackAction::CustomTemplate { template, return_form } => {
1805 let form = match return_form {
1806 TemplateReturnForm::Dict => "dict",
1807 TemplateReturnForm::BareString => "bare_string",
1808 };
1809 ("custom_template", escape_php(template), form)
1810 }
1811 };
1812
1813 let rendered = crate::template_env::render(
1814 "php/visitor_method.jinja",
1815 minijinja::context! {
1816 method_name => method_name,
1817 params => params,
1818 action_type => action_type,
1819 action_value => action_value,
1820 return_form => return_form,
1821 },
1822 );
1823 for line in rendered.lines() {
1824 setup_lines.push(line.to_string());
1825 }
1826}
1827
1828fn is_php_reserved_type(name: &str) -> bool {
1830 matches!(
1831 name.to_ascii_lowercase().as_str(),
1832 "string"
1833 | "int"
1834 | "integer"
1835 | "float"
1836 | "double"
1837 | "bool"
1838 | "boolean"
1839 | "array"
1840 | "object"
1841 | "null"
1842 | "void"
1843 | "callable"
1844 | "iterable"
1845 | "never"
1846 | "self"
1847 | "parent"
1848 | "static"
1849 | "true"
1850 | "false"
1851 | "mixed"
1852 )
1853}