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 {
796 function_name = function_name.to_lower_camel_case();
797 }
798 let result_var = &call_config.result_var;
799 let args = &call_config.args;
800
801 let method_name = sanitize_filename(&fixture.id);
802 let description = &fixture.description;
803 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
804
805 let call_options_type = call_overrides.and_then(|o| o.options_type.as_deref()).or_else(|| {
807 e2e_config
808 .call
809 .overrides
810 .get(lang)
811 .and_then(|o| o.options_type.as_deref())
812 });
813
814 let (mut setup_lines, args_str) = build_args_and_setup(
815 &fixture.input,
816 args,
817 class_name,
818 enum_fields,
819 fixture,
820 options_via,
821 call_options_type,
822 );
823
824 let skip_test = call_config.skip_languages.iter().any(|l| l == "php");
826 if skip_test {
827 let rendered = crate::template_env::render(
828 "php/test_method.jinja",
829 minijinja::context! {
830 method_name => method_name,
831 description => description,
832 client_factory => String::new(),
833 setup_lines => Vec::<String>::new(),
834 expects_error => false,
835 skip_test => true,
836 has_usable_assertions => false,
837 call_expr => String::new(),
838 result_var => result_var,
839 assertions_body => String::new(),
840 },
841 );
842 out.push_str(&rendered);
843 return;
844 }
845
846 let mut options_already_created = !args_str.is_empty() && args_str == "$options";
848 if let Some(visitor_spec) = &fixture.visitor {
849 build_php_visitor(&mut setup_lines, visitor_spec);
850 if !options_already_created {
851 setup_lines.push("$builder = \\HtmlToMarkdown\\ConversionOptions::builder();".to_string());
852 setup_lines.push("$options = $builder->visitor($visitor)->build();".to_string());
853 options_already_created = true;
854 }
855 }
856
857 let final_args = if options_already_created {
858 if args_str.is_empty() || args_str == "$options" {
859 "$options".to_string()
860 } else {
861 format!("{args_str}, $options")
862 }
863 } else {
864 args_str
865 };
866
867 let call_expr = if php_client_factory.is_some() {
868 format!("$client->{function_name}({final_args})")
869 } else {
870 format!("{class_name}::{function_name}({final_args})")
871 };
872
873 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
874 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
875 let client_factory = if let Some(factory) = php_client_factory {
876 let fixture_id = &fixture.id;
877 if let Some(var) = api_key_var.filter(|_| has_mock) {
878 format!(
879 "$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);"
880 )
881 } else if has_mock {
882 let base_url_expr = if fixture.has_host_root_route() {
883 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
884 format!("(getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}')")
885 } else {
886 format!("getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}'")
887 };
888 format!("$client = \\{namespace}\\{class_name}::{factory}('test-key', {base_url_expr});")
889 } else if let Some(var) = api_key_var {
890 format!(
891 "$apiKey = getenv('{var}');\n if (!$apiKey) {{ $this->markTestSkipped('{var} not set'); return; }}\n $client = \\{namespace}\\{class_name}::{factory}($apiKey);"
892 )
893 } else {
894 format!("$client = \\{namespace}\\{class_name}::{factory}('test-key');")
895 }
896 } else {
897 String::new()
898 };
899
900 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
902
903 let has_usable_assertions = fixture.assertions.iter().any(|a| {
906 if a.assertion_type == "error" || a.assertion_type == "not_error" {
907 return false;
908 }
909 match &a.field {
910 Some(f) if !f.is_empty() => {
911 if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
912 return true;
913 }
914 field_resolver.is_valid_for_result(f)
915 }
916 _ => true,
917 }
918 });
919
920 let collect_snippet = if is_streaming {
922 crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("php", result_var, "chunks")
923 .unwrap_or_default()
924 } else {
925 String::new()
926 };
927
928 let mut assertions_body = String::new();
930 for assertion in &fixture.assertions {
931 render_assertion(
932 &mut assertions_body,
933 assertion,
934 result_var,
935 field_resolver,
936 result_is_simple,
937 call_config.result_is_array,
938 );
939 }
940
941 if is_streaming && !expects_error && assertions_body.trim().is_empty() {
947 assertions_body.push_str(" $this->assertTrue(is_array($chunks), 'expected drained chunks list');\n");
948 }
949
950 let rendered = crate::template_env::render(
951 "php/test_method.jinja",
952 minijinja::context! {
953 method_name => method_name,
954 description => description,
955 client_factory => client_factory,
956 setup_lines => setup_lines,
957 expects_error => expects_error,
958 skip_test => fixture.assertions.is_empty(),
959 has_usable_assertions => has_usable_assertions || is_streaming,
960 call_expr => call_expr,
961 result_var => result_var,
962 collect_snippet => collect_snippet,
963 assertions_body => assertions_body,
964 },
965 );
966 out.push_str(&rendered);
967}
968
969fn emit_php_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
982 if let Some(items) = arr.as_array() {
983 let item_strs: Vec<String> = items
984 .iter()
985 .filter_map(|item| {
986 if let Some(obj) = item.as_object() {
987 match elem_type {
988 "BatchBytesItem" => {
989 let content = obj.get("content").and_then(|v| v.as_array());
990 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
991 let content_code = if let Some(arr) = content {
992 let bytes: Vec<String> = arr
993 .iter()
994 .filter_map(|v| v.as_u64())
995 .map(|n| format!("\\x{:02x}", n))
996 .collect();
997 format!("\"{}\"", bytes.join(""))
998 } else {
999 "\"\"".to_string()
1000 };
1001 Some(format!(
1002 "new {}(content: {}, mimeType: \"{}\")",
1003 elem_type, content_code, mime_type
1004 ))
1005 }
1006 "BatchFileItem" => {
1007 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1008 Some(format!("new {}(path: \"{}\")", elem_type, path))
1009 }
1010 _ => None,
1011 }
1012 } else {
1013 None
1014 }
1015 })
1016 .collect();
1017 format!("[{}]", item_strs.join(", "))
1018 } else {
1019 "[]".to_string()
1020 }
1021}
1022
1023fn build_args_and_setup(
1024 input: &serde_json::Value,
1025 args: &[crate::config::ArgMapping],
1026 class_name: &str,
1027 _enum_fields: &HashMap<String, String>,
1028 fixture: &crate::fixture::Fixture,
1029 options_via: &str,
1030 options_type: Option<&str>,
1031) -> (Vec<String>, String) {
1032 let fixture_id = &fixture.id;
1033 if args.is_empty() {
1034 let is_empty_input = match input {
1037 serde_json::Value::Null => true,
1038 serde_json::Value::Object(m) => m.is_empty(),
1039 _ => false,
1040 };
1041 if is_empty_input {
1042 return (Vec::new(), String::new());
1043 }
1044 return (Vec::new(), json_to_php(input));
1045 }
1046
1047 let mut setup_lines: Vec<String> = Vec::new();
1048 let mut parts: Vec<String> = Vec::new();
1049
1050 let arg_has_emission = |arg: &crate::config::ArgMapping| -> bool {
1055 let val = if arg.field == "input" {
1056 Some(input)
1057 } else {
1058 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1059 input.get(field)
1060 };
1061 match val {
1062 None | Some(serde_json::Value::Null) => !arg.optional,
1063 Some(_) => true,
1064 }
1065 };
1066 let any_later_has_emission = |from_idx: usize| -> bool { args[from_idx..].iter().any(arg_has_emission) };
1067
1068 for (idx, arg) in args.iter().enumerate() {
1069 if arg.arg_type == "mock_url" {
1070 if fixture.has_host_root_route() {
1071 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1072 setup_lines.push(format!(
1073 "${} = getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1074 arg.name,
1075 ));
1076 } else {
1077 setup_lines.push(format!(
1078 "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1079 arg.name,
1080 ));
1081 }
1082 parts.push(format!("${}", arg.name));
1083 continue;
1084 }
1085
1086 if arg.arg_type == "handle" {
1087 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1089 let config_value = if arg.field == "input" {
1090 input
1091 } else {
1092 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1093 input.get(field).unwrap_or(&serde_json::Value::Null)
1094 };
1095 if config_value.is_null()
1096 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1097 {
1098 setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
1099 } else {
1100 let name = &arg.name;
1101 let filtered_config = filter_empty_enum_strings(config_value);
1106 setup_lines.push(format!(
1107 "${name}_config = CrawlConfig::from_json(json_encode({}));",
1108 json_to_php_camel_keys(&filtered_config)
1109 ));
1110 setup_lines.push(format!(
1111 "${} = {class_name}::{constructor_name}(${name}_config);",
1112 arg.name,
1113 ));
1114 }
1115 parts.push(format!("${}", arg.name));
1116 continue;
1117 }
1118
1119 let val = if arg.field == "input" {
1120 Some(input)
1121 } else {
1122 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1123 input.get(field)
1124 };
1125
1126 if arg.arg_type == "bytes" {
1130 match val {
1131 None | Some(serde_json::Value::Null) => {
1132 if arg.optional {
1133 parts.push("null".to_string());
1134 } else {
1135 parts.push("\"\"".to_string());
1136 }
1137 }
1138 Some(serde_json::Value::String(s)) => {
1139 let var_name = format!("{}Bytes", arg.name);
1140 setup_lines.push(format!(
1141 "${var_name} = file_get_contents(\"{path}\");\n if (${var_name} === false) {{ $this->fail(\"failed to read fixture: {path}\"); }}",
1142 path = s.replace('"', "\\\"")
1143 ));
1144 parts.push(format!("${var_name}"));
1145 }
1146 Some(serde_json::Value::Array(arr)) => {
1147 let bytes: String = arr
1148 .iter()
1149 .filter_map(|v| v.as_u64())
1150 .map(|n| format!("\\x{:02x}", n))
1151 .collect();
1152 parts.push(format!("\"{bytes}\""));
1153 }
1154 Some(other) => {
1155 parts.push(json_to_php(other));
1156 }
1157 }
1158 continue;
1159 }
1160
1161 match val {
1162 None | Some(serde_json::Value::Null) if arg.arg_type == "json_object" && arg.name == "config" => {
1163 let type_name = if arg.name == "config" {
1169 "ExtractionConfig".to_string()
1170 } else {
1171 format!("{}Config", arg.name.to_upper_camel_case())
1172 };
1173 parts.push(format!("{type_name}::from_json('{{}}')"));
1174 continue;
1175 }
1176 None | Some(serde_json::Value::Null) if arg.optional => {
1177 if any_later_has_emission(idx + 1) {
1182 parts.push("null".to_string());
1183 }
1184 continue;
1185 }
1186 None | Some(serde_json::Value::Null) => {
1187 let default_val = match arg.arg_type.as_str() {
1189 "string" => "\"\"".to_string(),
1190 "int" | "integer" => "0".to_string(),
1191 "float" | "number" => "0.0".to_string(),
1192 "bool" | "boolean" => "false".to_string(),
1193 "json_object" if options_via == "json" => "null".to_string(),
1194 _ => "null".to_string(),
1195 };
1196 parts.push(default_val);
1197 }
1198 Some(v) => {
1199 if arg.arg_type == "json_object" && !v.is_null() {
1200 if let Some(elem_type) = &arg.element_type {
1202 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1203 parts.push(emit_php_batch_item_array(v, elem_type));
1204 continue;
1205 }
1206 if v.is_array() && is_php_reserved_type(elem_type) {
1210 parts.push(json_to_php(v));
1211 continue;
1212 }
1213 }
1214 match options_via {
1215 "json" => {
1216 let filtered_v = filter_empty_enum_strings(v);
1219
1220 if let serde_json::Value::Object(obj) = &filtered_v {
1222 if obj.is_empty() {
1223 parts.push("null".to_string());
1224 continue;
1225 }
1226 }
1227
1228 parts.push(format!("json_encode({})", json_to_php_camel_keys(&filtered_v)));
1229 continue;
1230 }
1231 _ => {
1232 if let Some(type_name) = options_type {
1233 let filtered_v = filter_empty_enum_strings(v);
1238
1239 if let serde_json::Value::Object(obj) = &filtered_v {
1242 if obj.is_empty() {
1243 let arg_var = format!("${}", arg.name);
1244 setup_lines.push(format!("{arg_var} = {type_name}::from_json('{{}}');"));
1245 parts.push(arg_var);
1246 continue;
1247 }
1248 }
1249
1250 let arg_var = format!("${}", arg.name);
1251 setup_lines.push(format!(
1255 "{arg_var} = {type_name}::from_json(json_encode({}));",
1256 json_to_php_camel_keys(&filtered_v)
1257 ));
1258 parts.push(arg_var);
1259 continue;
1260 }
1261 if let Some(obj) = v.as_object() {
1265 setup_lines.push("$builder = $this->createDefaultOptionsBuilder();".to_string());
1266 for (k, vv) in obj {
1267 let snake_key = k.to_snake_case();
1268 if snake_key == "preprocessing" {
1269 if let Some(prep_obj) = vv.as_object() {
1270 let enabled =
1271 prep_obj.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);
1272 let preset =
1273 prep_obj.get("preset").and_then(|v| v.as_str()).unwrap_or("Minimal");
1274 let remove_navigation = prep_obj
1275 .get("remove_navigation")
1276 .and_then(|v| v.as_bool())
1277 .unwrap_or(true);
1278 let remove_forms =
1279 prep_obj.get("remove_forms").and_then(|v| v.as_bool()).unwrap_or(true);
1280 setup_lines.push(format!(
1281 "$preprocessing = $this->createPreprocessingOptions({}, {}, {}, {});",
1282 if enabled { "true" } else { "false" },
1283 json_to_php(&serde_json::Value::String(preset.to_string())),
1284 if remove_navigation { "true" } else { "false" },
1285 if remove_forms { "true" } else { "false" }
1286 ));
1287 setup_lines.push(
1288 "$builder = $builder->preprocessing($preprocessing);".to_string(),
1289 );
1290 }
1291 }
1292 }
1293 setup_lines.push("$options = $builder->build();".to_string());
1294 parts.push("$options".to_string());
1295 continue;
1296 }
1297 }
1298 }
1299 }
1300 parts.push(json_to_php(v));
1301 }
1302 }
1303 }
1304
1305 (setup_lines, parts.join(", "))
1306}
1307
1308fn render_assertion(
1309 out: &mut String,
1310 assertion: &Assertion,
1311 result_var: &str,
1312 field_resolver: &FieldResolver,
1313 result_is_simple: bool,
1314 result_is_array: bool,
1315) {
1316 if let Some(f) = &assertion.field {
1319 match f.as_str() {
1320 "chunks_have_content" => {
1321 let pred = format!(
1322 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->content), true)"
1323 );
1324 out.push_str(&crate::template_env::render(
1325 "php/synthetic_assertion.jinja",
1326 minijinja::context! {
1327 assertion_kind => "chunks_content",
1328 assertion_type => assertion.assertion_type.as_str(),
1329 pred => pred,
1330 field_name => f,
1331 },
1332 ));
1333 return;
1334 }
1335 "chunks_have_embeddings" => {
1336 let pred = format!(
1337 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->embedding), true)"
1338 );
1339 out.push_str(&crate::template_env::render(
1340 "php/synthetic_assertion.jinja",
1341 minijinja::context! {
1342 assertion_kind => "chunks_embeddings",
1343 assertion_type => assertion.assertion_type.as_str(),
1344 pred => pred,
1345 field_name => f,
1346 },
1347 ));
1348 return;
1349 }
1350 "embeddings" => {
1354 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1355 out.push_str(&crate::template_env::render(
1356 "php/synthetic_assertion.jinja",
1357 minijinja::context! {
1358 assertion_kind => "embeddings",
1359 assertion_type => assertion.assertion_type.as_str(),
1360 php_val => php_val,
1361 result_var => result_var,
1362 },
1363 ));
1364 return;
1365 }
1366 "embedding_dimensions" => {
1367 let expr = format!("(empty(${result_var}) ? 0 : count(${result_var}[0]))");
1368 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1369 out.push_str(&crate::template_env::render(
1370 "php/synthetic_assertion.jinja",
1371 minijinja::context! {
1372 assertion_kind => "embedding_dimensions",
1373 assertion_type => assertion.assertion_type.as_str(),
1374 expr => expr,
1375 php_val => php_val,
1376 },
1377 ));
1378 return;
1379 }
1380 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1381 let pred = match f.as_str() {
1382 "embeddings_valid" => {
1383 format!("array_reduce(${result_var}, fn($carry, $e) => $carry && count($e) > 0, true)")
1384 }
1385 "embeddings_finite" => {
1386 format!(
1387 "array_reduce(${result_var}, fn($carry, $e) => $carry && array_reduce($e, fn($c, $v) => $c && is_finite($v), true), true)"
1388 )
1389 }
1390 "embeddings_non_zero" => {
1391 format!(
1392 "array_reduce(${result_var}, fn($carry, $e) => $carry && count(array_filter($e, fn($v) => $v !== 0.0)) > 0, true)"
1393 )
1394 }
1395 "embeddings_normalized" => {
1396 format!(
1397 "array_reduce(${result_var}, fn($carry, $e) => $carry && abs(array_sum(array_map(fn($v) => $v * $v, $e)) - 1.0) < 1e-3, true)"
1398 )
1399 }
1400 _ => unreachable!(),
1401 };
1402 let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1403 out.push_str(&crate::template_env::render(
1404 "php/synthetic_assertion.jinja",
1405 minijinja::context! {
1406 assertion_kind => assertion_kind,
1407 assertion_type => assertion.assertion_type.as_str(),
1408 pred => pred,
1409 field_name => f,
1410 },
1411 ));
1412 return;
1413 }
1414 "keywords" | "keywords_count" => {
1417 out.push_str(&crate::template_env::render(
1418 "php/synthetic_assertion.jinja",
1419 minijinja::context! {
1420 assertion_kind => "keywords",
1421 field_name => f,
1422 },
1423 ));
1424 return;
1425 }
1426 _ => {}
1427 }
1428 }
1429
1430 if let Some(f) = &assertion.field {
1433 if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1434 if let Some(expr) =
1435 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "php", "chunks")
1436 {
1437 let line = match assertion.assertion_type.as_str() {
1438 "count_min" => {
1439 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1440 format!(
1441 " $this->assertGreaterThanOrEqual({n}, count({expr}), 'expected >= {n} chunks');\n"
1442 )
1443 } else {
1444 String::new()
1445 }
1446 }
1447 "count_equals" => {
1448 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1449 format!(" $this->assertCount({n}, {expr});\n")
1450 } else {
1451 String::new()
1452 }
1453 }
1454 "equals" => {
1455 if let Some(serde_json::Value::String(s)) = &assertion.value {
1456 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1457 format!(" $this->assertEquals('{escaped}', {expr});\n")
1458 } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1459 format!(" $this->assertEquals({n}, {expr});\n")
1460 } else {
1461 String::new()
1462 }
1463 }
1464 "not_empty" => format!(" $this->assertNotEmpty({expr});\n"),
1465 "is_empty" => format!(" $this->assertEmpty({expr});\n"),
1466 "is_true" => format!(" $this->assertTrue({expr});\n"),
1467 "is_false" => format!(" $this->assertFalse({expr});\n"),
1468 "greater_than" => {
1469 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1470 format!(" $this->assertGreaterThan({n}, {expr});\n")
1471 } else {
1472 String::new()
1473 }
1474 }
1475 "greater_than_or_equal" => {
1476 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1477 format!(" $this->assertGreaterThanOrEqual({n}, {expr});\n")
1478 } else {
1479 String::new()
1480 }
1481 }
1482 "contains" => {
1483 if let Some(serde_json::Value::String(s)) = &assertion.value {
1484 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1485 format!(" $this->assertStringContainsString('{escaped}', {expr});\n")
1486 } else {
1487 String::new()
1488 }
1489 }
1490 _ => format!(
1491 " // streaming field '{f}': assertion type '{}' not rendered\n",
1492 assertion.assertion_type
1493 ),
1494 };
1495 if !line.is_empty() {
1496 out.push_str(&line);
1497 }
1498 }
1499 return;
1500 }
1501 }
1502
1503 if let Some(f) = &assertion.field {
1505 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1506 out.push_str(&crate::template_env::render(
1507 "php/synthetic_assertion.jinja",
1508 minijinja::context! {
1509 assertion_kind => "skipped",
1510 field_name => f,
1511 },
1512 ));
1513 return;
1514 }
1515 }
1516
1517 if result_is_simple {
1520 if let Some(f) = &assertion.field {
1521 let f_lower = f.to_lowercase();
1522 if !f.is_empty()
1523 && f_lower != "content"
1524 && (f_lower.starts_with("metadata")
1525 || f_lower.starts_with("document")
1526 || f_lower.starts_with("structure"))
1527 {
1528 out.push_str(&crate::template_env::render(
1529 "php/synthetic_assertion.jinja",
1530 minijinja::context! {
1531 assertion_kind => "result_is_simple",
1532 field_name => f,
1533 },
1534 ));
1535 return;
1536 }
1537 }
1538 }
1539
1540 let field_expr = match &assertion.field {
1541 _ if result_is_simple => format!("${result_var}"),
1545 Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
1546 _ => format!("${result_var}"),
1547 };
1548
1549 let field_is_array = assertion.field.as_ref().map_or(result_is_array, |f| {
1552 if f.is_empty() {
1553 result_is_array
1554 } else {
1555 field_resolver.is_array(f)
1556 }
1557 });
1558
1559 let trimmed_field_expr_for = |expected: &serde_json::Value| -> String {
1563 if expected.is_string() {
1564 format!("trim({})", field_expr)
1565 } else {
1566 field_expr.clone()
1567 }
1568 };
1569
1570 let assertion_type = assertion.assertion_type.as_str();
1572 let has_php_val = assertion.value.is_some();
1573 let php_val = match assertion.value.as_ref() {
1577 Some(v) => json_to_php(v),
1578 None if assertion_type == "equals" => "null".to_string(),
1579 None => String::new(),
1580 };
1581 let trimmed_field_expr = trimmed_field_expr_for(assertion.value.as_ref().unwrap_or(&serde_json::Value::Null));
1582 let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1583 let values_php: Vec<String> = assertion
1587 .values
1588 .as_ref()
1589 .map(|vals| vals.iter().map(json_to_php).collect::<Vec<_>>())
1590 .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_php(v)]))
1591 .unwrap_or_default();
1592 let contains_any_checks: Vec<String> = assertion
1593 .values
1594 .as_ref()
1595 .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1596 let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1597
1598 let call_expr = if let Some(method_name) = &assertion.method {
1600 build_php_method_call(result_var, method_name, assertion.args.as_ref())
1601 } else {
1602 String::new()
1603 };
1604 let check = assertion.check.as_deref().unwrap_or("is_true");
1605 let has_php_check_val = matches!(assertion.assertion_type.as_str(), "method_result") && assertion.value.is_some();
1606 let php_check_val = if matches!(assertion.assertion_type.as_str(), "method_result") {
1607 assertion.value.as_ref().map(json_to_php).unwrap_or_default()
1608 } else {
1609 String::new()
1610 };
1611 let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1612 let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1613 let bool_is_true = assertion.value.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
1614
1615 if matches!(assertion_type, "not_error" | "error") {
1617 if assertion_type == "not_error" {
1618 }
1620 return;
1622 }
1623
1624 let rendered = crate::template_env::render(
1625 "php/assertion.jinja",
1626 minijinja::context! {
1627 assertion_type => assertion_type,
1628 field_expr => field_expr,
1629 php_val => php_val,
1630 has_php_val => has_php_val,
1631 trimmed_field_expr => trimmed_field_expr,
1632 is_string_val => is_string_val,
1633 field_is_array => field_is_array,
1634 values_php => values_php,
1635 contains_any_checks => contains_any_checks,
1636 n => n,
1637 call_expr => call_expr,
1638 check => check,
1639 php_check_val => php_check_val,
1640 has_php_check_val => has_php_check_val,
1641 check_n => check_n,
1642 is_bool_val => is_bool_val,
1643 bool_is_true => bool_is_true,
1644 },
1645 );
1646 let _ = write!(out, " {}", rendered);
1647}
1648
1649fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1656 let extra_args = if let Some(args_val) = args {
1657 args_val
1658 .as_object()
1659 .map(|obj| {
1660 obj.values()
1661 .map(|v| match v {
1662 serde_json::Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1663 serde_json::Value::Bool(true) => "true".to_string(),
1664 serde_json::Value::Bool(false) => "false".to_string(),
1665 serde_json::Value::Number(n) => n.to_string(),
1666 serde_json::Value::Null => "null".to_string(),
1667 other => format!("\"{}\"", other.to_string().replace('\\', "\\\\").replace('"', "\\\"")),
1668 })
1669 .collect::<Vec<_>>()
1670 .join(", ")
1671 })
1672 .unwrap_or_default()
1673 } else {
1674 String::new()
1675 };
1676
1677 if extra_args.is_empty() {
1678 format!("${result_var}->{method_name}()")
1679 } else {
1680 format!("${result_var}->{method_name}({extra_args})")
1681 }
1682}
1683
1684fn filter_empty_enum_strings(value: &serde_json::Value) -> serde_json::Value {
1688 match value {
1689 serde_json::Value::Object(map) => {
1690 let filtered: serde_json::Map<String, serde_json::Value> = map
1691 .iter()
1692 .filter_map(|(k, v)| {
1693 if let serde_json::Value::String(s) = v {
1695 if s.is_empty() {
1696 return None;
1697 }
1698 }
1699 Some((k.clone(), filter_empty_enum_strings(v)))
1701 })
1702 .collect();
1703 serde_json::Value::Object(filtered)
1704 }
1705 serde_json::Value::Array(arr) => {
1706 let filtered: Vec<serde_json::Value> = arr.iter().map(filter_empty_enum_strings).collect();
1707 serde_json::Value::Array(filtered)
1708 }
1709 other => other.clone(),
1710 }
1711}
1712
1713fn json_to_php(value: &serde_json::Value) -> String {
1715 match value {
1716 serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1717 serde_json::Value::Bool(true) => "true".to_string(),
1718 serde_json::Value::Bool(false) => "false".to_string(),
1719 serde_json::Value::Number(n) => n.to_string(),
1720 serde_json::Value::Null => "null".to_string(),
1721 serde_json::Value::Array(arr) => {
1722 let items: Vec<String> = arr.iter().map(json_to_php).collect();
1723 format!("[{}]", items.join(", "))
1724 }
1725 serde_json::Value::Object(map) => {
1726 let items: Vec<String> = map
1727 .iter()
1728 .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1729 .collect();
1730 format!("[{}]", items.join(", "))
1731 }
1732 }
1733}
1734
1735fn json_to_php_camel_keys(value: &serde_json::Value) -> String {
1740 match value {
1741 serde_json::Value::Object(map) => {
1742 let items: Vec<String> = map
1743 .iter()
1744 .map(|(k, v)| {
1745 let camel_key = k.to_lower_camel_case();
1746 format!("\"{}\" => {}", escape_php(&camel_key), json_to_php_camel_keys(v))
1747 })
1748 .collect();
1749 format!("[{}]", items.join(", "))
1750 }
1751 serde_json::Value::Array(arr) => {
1752 let items: Vec<String> = arr.iter().map(json_to_php_camel_keys).collect();
1753 format!("[{}]", items.join(", "))
1754 }
1755 _ => json_to_php(value),
1756 }
1757}
1758
1759fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1765 setup_lines.push("$visitor = new class {".to_string());
1766 for (method_name, action) in &visitor_spec.callbacks {
1767 emit_php_visitor_method(setup_lines, method_name, action);
1768 }
1769 setup_lines.push("};".to_string());
1770}
1771
1772fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1774 let params = match method_name {
1775 "visit_link" => "$ctx, $href, $text, $title",
1776 "visit_image" => "$ctx, $src, $alt, $title",
1777 "visit_heading" => "$ctx, $level, $text, $id",
1778 "visit_code_block" => "$ctx, $lang, $code",
1779 "visit_code_inline"
1780 | "visit_strong"
1781 | "visit_emphasis"
1782 | "visit_strikethrough"
1783 | "visit_underline"
1784 | "visit_subscript"
1785 | "visit_superscript"
1786 | "visit_mark"
1787 | "visit_button"
1788 | "visit_summary"
1789 | "visit_figcaption"
1790 | "visit_definition_term"
1791 | "visit_definition_description" => "$ctx, $text",
1792 "visit_text" => "$ctx, $text",
1793 "visit_list_item" => "$ctx, $ordered, $marker, $text",
1794 "visit_blockquote" => "$ctx, $content, $depth",
1795 "visit_table_row" => "$ctx, $cells, $isHeader",
1796 "visit_custom_element" => "$ctx, $tagName, $html",
1797 "visit_form" => "$ctx, $actionUrl, $method",
1798 "visit_input" => "$ctx, $input_type, $name, $value",
1799 "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1800 "visit_details" => "$ctx, $isOpen",
1801 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1802 "visit_list_start" => "$ctx, $ordered",
1803 "visit_list_end" => "$ctx, $ordered, $output",
1804 _ => "$ctx",
1805 };
1806
1807 let (action_type, action_value, return_form) = match action {
1808 CallbackAction::Skip => ("skip", String::new(), "dict"),
1809 CallbackAction::Continue => ("continue", String::new(), "dict"),
1810 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
1811 CallbackAction::Custom { output } => ("custom", escape_php(output), "dict"),
1812 CallbackAction::CustomTemplate { template, return_form } => {
1813 let form = match return_form {
1814 TemplateReturnForm::Dict => "dict",
1815 TemplateReturnForm::BareString => "bare_string",
1816 };
1817 ("custom_template", escape_php(template), form)
1818 }
1819 };
1820
1821 let rendered = crate::template_env::render(
1822 "php/visitor_method.jinja",
1823 minijinja::context! {
1824 method_name => method_name,
1825 params => params,
1826 action_type => action_type,
1827 action_value => action_value,
1828 return_form => return_form,
1829 },
1830 );
1831 for line in rendered.lines() {
1832 setup_lines.push(line.to_string());
1833 }
1834}
1835
1836fn is_php_reserved_type(name: &str) -> bool {
1838 matches!(
1839 name.to_ascii_lowercase().as_str(),
1840 "string"
1841 | "int"
1842 | "integer"
1843 | "float"
1844 | "double"
1845 | "bool"
1846 | "boolean"
1847 | "array"
1848 | "object"
1849 | "null"
1850 | "void"
1851 | "callable"
1852 | "iterable"
1853 | "never"
1854 | "self"
1855 | "parent"
1856 | "static"
1857 | "true"
1858 | "false"
1859 | "mixed"
1860 )
1861}