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 = fixture.is_streaming_mock()
905 || fixture.assertions.iter().any(|a| {
906 a.field
907 .as_deref()
908 .is_some_and(|f| !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f))
909 });
910
911 let has_usable_assertions = fixture.assertions.iter().any(|a| {
914 if a.assertion_type == "error" || a.assertion_type == "not_error" {
915 return false;
916 }
917 match &a.field {
918 Some(f) if !f.is_empty() => {
919 if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
920 return true;
921 }
922 field_resolver.is_valid_for_result(f)
923 }
924 _ => true,
925 }
926 });
927
928 let collect_snippet = if is_streaming {
930 crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("php", result_var, "chunks")
931 .unwrap_or_default()
932 } else {
933 String::new()
934 };
935
936 let mut assertions_body = String::new();
938 for assertion in &fixture.assertions {
939 render_assertion(
940 &mut assertions_body,
941 assertion,
942 result_var,
943 field_resolver,
944 result_is_simple,
945 call_config.result_is_array,
946 );
947 }
948
949 if is_streaming && !expects_error && assertions_body.trim().is_empty() {
955 assertions_body.push_str(" $this->assertTrue(is_array($chunks), 'expected drained chunks list');\n");
956 }
957
958 let rendered = crate::template_env::render(
959 "php/test_method.jinja",
960 minijinja::context! {
961 method_name => method_name,
962 description => description,
963 client_factory => client_factory,
964 setup_lines => setup_lines,
965 expects_error => expects_error,
966 skip_test => fixture.assertions.is_empty(),
967 has_usable_assertions => has_usable_assertions || is_streaming,
968 call_expr => call_expr,
969 result_var => result_var,
970 collect_snippet => collect_snippet,
971 assertions_body => assertions_body,
972 },
973 );
974 out.push_str(&rendered);
975}
976
977fn emit_php_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
990 if let Some(items) = arr.as_array() {
991 let item_strs: Vec<String> = items
992 .iter()
993 .filter_map(|item| {
994 if let Some(obj) = item.as_object() {
995 match elem_type {
996 "BatchBytesItem" => {
997 let content = obj.get("content").and_then(|v| v.as_array());
998 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
999 let content_code = if let Some(arr) = content {
1000 let bytes: Vec<String> = arr
1001 .iter()
1002 .filter_map(|v| v.as_u64())
1003 .map(|n| format!("\\x{:02x}", n))
1004 .collect();
1005 format!("\"{}\"", bytes.join(""))
1006 } else {
1007 "\"\"".to_string()
1008 };
1009 Some(format!(
1010 "new {}(content: {}, mimeType: \"{}\")",
1011 elem_type, content_code, mime_type
1012 ))
1013 }
1014 "BatchFileItem" => {
1015 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1016 Some(format!("new {}(path: \"{}\")", elem_type, path))
1017 }
1018 _ => None,
1019 }
1020 } else {
1021 None
1022 }
1023 })
1024 .collect();
1025 format!("[{}]", item_strs.join(", "))
1026 } else {
1027 "[]".to_string()
1028 }
1029}
1030
1031fn build_args_and_setup(
1032 input: &serde_json::Value,
1033 args: &[crate::config::ArgMapping],
1034 class_name: &str,
1035 _enum_fields: &HashMap<String, String>,
1036 fixture: &crate::fixture::Fixture,
1037 options_via: &str,
1038 options_type: Option<&str>,
1039) -> (Vec<String>, String) {
1040 let fixture_id = &fixture.id;
1041 if args.is_empty() {
1042 let is_empty_input = match input {
1045 serde_json::Value::Null => true,
1046 serde_json::Value::Object(m) => m.is_empty(),
1047 _ => false,
1048 };
1049 if is_empty_input {
1050 return (Vec::new(), String::new());
1051 }
1052 return (Vec::new(), json_to_php(input));
1053 }
1054
1055 let mut setup_lines: Vec<String> = Vec::new();
1056 let mut parts: Vec<String> = Vec::new();
1057
1058 let arg_has_emission = |arg: &crate::config::ArgMapping| -> bool {
1063 let val = if arg.field == "input" {
1064 Some(input)
1065 } else {
1066 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1067 input.get(field)
1068 };
1069 match val {
1070 None | Some(serde_json::Value::Null) => !arg.optional,
1071 Some(_) => true,
1072 }
1073 };
1074 let any_later_has_emission = |from_idx: usize| -> bool { args[from_idx..].iter().any(arg_has_emission) };
1075
1076 for (idx, arg) in args.iter().enumerate() {
1077 if arg.arg_type == "mock_url" {
1078 if fixture.has_host_root_route() {
1079 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1080 setup_lines.push(format!(
1081 "${} = getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1082 arg.name,
1083 ));
1084 } else {
1085 setup_lines.push(format!(
1086 "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1087 arg.name,
1088 ));
1089 }
1090 parts.push(format!("${}", arg.name));
1091 continue;
1092 }
1093
1094 if arg.arg_type == "handle" {
1095 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1097 let config_value = if arg.field == "input" {
1098 input
1099 } else {
1100 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1101 input.get(field).unwrap_or(&serde_json::Value::Null)
1102 };
1103 if config_value.is_null()
1104 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1105 {
1106 setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
1107 } else {
1108 let name = &arg.name;
1109 let filtered_config = filter_empty_enum_strings(config_value);
1114 setup_lines.push(format!(
1115 "${name}_config = CrawlConfig::from_json(json_encode({}));",
1116 json_to_php(&filtered_config)
1117 ));
1118 setup_lines.push(format!(
1119 "${} = {class_name}::{constructor_name}(${name}_config);",
1120 arg.name,
1121 ));
1122 }
1123 parts.push(format!("${}", arg.name));
1124 continue;
1125 }
1126
1127 let val = if arg.field == "input" {
1128 Some(input)
1129 } else {
1130 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1131 input.get(field)
1132 };
1133
1134 if arg.arg_type == "bytes" {
1138 match val {
1139 None | Some(serde_json::Value::Null) => {
1140 if arg.optional {
1141 parts.push("null".to_string());
1142 } else {
1143 parts.push("\"\"".to_string());
1144 }
1145 }
1146 Some(serde_json::Value::String(s)) => {
1147 let var_name = format!("{}Bytes", arg.name);
1148 setup_lines.push(format!(
1149 "${var_name} = file_get_contents(\"{path}\");\n if (${var_name} === false) {{ $this->fail(\"failed to read fixture: {path}\"); }}",
1150 path = s.replace('"', "\\\"")
1151 ));
1152 parts.push(format!("${var_name}"));
1153 }
1154 Some(serde_json::Value::Array(arr)) => {
1155 let bytes: String = arr
1156 .iter()
1157 .filter_map(|v| v.as_u64())
1158 .map(|n| format!("\\x{:02x}", n))
1159 .collect();
1160 parts.push(format!("\"{bytes}\""));
1161 }
1162 Some(other) => {
1163 parts.push(json_to_php(other));
1164 }
1165 }
1166 continue;
1167 }
1168
1169 match val {
1170 None | Some(serde_json::Value::Null) if arg.arg_type == "json_object" && arg.name == "config" => {
1171 let type_name = if arg.name == "config" {
1177 "ExtractionConfig".to_string()
1178 } else {
1179 format!("{}Config", arg.name.to_upper_camel_case())
1180 };
1181 parts.push(format!("{type_name}::from_json('{{}}')"));
1182 continue;
1183 }
1184 None | Some(serde_json::Value::Null) if arg.optional => {
1185 if any_later_has_emission(idx + 1) {
1190 parts.push("null".to_string());
1191 }
1192 continue;
1193 }
1194 None | Some(serde_json::Value::Null) => {
1195 let default_val = match arg.arg_type.as_str() {
1197 "string" => "\"\"".to_string(),
1198 "int" | "integer" => "0".to_string(),
1199 "float" | "number" => "0.0".to_string(),
1200 "bool" | "boolean" => "false".to_string(),
1201 "json_object" if options_via == "json" => "null".to_string(),
1202 _ => "null".to_string(),
1203 };
1204 parts.push(default_val);
1205 }
1206 Some(v) => {
1207 if arg.arg_type == "json_object" && !v.is_null() {
1208 if let Some(elem_type) = &arg.element_type {
1210 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1211 parts.push(emit_php_batch_item_array(v, elem_type));
1212 continue;
1213 }
1214 if v.is_array() && is_php_reserved_type(elem_type) {
1218 parts.push(json_to_php(v));
1219 continue;
1220 }
1221 }
1222 match options_via {
1223 "json" => {
1224 let filtered_v = filter_empty_enum_strings(v);
1227
1228 if let serde_json::Value::Object(obj) = &filtered_v {
1230 if obj.is_empty() {
1231 parts.push("null".to_string());
1232 continue;
1233 }
1234 }
1235
1236 parts.push(format!("json_encode({})", json_to_php_camel_keys(&filtered_v)));
1237 continue;
1238 }
1239 _ => {
1240 if let Some(type_name) = options_type {
1241 let filtered_v = filter_empty_enum_strings(v);
1246
1247 if let serde_json::Value::Object(obj) = &filtered_v {
1250 if obj.is_empty() {
1251 let arg_var = format!("${}", arg.name);
1252 setup_lines.push(format!("{arg_var} = {type_name}::from_json('{{}}');"));
1253 parts.push(arg_var);
1254 continue;
1255 }
1256 }
1257
1258 let arg_var = format!("${}", arg.name);
1259 setup_lines.push(format!(
1263 "{arg_var} = {type_name}::from_json(json_encode({}));",
1264 json_to_php_camel_keys(&filtered_v)
1265 ));
1266 parts.push(arg_var);
1267 continue;
1268 }
1269 if let Some(obj) = v.as_object() {
1273 setup_lines.push("$builder = $this->createDefaultOptionsBuilder();".to_string());
1274 for (k, vv) in obj {
1275 let snake_key = k.to_snake_case();
1276 if snake_key == "preprocessing" {
1277 if let Some(prep_obj) = vv.as_object() {
1278 let enabled =
1279 prep_obj.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);
1280 let preset =
1281 prep_obj.get("preset").and_then(|v| v.as_str()).unwrap_or("Minimal");
1282 let remove_navigation = prep_obj
1283 .get("remove_navigation")
1284 .and_then(|v| v.as_bool())
1285 .unwrap_or(true);
1286 let remove_forms =
1287 prep_obj.get("remove_forms").and_then(|v| v.as_bool()).unwrap_or(true);
1288 setup_lines.push(format!(
1289 "$preprocessing = $this->createPreprocessingOptions({}, {}, {}, {});",
1290 if enabled { "true" } else { "false" },
1291 json_to_php(&serde_json::Value::String(preset.to_string())),
1292 if remove_navigation { "true" } else { "false" },
1293 if remove_forms { "true" } else { "false" }
1294 ));
1295 setup_lines.push(
1296 "$builder = $builder->preprocessing($preprocessing);".to_string(),
1297 );
1298 }
1299 }
1300 }
1301 setup_lines.push("$options = $builder->build();".to_string());
1302 parts.push("$options".to_string());
1303 continue;
1304 }
1305 }
1306 }
1307 }
1308 parts.push(json_to_php(v));
1309 }
1310 }
1311 }
1312
1313 (setup_lines, parts.join(", "))
1314}
1315
1316fn render_assertion(
1317 out: &mut String,
1318 assertion: &Assertion,
1319 result_var: &str,
1320 field_resolver: &FieldResolver,
1321 result_is_simple: bool,
1322 result_is_array: bool,
1323) {
1324 if let Some(f) = &assertion.field {
1327 match f.as_str() {
1328 "chunks_have_content" => {
1329 let pred = format!(
1330 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->content), true)"
1331 );
1332 out.push_str(&crate::template_env::render(
1333 "php/synthetic_assertion.jinja",
1334 minijinja::context! {
1335 assertion_kind => "chunks_content",
1336 assertion_type => assertion.assertion_type.as_str(),
1337 pred => pred,
1338 field_name => f,
1339 },
1340 ));
1341 return;
1342 }
1343 "chunks_have_embeddings" => {
1344 let pred = format!(
1345 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->embedding), true)"
1346 );
1347 out.push_str(&crate::template_env::render(
1348 "php/synthetic_assertion.jinja",
1349 minijinja::context! {
1350 assertion_kind => "chunks_embeddings",
1351 assertion_type => assertion.assertion_type.as_str(),
1352 pred => pred,
1353 field_name => f,
1354 },
1355 ));
1356 return;
1357 }
1358 "embeddings" => {
1362 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1363 out.push_str(&crate::template_env::render(
1364 "php/synthetic_assertion.jinja",
1365 minijinja::context! {
1366 assertion_kind => "embeddings",
1367 assertion_type => assertion.assertion_type.as_str(),
1368 php_val => php_val,
1369 result_var => result_var,
1370 },
1371 ));
1372 return;
1373 }
1374 "embedding_dimensions" => {
1375 let expr = format!("(empty(${result_var}) ? 0 : count(${result_var}[0]))");
1376 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1377 out.push_str(&crate::template_env::render(
1378 "php/synthetic_assertion.jinja",
1379 minijinja::context! {
1380 assertion_kind => "embedding_dimensions",
1381 assertion_type => assertion.assertion_type.as_str(),
1382 expr => expr,
1383 php_val => php_val,
1384 },
1385 ));
1386 return;
1387 }
1388 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1389 let pred = match f.as_str() {
1390 "embeddings_valid" => {
1391 format!("array_reduce(${result_var}, fn($carry, $e) => $carry && count($e) > 0, true)")
1392 }
1393 "embeddings_finite" => {
1394 format!(
1395 "array_reduce(${result_var}, fn($carry, $e) => $carry && array_reduce($e, fn($c, $v) => $c && is_finite($v), true), true)"
1396 )
1397 }
1398 "embeddings_non_zero" => {
1399 format!(
1400 "array_reduce(${result_var}, fn($carry, $e) => $carry && count(array_filter($e, fn($v) => $v !== 0.0)) > 0, true)"
1401 )
1402 }
1403 "embeddings_normalized" => {
1404 format!(
1405 "array_reduce(${result_var}, fn($carry, $e) => $carry && abs(array_sum(array_map(fn($v) => $v * $v, $e)) - 1.0) < 1e-3, true)"
1406 )
1407 }
1408 _ => unreachable!(),
1409 };
1410 let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1411 out.push_str(&crate::template_env::render(
1412 "php/synthetic_assertion.jinja",
1413 minijinja::context! {
1414 assertion_kind => assertion_kind,
1415 assertion_type => assertion.assertion_type.as_str(),
1416 pred => pred,
1417 field_name => f,
1418 },
1419 ));
1420 return;
1421 }
1422 "keywords" | "keywords_count" => {
1425 out.push_str(&crate::template_env::render(
1426 "php/synthetic_assertion.jinja",
1427 minijinja::context! {
1428 assertion_kind => "keywords",
1429 field_name => f,
1430 },
1431 ));
1432 return;
1433 }
1434 _ => {}
1435 }
1436 }
1437
1438 if let Some(f) = &assertion.field {
1441 if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1442 if let Some(expr) =
1443 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "php", "chunks")
1444 {
1445 let line = match assertion.assertion_type.as_str() {
1446 "count_min" => {
1447 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1448 format!(
1449 " $this->assertGreaterThanOrEqual({n}, count({expr}), 'expected >= {n} chunks');\n"
1450 )
1451 } else {
1452 String::new()
1453 }
1454 }
1455 "count_equals" => {
1456 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1457 format!(" $this->assertCount({n}, {expr});\n")
1458 } else {
1459 String::new()
1460 }
1461 }
1462 "equals" => {
1463 if let Some(serde_json::Value::String(s)) = &assertion.value {
1464 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1465 format!(" $this->assertEquals('{escaped}', {expr});\n")
1466 } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1467 format!(" $this->assertEquals({n}, {expr});\n")
1468 } else {
1469 String::new()
1470 }
1471 }
1472 "not_empty" => format!(" $this->assertNotEmpty({expr});\n"),
1473 "is_empty" => format!(" $this->assertEmpty({expr});\n"),
1474 "is_true" => format!(" $this->assertTrue({expr});\n"),
1475 "is_false" => format!(" $this->assertFalse({expr});\n"),
1476 "greater_than" => {
1477 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1478 format!(" $this->assertGreaterThan({n}, {expr});\n")
1479 } else {
1480 String::new()
1481 }
1482 }
1483 "greater_than_or_equal" => {
1484 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1485 format!(" $this->assertGreaterThanOrEqual({n}, {expr});\n")
1486 } else {
1487 String::new()
1488 }
1489 }
1490 "contains" => {
1491 if let Some(serde_json::Value::String(s)) = &assertion.value {
1492 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1493 format!(" $this->assertStringContainsString('{escaped}', {expr});\n")
1494 } else {
1495 String::new()
1496 }
1497 }
1498 _ => format!(
1499 " // streaming field '{f}': assertion type '{}' not rendered\n",
1500 assertion.assertion_type
1501 ),
1502 };
1503 if !line.is_empty() {
1504 out.push_str(&line);
1505 }
1506 }
1507 return;
1508 }
1509 }
1510
1511 if let Some(f) = &assertion.field {
1513 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1514 out.push_str(&crate::template_env::render(
1515 "php/synthetic_assertion.jinja",
1516 minijinja::context! {
1517 assertion_kind => "skipped",
1518 field_name => f,
1519 },
1520 ));
1521 return;
1522 }
1523 }
1524
1525 if result_is_simple {
1528 if let Some(f) = &assertion.field {
1529 let f_lower = f.to_lowercase();
1530 if !f.is_empty()
1531 && f_lower != "content"
1532 && (f_lower.starts_with("metadata")
1533 || f_lower.starts_with("document")
1534 || f_lower.starts_with("structure"))
1535 {
1536 out.push_str(&crate::template_env::render(
1537 "php/synthetic_assertion.jinja",
1538 minijinja::context! {
1539 assertion_kind => "result_is_simple",
1540 field_name => f,
1541 },
1542 ));
1543 return;
1544 }
1545 }
1546 }
1547
1548 let field_expr = match &assertion.field {
1549 _ if result_is_simple => format!("${result_var}"),
1553 Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
1554 _ => format!("${result_var}"),
1555 };
1556
1557 let field_is_array = assertion.field.as_ref().map_or(result_is_array, |f| {
1560 if f.is_empty() {
1561 result_is_array
1562 } else {
1563 field_resolver.is_array(f)
1564 }
1565 });
1566
1567 let trimmed_field_expr_for = |expected: &serde_json::Value| -> String {
1571 if expected.is_string() {
1572 format!("trim({})", field_expr)
1573 } else {
1574 field_expr.clone()
1575 }
1576 };
1577
1578 let assertion_type = assertion.assertion_type.as_str();
1580 let has_php_val = assertion.value.is_some();
1581 let php_val = match assertion.value.as_ref() {
1585 Some(v) => json_to_php(v),
1586 None if assertion_type == "equals" => "null".to_string(),
1587 None => String::new(),
1588 };
1589 let trimmed_field_expr = trimmed_field_expr_for(assertion.value.as_ref().unwrap_or(&serde_json::Value::Null));
1590 let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1591 let values_php: Vec<String> = assertion
1595 .values
1596 .as_ref()
1597 .map(|vals| vals.iter().map(json_to_php).collect::<Vec<_>>())
1598 .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_php(v)]))
1599 .unwrap_or_default();
1600 let contains_any_checks: Vec<String> = assertion
1601 .values
1602 .as_ref()
1603 .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1604 let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1605
1606 let call_expr = if let Some(method_name) = &assertion.method {
1608 build_php_method_call(result_var, method_name, assertion.args.as_ref())
1609 } else {
1610 String::new()
1611 };
1612 let check = assertion.check.as_deref().unwrap_or("is_true");
1613 let has_php_check_val = matches!(assertion.assertion_type.as_str(), "method_result") && assertion.value.is_some();
1614 let php_check_val = if matches!(assertion.assertion_type.as_str(), "method_result") {
1615 assertion.value.as_ref().map(json_to_php).unwrap_or_default()
1616 } else {
1617 String::new()
1618 };
1619 let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1620 let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1621 let bool_is_true = assertion.value.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
1622
1623 if matches!(assertion_type, "not_error" | "error") {
1625 if assertion_type == "not_error" {
1626 }
1628 return;
1630 }
1631
1632 let rendered = crate::template_env::render(
1633 "php/assertion.jinja",
1634 minijinja::context! {
1635 assertion_type => assertion_type,
1636 field_expr => field_expr,
1637 php_val => php_val,
1638 has_php_val => has_php_val,
1639 trimmed_field_expr => trimmed_field_expr,
1640 is_string_val => is_string_val,
1641 field_is_array => field_is_array,
1642 values_php => values_php,
1643 contains_any_checks => contains_any_checks,
1644 n => n,
1645 call_expr => call_expr,
1646 check => check,
1647 php_check_val => php_check_val,
1648 has_php_check_val => has_php_check_val,
1649 check_n => check_n,
1650 is_bool_val => is_bool_val,
1651 bool_is_true => bool_is_true,
1652 },
1653 );
1654 let _ = write!(out, " {}", rendered);
1655}
1656
1657fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1664 let extra_args = if let Some(args_val) = args {
1665 args_val
1666 .as_object()
1667 .map(|obj| {
1668 obj.values()
1669 .map(|v| match v {
1670 serde_json::Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1671 serde_json::Value::Bool(true) => "true".to_string(),
1672 serde_json::Value::Bool(false) => "false".to_string(),
1673 serde_json::Value::Number(n) => n.to_string(),
1674 serde_json::Value::Null => "null".to_string(),
1675 other => format!("\"{}\"", other.to_string().replace('\\', "\\\\").replace('"', "\\\"")),
1676 })
1677 .collect::<Vec<_>>()
1678 .join(", ")
1679 })
1680 .unwrap_or_default()
1681 } else {
1682 String::new()
1683 };
1684
1685 if extra_args.is_empty() {
1686 format!("${result_var}->{method_name}()")
1687 } else {
1688 format!("${result_var}->{method_name}({extra_args})")
1689 }
1690}
1691
1692fn filter_empty_enum_strings(value: &serde_json::Value) -> serde_json::Value {
1696 match value {
1697 serde_json::Value::Object(map) => {
1698 let filtered: serde_json::Map<String, serde_json::Value> = map
1699 .iter()
1700 .filter_map(|(k, v)| {
1701 if let serde_json::Value::String(s) = v {
1703 if s.is_empty() {
1704 return None;
1705 }
1706 }
1707 Some((k.clone(), filter_empty_enum_strings(v)))
1709 })
1710 .collect();
1711 serde_json::Value::Object(filtered)
1712 }
1713 serde_json::Value::Array(arr) => {
1714 let filtered: Vec<serde_json::Value> = arr.iter().map(filter_empty_enum_strings).collect();
1715 serde_json::Value::Array(filtered)
1716 }
1717 other => other.clone(),
1718 }
1719}
1720
1721fn json_to_php(value: &serde_json::Value) -> String {
1723 match value {
1724 serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1725 serde_json::Value::Bool(true) => "true".to_string(),
1726 serde_json::Value::Bool(false) => "false".to_string(),
1727 serde_json::Value::Number(n) => n.to_string(),
1728 serde_json::Value::Null => "null".to_string(),
1729 serde_json::Value::Array(arr) => {
1730 let items: Vec<String> = arr.iter().map(json_to_php).collect();
1731 format!("[{}]", items.join(", "))
1732 }
1733 serde_json::Value::Object(map) => {
1734 let items: Vec<String> = map
1735 .iter()
1736 .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1737 .collect();
1738 format!("[{}]", items.join(", "))
1739 }
1740 }
1741}
1742
1743fn json_to_php_camel_keys(value: &serde_json::Value) -> String {
1748 match value {
1749 serde_json::Value::Object(map) => {
1750 let items: Vec<String> = map
1751 .iter()
1752 .map(|(k, v)| {
1753 let camel_key = k.to_lower_camel_case();
1754 format!("\"{}\" => {}", escape_php(&camel_key), json_to_php_camel_keys(v))
1755 })
1756 .collect();
1757 format!("[{}]", items.join(", "))
1758 }
1759 serde_json::Value::Array(arr) => {
1760 let items: Vec<String> = arr.iter().map(json_to_php_camel_keys).collect();
1761 format!("[{}]", items.join(", "))
1762 }
1763 _ => json_to_php(value),
1764 }
1765}
1766
1767fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1773 setup_lines.push("$visitor = new class {".to_string());
1774 for (method_name, action) in &visitor_spec.callbacks {
1775 emit_php_visitor_method(setup_lines, method_name, action);
1776 }
1777 setup_lines.push("};".to_string());
1778}
1779
1780fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1782 let params = match method_name {
1783 "visit_link" => "$ctx, $href, $text, $title",
1784 "visit_image" => "$ctx, $src, $alt, $title",
1785 "visit_heading" => "$ctx, $level, $text, $id",
1786 "visit_code_block" => "$ctx, $lang, $code",
1787 "visit_code_inline"
1788 | "visit_strong"
1789 | "visit_emphasis"
1790 | "visit_strikethrough"
1791 | "visit_underline"
1792 | "visit_subscript"
1793 | "visit_superscript"
1794 | "visit_mark"
1795 | "visit_button"
1796 | "visit_summary"
1797 | "visit_figcaption"
1798 | "visit_definition_term"
1799 | "visit_definition_description" => "$ctx, $text",
1800 "visit_text" => "$ctx, $text",
1801 "visit_list_item" => "$ctx, $ordered, $marker, $text",
1802 "visit_blockquote" => "$ctx, $content, $depth",
1803 "visit_table_row" => "$ctx, $cells, $isHeader",
1804 "visit_custom_element" => "$ctx, $tagName, $html",
1805 "visit_form" => "$ctx, $actionUrl, $method",
1806 "visit_input" => "$ctx, $input_type, $name, $value",
1807 "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1808 "visit_details" => "$ctx, $isOpen",
1809 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1810 "visit_list_start" => "$ctx, $ordered",
1811 "visit_list_end" => "$ctx, $ordered, $output",
1812 _ => "$ctx",
1813 };
1814
1815 let (action_type, action_value, return_form) = match action {
1816 CallbackAction::Skip => ("skip", String::new(), "dict"),
1817 CallbackAction::Continue => ("continue", String::new(), "dict"),
1818 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
1819 CallbackAction::Custom { output } => ("custom", escape_php(output), "dict"),
1820 CallbackAction::CustomTemplate { template, return_form } => {
1821 let form = match return_form {
1822 TemplateReturnForm::Dict => "dict",
1823 TemplateReturnForm::BareString => "bare_string",
1824 };
1825 ("custom_template", escape_php(template), form)
1826 }
1827 };
1828
1829 let rendered = crate::template_env::render(
1830 "php/visitor_method.jinja",
1831 minijinja::context! {
1832 method_name => method_name,
1833 params => params,
1834 action_type => action_type,
1835 action_value => action_value,
1836 return_form => return_form,
1837 },
1838 );
1839 for line in rendered.lines() {
1840 setup_lines.push(line.to_string());
1841 }
1842}
1843
1844fn is_php_reserved_type(name: &str) -> bool {
1846 matches!(
1847 name.to_ascii_lowercase().as_str(),
1848 "string"
1849 | "int"
1850 | "integer"
1851 | "float"
1852 | "double"
1853 | "bool"
1854 | "boolean"
1855 | "array"
1856 | "object"
1857 | "null"
1858 | "void"
1859 | "callable"
1860 | "iterable"
1861 | "never"
1862 | "self"
1863 | "parent"
1864 | "static"
1865 | "true"
1866 | "false"
1867 | "mixed"
1868 )
1869}