1use crate::config::E2eConfig;
8use crate::escape::{escape_php, sanitize_filename};
9use crate::field_access::FieldResolver;
10use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, HttpFixture, ValidationErrorExpectation};
11use alef_backend_php::naming::php_autoload_namespace;
12use alef_core::backend::GeneratedFile;
13use alef_core::config::ResolvedCrateConfig;
14use alef_core::hash::{self, CommentStyle};
15use alef_core::template_versions as tv;
16use anyhow::Result;
17use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
18use std::collections::HashMap;
19use std::fmt::Write as FmtWrite;
20use std::path::PathBuf;
21
22use super::E2eCodegen;
23use super::client;
24
25pub struct PhpCodegen;
27
28impl E2eCodegen for PhpCodegen {
29 fn generate(
30 &self,
31 groups: &[FixtureGroup],
32 e2e_config: &E2eConfig,
33 config: &ResolvedCrateConfig,
34 ) -> Result<Vec<GeneratedFile>> {
35 let lang = self.language_name();
36 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38 let mut files = Vec::new();
39
40 let call = &e2e_config.call;
44 let overrides = call.overrides.get(lang);
45 let extension_name = config.php_extension_name();
46 let class_name = overrides
47 .and_then(|o| o.class.as_ref())
48 .cloned()
49 .map(|cn| cn.split('\\').next_back().unwrap_or(&cn).to_string())
50 .unwrap_or_else(|| extension_name.to_upper_camel_case());
51 let namespace = overrides.and_then(|o| o.module.as_ref()).cloned().unwrap_or_else(|| {
52 if extension_name.contains('_') {
53 extension_name
54 .split('_')
55 .map(|p| p.to_upper_camel_case())
56 .collect::<Vec<_>>()
57 .join("\\")
58 } else {
59 extension_name.to_upper_camel_case()
60 }
61 });
62 let empty_enum_fields = HashMap::new();
63 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
64 let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
65 let php_client_factory = overrides.and_then(|o| o.php_client_factory.as_deref());
66 let options_via = overrides.and_then(|o| o.options_via.as_deref()).unwrap_or("array");
67
68 let php_pkg = e2e_config.resolve_package("php");
70 let pkg_name = php_pkg
71 .as_ref()
72 .and_then(|p| p.name.as_ref())
73 .cloned()
74 .unwrap_or_else(|| {
75 let org = config
78 .try_github_repo()
79 .ok()
80 .as_deref()
81 .and_then(alef_core::config::derive_repo_org)
82 .unwrap_or_else(|| config.name.clone());
83 format!("{org}/{}", call.module.replace('_', "-"))
84 });
85 let pkg_path = php_pkg
86 .as_ref()
87 .and_then(|p| p.path.as_ref())
88 .cloned()
89 .unwrap_or_else(|| "../../packages/php".to_string());
90 let pkg_version = php_pkg
91 .as_ref()
92 .and_then(|p| p.version.as_ref())
93 .cloned()
94 .or_else(|| config.resolved_version())
95 .unwrap_or_else(|| "0.1.0".to_string());
96
97 let e2e_vendor = pkg_name.split('/').next().unwrap_or(&pkg_name).to_string();
102 let e2e_pkg_name = format!("{e2e_vendor}/e2e-php");
103 let php_namespace_escaped = php_autoload_namespace(config).replace('\\', "\\\\");
108 let e2e_autoload_ns = format!("{php_namespace_escaped}\\\\E2e\\\\");
109
110 files.push(GeneratedFile {
112 path: output_base.join("composer.json"),
113 content: render_composer_json(
114 &e2e_pkg_name,
115 &e2e_autoload_ns,
116 &pkg_name,
117 &pkg_path,
118 &pkg_version,
119 e2e_config.dep_mode,
120 ),
121 generated_header: false,
122 });
123
124 files.push(GeneratedFile {
126 path: output_base.join("phpunit.xml"),
127 content: render_phpunit_xml(),
128 generated_header: false,
129 });
130
131 let has_http_fixtures = groups
134 .iter()
135 .flat_map(|g| g.fixtures.iter())
136 .any(|f| f.needs_mock_server());
137
138 let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
140 let cc = e2e_config.resolve_call(f.call.as_deref());
141 cc.args
142 .iter()
143 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
144 });
145
146 files.push(GeneratedFile {
148 path: output_base.join("bootstrap.php"),
149 content: render_bootstrap(&pkg_path, has_http_fixtures, has_file_fixtures),
150 generated_header: true,
151 });
152
153 files.push(GeneratedFile {
155 path: output_base.join("run_tests.php"),
156 content: render_run_tests_php(&extension_name, config.php_cargo_crate_name()),
157 generated_header: true,
158 });
159
160 let tests_base = output_base.join("tests");
162 let field_resolver = FieldResolver::new(
163 &e2e_config.fields,
164 &e2e_config.fields_optional,
165 &e2e_config.result_fields,
166 &e2e_config.fields_array,
167 &std::collections::HashSet::new(),
168 );
169
170 for group in groups {
171 let active: Vec<&Fixture> = group
172 .fixtures
173 .iter()
174 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
175 .collect();
176
177 if active.is_empty() {
178 continue;
179 }
180
181 let test_class = format!("{}Test", sanitize_filename(&group.category).to_upper_camel_case());
182 let filename = format!("{test_class}.php");
183 let content = render_test_file(
184 &group.category,
185 &active,
186 e2e_config,
187 lang,
188 &namespace,
189 &class_name,
190 &test_class,
191 &field_resolver,
192 enum_fields,
193 result_is_simple,
194 php_client_factory,
195 options_via,
196 );
197 files.push(GeneratedFile {
198 path: tests_base.join(filename),
199 content,
200 generated_header: true,
201 });
202 }
203
204 Ok(files)
205 }
206
207 fn language_name(&self) -> &'static str {
208 "php"
209 }
210}
211
212fn render_composer_json(
217 e2e_pkg_name: &str,
218 e2e_autoload_ns: &str,
219 pkg_name: &str,
220 pkg_path: &str,
221 pkg_version: &str,
222 dep_mode: crate::config::DependencyMode,
223) -> String {
224 let (require_section, autoload_section) = match dep_mode {
225 crate::config::DependencyMode::Registry => {
226 let require = format!(
227 r#" "require": {{
228 "{pkg_name}": "{pkg_version}"
229 }},
230 "require-dev": {{
231 "phpunit/phpunit": "{phpunit}",
232 "guzzlehttp/guzzle": "{guzzle}"
233 }},"#,
234 phpunit = tv::packagist::PHPUNIT,
235 guzzle = tv::packagist::GUZZLE,
236 );
237 (require, String::new())
238 }
239 crate::config::DependencyMode::Local => {
240 let require = format!(
241 r#" "require-dev": {{
242 "phpunit/phpunit": "{phpunit}",
243 "guzzlehttp/guzzle": "{guzzle}"
244 }},"#,
245 phpunit = tv::packagist::PHPUNIT,
246 guzzle = tv::packagist::GUZZLE,
247 );
248 let pkg_namespace = pkg_name
251 .split('/')
252 .nth(1)
253 .unwrap_or(pkg_name)
254 .split('-')
255 .map(heck::ToUpperCamelCase::to_upper_camel_case)
256 .collect::<Vec<_>>()
257 .join("\\");
258 let autoload = format!(
259 r#"
260 "autoload": {{
261 "psr-4": {{
262 "{}\\": "{}/src/"
263 }}
264 }},"#,
265 pkg_namespace.replace('\\', "\\\\"),
266 pkg_path
267 );
268 (require, autoload)
269 }
270 };
271
272 crate::template_env::render(
273 "php/composer.json.jinja",
274 minijinja::context! {
275 e2e_pkg_name => e2e_pkg_name,
276 e2e_autoload_ns => e2e_autoload_ns,
277 require_section => require_section,
278 autoload_section => autoload_section,
279 },
280 )
281}
282
283fn render_phpunit_xml() -> String {
284 crate::template_env::render("php/phpunit.xml.jinja", minijinja::context! {})
285}
286
287fn render_bootstrap(pkg_path: &str, has_http_fixtures: bool, has_file_fixtures: bool) -> String {
288 let header = hash::header(CommentStyle::DoubleSlash);
289 crate::template_env::render(
290 "php/bootstrap.php.jinja",
291 minijinja::context! {
292 header => header,
293 pkg_path => pkg_path,
294 has_http_fixtures => has_http_fixtures,
295 has_file_fixtures => has_file_fixtures,
296 },
297 )
298}
299
300fn render_run_tests_php(extension_name: &str, cargo_crate_name: Option<&str>) -> String {
301 let header = hash::header(CommentStyle::DoubleSlash);
302 let ext_lib_name = if let Some(crate_name) = cargo_crate_name {
303 format!("lib{}", crate_name.replace('-', "_"))
306 } else {
307 format!("lib{extension_name}_php")
308 };
309 format!(
310 r#"#!/usr/bin/env php
311<?php
312{header}
313declare(strict_types=1);
314
315// Determine platform-specific extension suffix.
316$extSuffix = match (PHP_OS_FAMILY) {{
317 'Darwin' => '.dylib',
318 default => '.so',
319}};
320$extPath = __DIR__ . '/../../target/release/{ext_lib_name}' . $extSuffix;
321
322// If the locally-built extension exists and we have not already restarted with it,
323// re-exec PHP with no system ini (-n) to avoid conflicts with any system-installed
324// version of the extension, then load the local build explicitly.
325if (file_exists($extPath) && !getenv('ALEF_PHP_LOCAL_EXT_LOADED')) {{
326 putenv('ALEF_PHP_LOCAL_EXT_LOADED=1');
327 $php = PHP_BINARY;
328 $phpunitPath = __DIR__ . '/vendor/bin/phpunit';
329
330 $cmd = array_merge(
331 [$php, '-n', '-d', 'extension=' . $extPath],
332 [$phpunitPath],
333 array_slice($GLOBALS['argv'], 1)
334 );
335
336 passthru(implode(' ', array_map('escapeshellarg', $cmd)), $exitCode);
337 exit($exitCode);
338}}
339
340// Extension is now loaded (via the restart above with -n flag).
341// Invoke PHPUnit normally.
342$phpunitPath = __DIR__ . '/vendor/bin/phpunit';
343if (!file_exists($phpunitPath)) {{
344 echo "PHPUnit not found at $phpunitPath. Run 'composer install' first.\n";
345 exit(1);
346}}
347
348require $phpunitPath;
349"#
350 )
351}
352
353#[allow(clippy::too_many_arguments)]
354fn render_test_file(
355 category: &str,
356 fixtures: &[&Fixture],
357 e2e_config: &E2eConfig,
358 lang: &str,
359 namespace: &str,
360 class_name: &str,
361 test_class: &str,
362 field_resolver: &FieldResolver,
363 enum_fields: &HashMap<String, String>,
364 result_is_simple: bool,
365 php_client_factory: Option<&str>,
366 options_via: &str,
367) -> String {
368 let header = hash::header(CommentStyle::DoubleSlash);
369
370 let needs_crawl_config_import = fixtures.iter().any(|f| {
372 let call = e2e_config.resolve_call(f.call.as_deref());
373 call.args.iter().filter(|a| a.arg_type == "handle").any(|a| {
374 let v = f.input.get(&a.field).unwrap_or(&serde_json::Value::Null);
375 !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
376 })
377 });
378
379 let has_http_tests = fixtures.iter().any(|f| f.is_http_test());
381
382 let mut options_type_imports: Vec<String> = fixtures
384 .iter()
385 .flat_map(|f| {
386 let call = e2e_config.resolve_call(f.call.as_deref());
387 let php_override = call.overrides.get(lang);
388 let opt_type = php_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
389 e2e_config
390 .call
391 .overrides
392 .get(lang)
393 .and_then(|o| o.options_type.as_deref())
394 });
395 let element_types: Vec<String> = call
396 .args
397 .iter()
398 .filter_map(|a| a.element_type.as_ref().map(|t| t.to_string()))
399 .filter(|t| !is_php_reserved_type(t))
400 .collect();
401 opt_type.map(|t| t.to_string()).into_iter().chain(element_types)
402 })
403 .collect::<std::collections::HashSet<_>>()
404 .into_iter()
405 .collect();
406 options_type_imports.sort();
407
408 let mut imports_use: Vec<String> = Vec::new();
410 if needs_crawl_config_import {
411 imports_use.push(format!("use {namespace}\\CrawlConfig;"));
412 }
413 for type_name in &options_type_imports {
414 if type_name != class_name {
415 imports_use.push(format!("use {namespace}\\{type_name};"));
416 }
417 }
418
419 let mut fixtures_body = String::new();
421 for (i, fixture) in fixtures.iter().enumerate() {
422 if fixture.is_http_test() {
423 render_http_test_method(&mut fixtures_body, fixture, fixture.http.as_ref().unwrap());
424 } else {
425 render_test_method(
426 &mut fixtures_body,
427 fixture,
428 e2e_config,
429 lang,
430 namespace,
431 class_name,
432 field_resolver,
433 enum_fields,
434 result_is_simple,
435 php_client_factory,
436 options_via,
437 );
438 }
439 if i + 1 < fixtures.len() {
440 fixtures_body.push('\n');
441 }
442 }
443
444 crate::template_env::render(
445 "php/test_file.jinja",
446 minijinja::context! {
447 header => header,
448 namespace => namespace,
449 class_name => class_name,
450 test_class => test_class,
451 category => category,
452 imports_use => imports_use,
453 has_http_tests => has_http_tests,
454 fixtures_body => fixtures_body,
455 },
456 )
457}
458
459struct PhpTestClientRenderer;
467
468impl client::TestClientRenderer for PhpTestClientRenderer {
469 fn language_name(&self) -> &'static str {
470 "php"
471 }
472
473 fn sanitize_test_name(&self, id: &str) -> String {
475 sanitize_filename(id)
476 }
477
478 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
484 let escaped_reason = skip_reason.map(escape_php);
485 let rendered = crate::template_env::render(
486 "php/http_test_open.jinja",
487 minijinja::context! {
488 fn_name => fn_name,
489 description => description,
490 skip_reason => escaped_reason,
491 },
492 );
493 out.push_str(&rendered);
494 }
495
496 fn render_test_close(&self, out: &mut String) {
498 let rendered = crate::template_env::render("php/http_test_close.jinja", minijinja::context! {});
499 out.push_str(&rendered);
500 }
501
502 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
507 let method = ctx.method.to_uppercase();
508
509 let mut opts: Vec<String> = Vec::new();
511
512 if let Some(body) = ctx.body {
513 let php_body = json_to_php(body);
514 opts.push(format!("'json' => {php_body}"));
515 }
516
517 let mut header_pairs: Vec<String> = Vec::new();
519 if let Some(ct) = ctx.content_type {
520 if !ctx.headers.keys().any(|k| k.to_lowercase() == "content-type") {
522 header_pairs.push(format!("\"Content-Type\" => \"{}\"", escape_php(ct)));
523 }
524 }
525 for (k, v) in ctx.headers {
526 header_pairs.push(format!("\"{}\" => \"{}\"", escape_php(k), escape_php(v)));
527 }
528 if !header_pairs.is_empty() {
529 opts.push(format!("'headers' => [{}]", header_pairs.join(", ")));
530 }
531
532 if !ctx.cookies.is_empty() {
533 let cookie_str = ctx
534 .cookies
535 .iter()
536 .map(|(k, v)| format!("{}={}", k, v))
537 .collect::<Vec<_>>()
538 .join("; ");
539 opts.push(format!("'headers' => ['Cookie' => \"{}\"]", escape_php(&cookie_str)));
540 }
541
542 if !ctx.query_params.is_empty() {
543 let pairs: Vec<String> = ctx
544 .query_params
545 .iter()
546 .map(|(k, v)| {
547 let val_str = match v {
548 serde_json::Value::String(s) => s.clone(),
549 other => other.to_string(),
550 };
551 format!("\"{}\" => \"{}\"", escape_php(k), escape_php(&val_str))
552 })
553 .collect();
554 opts.push(format!("'query' => [{}]", pairs.join(", ")));
555 }
556
557 let path_lit = format!("\"{}\"", escape_php(ctx.path));
558
559 let rendered = crate::template_env::render(
560 "php/http_request.jinja",
561 minijinja::context! {
562 method => method,
563 path => path_lit,
564 opts => opts,
565 response_var => ctx.response_var,
566 },
567 );
568 out.push_str(&rendered);
569 }
570
571 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
573 let rendered = crate::template_env::render(
574 "php/http_assertions.jinja",
575 minijinja::context! {
576 response_var => "",
577 status_code => status,
578 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
579 body_assertion => String::new(),
580 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
581 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
582 },
583 );
584 out.push_str(&rendered);
585 }
586
587 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
592 let header_key = name.to_lowercase();
593 let header_key_lit = format!("\"{}\"", escape_php(&header_key));
594 let assertion_code = match expected {
595 "<<present>>" => {
596 format!("$this->assertTrue($response->hasHeader({header_key_lit}));")
597 }
598 "<<absent>>" => {
599 format!("$this->assertFalse($response->hasHeader({header_key_lit}));")
600 }
601 "<<uuid>>" => {
602 format!(
603 "$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}));"
604 )
605 }
606 literal => {
607 let val_lit = format!("\"{}\"", escape_php(literal));
608 format!("$this->assertEquals({val_lit}, $response->getHeaderLine({header_key_lit}));")
609 }
610 };
611
612 let mut headers = vec![std::collections::HashMap::new()];
613 headers[0].insert("assertion_code", assertion_code);
614
615 let rendered = crate::template_env::render(
616 "php/http_assertions.jinja",
617 minijinja::context! {
618 response_var => "",
619 status_code => 0u16,
620 headers => headers,
621 body_assertion => String::new(),
622 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
623 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
624 },
625 );
626 out.push_str(&rendered);
627 }
628
629 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
635 let body_assertion = match expected {
636 serde_json::Value::String(s) if !s.is_empty() => {
637 let php_val = format!("\"{}\"", escape_php(s));
638 format!("$this->assertEquals({php_val}, (string) $response->getBody());")
639 }
640 _ => {
641 let php_val = json_to_php(expected);
642 format!(
643 "$body = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);\n $this->assertEquals({php_val}, $body);"
644 )
645 }
646 };
647
648 let rendered = crate::template_env::render(
649 "php/http_assertions.jinja",
650 minijinja::context! {
651 response_var => "",
652 status_code => 0u16,
653 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
654 body_assertion => body_assertion,
655 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
656 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
657 },
658 );
659 out.push_str(&rendered);
660 }
661
662 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
664 if let Some(obj) = expected.as_object() {
665 let mut partial_body: Vec<std::collections::HashMap<&str, String>> = Vec::new();
666 for (key, val) in obj {
667 let php_key = format!("\"{}\"", escape_php(key));
668 let php_val = json_to_php(val);
669 let assertion_code = format!("$this->assertEquals({php_val}, $body[{php_key}]);");
670 let mut entry = std::collections::HashMap::new();
671 entry.insert("assertion_code", assertion_code);
672 partial_body.push(entry);
673 }
674
675 let rendered = crate::template_env::render(
676 "php/http_assertions.jinja",
677 minijinja::context! {
678 response_var => "",
679 status_code => 0u16,
680 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
681 body_assertion => String::new(),
682 partial_body => partial_body,
683 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
684 },
685 );
686 out.push_str(&rendered);
687 }
688 }
689
690 fn render_assert_validation_errors(
693 &self,
694 out: &mut String,
695 _response_var: &str,
696 errors: &[ValidationErrorExpectation],
697 ) {
698 let mut validation_errors: Vec<std::collections::HashMap<&str, String>> = Vec::new();
699 for err in errors {
700 let msg_lit = format!("\"{}\"", escape_php(&err.msg));
701 let assertion_code =
702 format!("$this->assertStringContainsString({msg_lit}, json_encode($body, JSON_UNESCAPED_SLASHES));");
703 let mut entry = std::collections::HashMap::new();
704 entry.insert("assertion_code", assertion_code);
705 validation_errors.push(entry);
706 }
707
708 let rendered = crate::template_env::render(
709 "php/http_assertions.jinja",
710 minijinja::context! {
711 response_var => "",
712 status_code => 0u16,
713 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
714 body_assertion => String::new(),
715 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
716 validation_errors => validation_errors,
717 },
718 );
719 out.push_str(&rendered);
720 }
721}
722
723fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
728 if http.expected_response.status_code == 101 {
732 let method_name = sanitize_filename(&fixture.id);
733 let description = &fixture.description;
734 out.push_str(&crate::template_env::render(
735 "php/http_test_skip_101.jinja",
736 minijinja::context! {
737 method_name => method_name,
738 description => description,
739 },
740 ));
741 return;
742 }
743
744 client::http_call::render_http_test(out, &PhpTestClientRenderer, fixture);
745}
746
747#[allow(clippy::too_many_arguments)]
752fn render_test_method(
753 out: &mut String,
754 fixture: &Fixture,
755 e2e_config: &E2eConfig,
756 lang: &str,
757 namespace: &str,
758 class_name: &str,
759 field_resolver: &FieldResolver,
760 enum_fields: &HashMap<String, String>,
761 result_is_simple: bool,
762 php_client_factory: Option<&str>,
763 options_via: &str,
764) {
765 let call_config = e2e_config.resolve_call(fixture.call.as_deref());
767 let call_overrides = call_config.overrides.get(lang);
768 let has_override = call_overrides.is_some_and(|o| o.function.is_some());
769 let mut function_name = call_overrides
770 .and_then(|o| o.function.as_ref())
771 .cloned()
772 .unwrap_or_else(|| call_config.function.clone());
773 if !has_override && call_config.r#async && !function_name.ends_with("_async") {
776 function_name = format!("{function_name}_async");
777 }
778 if !has_override {
779 function_name = function_name.to_lower_camel_case();
780 }
781 let result_var = &call_config.result_var;
782 let args = &call_config.args;
783
784 let method_name = sanitize_filename(&fixture.id);
785 let description = &fixture.description;
786 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
787
788 let call_options_type = call_overrides.and_then(|o| o.options_type.as_deref()).or_else(|| {
790 e2e_config
791 .call
792 .overrides
793 .get(lang)
794 .and_then(|o| o.options_type.as_deref())
795 });
796
797 let (mut setup_lines, args_str) = build_args_and_setup(
798 &fixture.input,
799 args,
800 class_name,
801 enum_fields,
802 &fixture.id,
803 options_via,
804 call_options_type,
805 );
806
807 let skip_test = call_config.skip_languages.iter().any(|l| l == "php");
809 if skip_test {
810 let rendered = crate::template_env::render(
811 "php/test_method.jinja",
812 minijinja::context! {
813 method_name => method_name,
814 description => description,
815 client_factory => String::new(),
816 setup_lines => Vec::<String>::new(),
817 expects_error => false,
818 skip_test => true,
819 has_usable_assertions => false,
820 call_expr => String::new(),
821 result_var => result_var,
822 assertions_body => String::new(),
823 },
824 );
825 out.push_str(&rendered);
826 return;
827 }
828
829 let mut options_already_created = !args_str.is_empty() && args_str == "$options";
831 if let Some(visitor_spec) = &fixture.visitor {
832 build_php_visitor(&mut setup_lines, visitor_spec);
833 if !options_already_created {
834 setup_lines.push("$builder = \\HtmlToMarkdown\\ConversionOptions::builder();".to_string());
835 setup_lines.push("$options = $builder->visitor($visitor)->build();".to_string());
836 options_already_created = true;
837 }
838 }
839
840 let final_args = if options_already_created {
841 if args_str.is_empty() || args_str == "$options" {
842 "$options".to_string()
843 } else {
844 format!("{args_str}, $options")
845 }
846 } else {
847 args_str
848 };
849
850 let call_expr = if php_client_factory.is_some() {
851 format!("$client->{function_name}({final_args})")
852 } else {
853 format!("{class_name}::{function_name}({final_args})")
854 };
855
856 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
857 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
858 let client_factory = if let Some(factory) = php_client_factory {
859 let fixture_id = &fixture.id;
860 if has_mock {
861 format!(
862 "$client = \\{namespace}\\{class_name}::{factory}('test-key', getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}');"
863 )
864 } else if let Some(var) = api_key_var {
865 format!(
866 "$apiKey = getenv('{var}');\n if (!$apiKey) {{ $this->markTestSkipped('{var} not set'); return; }}\n $client = \\{namespace}\\{class_name}::{factory}($apiKey);"
867 )
868 } else {
869 format!("$client = \\{namespace}\\{class_name}::{factory}('test-key');")
870 }
871 } else {
872 String::new()
873 };
874
875 let has_usable_assertions = fixture.assertions.iter().any(|a| {
877 if a.assertion_type == "error" || a.assertion_type == "not_error" {
878 return false;
879 }
880 match &a.field {
881 Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
882 _ => true,
883 }
884 });
885
886 let mut assertions_body = String::new();
888 for assertion in &fixture.assertions {
889 render_assertion(
890 &mut assertions_body,
891 assertion,
892 result_var,
893 field_resolver,
894 result_is_simple,
895 call_config.result_is_array,
896 );
897 }
898
899 let rendered = crate::template_env::render(
900 "php/test_method.jinja",
901 minijinja::context! {
902 method_name => method_name,
903 description => description,
904 client_factory => client_factory,
905 setup_lines => setup_lines,
906 expects_error => expects_error,
907 skip_test => fixture.assertions.is_empty(),
908 has_usable_assertions => has_usable_assertions,
909 call_expr => call_expr,
910 result_var => result_var,
911 assertions_body => assertions_body,
912 },
913 );
914 out.push_str(&rendered);
915}
916
917fn emit_php_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
930 if let Some(items) = arr.as_array() {
931 let item_strs: Vec<String> = items
932 .iter()
933 .filter_map(|item| {
934 if let Some(obj) = item.as_object() {
935 match elem_type {
936 "BatchBytesItem" => {
937 let content = obj.get("content").and_then(|v| v.as_array());
938 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
939 let content_code = if let Some(arr) = content {
940 let bytes: Vec<String> = arr
941 .iter()
942 .filter_map(|v| v.as_u64())
943 .map(|n| format!("\\x{:02x}", n))
944 .collect();
945 format!("\"{}\"", bytes.join(""))
946 } else {
947 "\"\"".to_string()
948 };
949 Some(format!(
950 "new {}(content: {}, mimeType: \"{}\")",
951 elem_type, content_code, mime_type
952 ))
953 }
954 "BatchFileItem" => {
955 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
956 Some(format!("new {}(path: \"{}\")", elem_type, path))
957 }
958 _ => None,
959 }
960 } else {
961 None
962 }
963 })
964 .collect();
965 format!("[{}]", item_strs.join(", "))
966 } else {
967 "[]".to_string()
968 }
969}
970
971fn build_args_and_setup(
972 input: &serde_json::Value,
973 args: &[crate::config::ArgMapping],
974 class_name: &str,
975 _enum_fields: &HashMap<String, String>,
976 fixture_id: &str,
977 options_via: &str,
978 options_type: Option<&str>,
979) -> (Vec<String>, String) {
980 if args.is_empty() {
981 let is_empty_input = match input {
984 serde_json::Value::Null => true,
985 serde_json::Value::Object(m) => m.is_empty(),
986 _ => false,
987 };
988 if is_empty_input {
989 return (Vec::new(), String::new());
990 }
991 return (Vec::new(), json_to_php(input));
992 }
993
994 let mut setup_lines: Vec<String> = Vec::new();
995 let mut parts: Vec<String> = Vec::new();
996
997 let arg_has_emission = |arg: &crate::config::ArgMapping| -> bool {
1002 let val = if arg.field == "input" {
1003 Some(input)
1004 } else {
1005 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1006 input.get(field)
1007 };
1008 match val {
1009 None | Some(serde_json::Value::Null) => !arg.optional,
1010 Some(_) => true,
1011 }
1012 };
1013 let any_later_has_emission = |from_idx: usize| -> bool { args[from_idx..].iter().any(arg_has_emission) };
1014
1015 for (idx, arg) in args.iter().enumerate() {
1016 if arg.arg_type == "mock_url" {
1017 setup_lines.push(format!(
1018 "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1019 arg.name,
1020 ));
1021 parts.push(format!("${}", arg.name));
1022 continue;
1023 }
1024
1025 if arg.arg_type == "handle" {
1026 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1028 let config_value = if arg.field == "input" {
1029 input
1030 } else {
1031 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1032 input.get(field).unwrap_or(&serde_json::Value::Null)
1033 };
1034 if config_value.is_null()
1035 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1036 {
1037 setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
1038 } else {
1039 let name = &arg.name;
1040 let filtered_config = filter_empty_enum_strings(config_value);
1045 setup_lines.push(format!(
1046 "${name}_config = CrawlConfig::from_json(json_encode({}));",
1047 json_to_php(&filtered_config)
1048 ));
1049 setup_lines.push(format!(
1050 "${} = {class_name}::{constructor_name}(${name}_config);",
1051 arg.name,
1052 ));
1053 }
1054 parts.push(format!("${}", arg.name));
1055 continue;
1056 }
1057
1058 let val = if arg.field == "input" {
1059 Some(input)
1060 } else {
1061 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1062 input.get(field)
1063 };
1064
1065 if arg.arg_type == "bytes" {
1069 match val {
1070 None | Some(serde_json::Value::Null) => {
1071 if arg.optional {
1072 parts.push("null".to_string());
1073 } else {
1074 parts.push("\"\"".to_string());
1075 }
1076 }
1077 Some(serde_json::Value::String(s)) => {
1078 let var_name = format!("{}Bytes", arg.name);
1079 setup_lines.push(format!(
1080 "${var_name} = file_get_contents(\"{path}\");\n if (${var_name} === false) {{ $this->fail(\"failed to read fixture: {path}\"); }}",
1081 path = s.replace('"', "\\\"")
1082 ));
1083 parts.push(format!("${var_name}"));
1084 }
1085 Some(serde_json::Value::Array(arr)) => {
1086 let bytes: String = arr
1087 .iter()
1088 .filter_map(|v| v.as_u64())
1089 .map(|n| format!("\\x{:02x}", n))
1090 .collect();
1091 parts.push(format!("\"{bytes}\""));
1092 }
1093 Some(other) => {
1094 parts.push(json_to_php(other));
1095 }
1096 }
1097 continue;
1098 }
1099
1100 match val {
1101 None | Some(serde_json::Value::Null) if arg.arg_type == "json_object" && arg.name == "config" => {
1102 let type_name = if arg.name == "config" {
1108 "ExtractionConfig".to_string()
1109 } else {
1110 format!("{}Config", arg.name.to_upper_camel_case())
1111 };
1112 parts.push(format!("{type_name}::from_json('{{}}')"));
1113 continue;
1114 }
1115 None | Some(serde_json::Value::Null) if arg.optional => {
1116 if any_later_has_emission(idx + 1) {
1121 parts.push("null".to_string());
1122 }
1123 continue;
1124 }
1125 None | Some(serde_json::Value::Null) => {
1126 let default_val = match arg.arg_type.as_str() {
1128 "string" => "\"\"".to_string(),
1129 "int" | "integer" => "0".to_string(),
1130 "float" | "number" => "0.0".to_string(),
1131 "bool" | "boolean" => "false".to_string(),
1132 "json_object" if options_via == "json" => "null".to_string(),
1133 _ => "null".to_string(),
1134 };
1135 parts.push(default_val);
1136 }
1137 Some(v) => {
1138 if arg.arg_type == "json_object" && !v.is_null() {
1139 if let Some(elem_type) = &arg.element_type {
1141 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1142 parts.push(emit_php_batch_item_array(v, elem_type));
1143 continue;
1144 }
1145 if v.is_array() && is_php_reserved_type(elem_type) {
1149 parts.push(json_to_php(v));
1150 continue;
1151 }
1152 }
1153 match options_via {
1154 "json" => {
1155 let filtered_v = filter_empty_enum_strings(v);
1158
1159 if let serde_json::Value::Object(obj) = &filtered_v {
1161 if obj.is_empty() {
1162 parts.push("null".to_string());
1163 continue;
1164 }
1165 }
1166
1167 parts.push(format!("json_encode({})", json_to_php_camel_keys(&filtered_v)));
1168 continue;
1169 }
1170 _ => {
1171 if let Some(type_name) = options_type {
1172 let filtered_v = filter_empty_enum_strings(v);
1177
1178 if let serde_json::Value::Object(obj) = &filtered_v {
1181 if obj.is_empty() {
1182 let arg_var = format!("${}", arg.name);
1183 setup_lines.push(format!("{arg_var} = {type_name}::from_json('{{}}');"));
1184 parts.push(arg_var);
1185 continue;
1186 }
1187 }
1188
1189 let arg_var = format!("${}", arg.name);
1190 setup_lines.push(format!(
1194 "{arg_var} = {type_name}::from_json(json_encode({}));",
1195 json_to_php(&filtered_v)
1196 ));
1197 parts.push(arg_var);
1198 continue;
1199 }
1200 if let Some(obj) = v.as_object() {
1204 setup_lines.push("$builder = $this->createDefaultOptionsBuilder();".to_string());
1205 for (k, vv) in obj {
1206 let snake_key = k.to_snake_case();
1207 if snake_key == "preprocessing" {
1208 if let Some(prep_obj) = vv.as_object() {
1209 let enabled =
1210 prep_obj.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);
1211 let preset =
1212 prep_obj.get("preset").and_then(|v| v.as_str()).unwrap_or("Minimal");
1213 let remove_navigation = prep_obj
1214 .get("remove_navigation")
1215 .and_then(|v| v.as_bool())
1216 .unwrap_or(true);
1217 let remove_forms =
1218 prep_obj.get("remove_forms").and_then(|v| v.as_bool()).unwrap_or(true);
1219 setup_lines.push(format!(
1220 "$preprocessing = $this->createPreprocessingOptions({}, {}, {}, {});",
1221 if enabled { "true" } else { "false" },
1222 json_to_php(&serde_json::Value::String(preset.to_string())),
1223 if remove_navigation { "true" } else { "false" },
1224 if remove_forms { "true" } else { "false" }
1225 ));
1226 setup_lines.push(
1227 "$builder = $builder->preprocessing($preprocessing);".to_string(),
1228 );
1229 }
1230 }
1231 }
1232 setup_lines.push("$options = $builder->build();".to_string());
1233 parts.push("$options".to_string());
1234 continue;
1235 }
1236 }
1237 }
1238 }
1239 parts.push(json_to_php(v));
1240 }
1241 }
1242 }
1243
1244 (setup_lines, parts.join(", "))
1245}
1246
1247fn render_assertion(
1248 out: &mut String,
1249 assertion: &Assertion,
1250 result_var: &str,
1251 field_resolver: &FieldResolver,
1252 result_is_simple: bool,
1253 result_is_array: bool,
1254) {
1255 if let Some(f) = &assertion.field {
1258 match f.as_str() {
1259 "chunks_have_content" => {
1260 let pred = format!(
1261 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->content), true)"
1262 );
1263 out.push_str(&crate::template_env::render(
1264 "php/synthetic_assertion.jinja",
1265 minijinja::context! {
1266 assertion_kind => "chunks_content",
1267 assertion_type => assertion.assertion_type.as_str(),
1268 pred => pred,
1269 field_name => f,
1270 },
1271 ));
1272 return;
1273 }
1274 "chunks_have_embeddings" => {
1275 let pred = format!(
1276 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->embedding), true)"
1277 );
1278 out.push_str(&crate::template_env::render(
1279 "php/synthetic_assertion.jinja",
1280 minijinja::context! {
1281 assertion_kind => "chunks_embeddings",
1282 assertion_type => assertion.assertion_type.as_str(),
1283 pred => pred,
1284 field_name => f,
1285 },
1286 ));
1287 return;
1288 }
1289 "embeddings" => {
1293 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1294 out.push_str(&crate::template_env::render(
1295 "php/synthetic_assertion.jinja",
1296 minijinja::context! {
1297 assertion_kind => "embeddings",
1298 assertion_type => assertion.assertion_type.as_str(),
1299 php_val => php_val,
1300 result_var => result_var,
1301 },
1302 ));
1303 return;
1304 }
1305 "embedding_dimensions" => {
1306 let expr = format!("(empty(${result_var}) ? 0 : count(${result_var}[0]))");
1307 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1308 out.push_str(&crate::template_env::render(
1309 "php/synthetic_assertion.jinja",
1310 minijinja::context! {
1311 assertion_kind => "embedding_dimensions",
1312 assertion_type => assertion.assertion_type.as_str(),
1313 expr => expr,
1314 php_val => php_val,
1315 },
1316 ));
1317 return;
1318 }
1319 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1320 let pred = match f.as_str() {
1321 "embeddings_valid" => {
1322 format!("array_reduce(${result_var}, fn($carry, $e) => $carry && count($e) > 0, true)")
1323 }
1324 "embeddings_finite" => {
1325 format!(
1326 "array_reduce(${result_var}, fn($carry, $e) => $carry && array_reduce($e, fn($c, $v) => $c && is_finite($v), true), true)"
1327 )
1328 }
1329 "embeddings_non_zero" => {
1330 format!(
1331 "array_reduce(${result_var}, fn($carry, $e) => $carry && count(array_filter($e, fn($v) => $v !== 0.0)) > 0, true)"
1332 )
1333 }
1334 "embeddings_normalized" => {
1335 format!(
1336 "array_reduce(${result_var}, fn($carry, $e) => $carry && abs(array_sum(array_map(fn($v) => $v * $v, $e)) - 1.0) < 1e-3, true)"
1337 )
1338 }
1339 _ => unreachable!(),
1340 };
1341 let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1342 out.push_str(&crate::template_env::render(
1343 "php/synthetic_assertion.jinja",
1344 minijinja::context! {
1345 assertion_kind => assertion_kind,
1346 assertion_type => assertion.assertion_type.as_str(),
1347 pred => pred,
1348 field_name => f,
1349 },
1350 ));
1351 return;
1352 }
1353 "keywords" | "keywords_count" => {
1356 out.push_str(&crate::template_env::render(
1357 "php/synthetic_assertion.jinja",
1358 minijinja::context! {
1359 assertion_kind => "keywords",
1360 field_name => f,
1361 },
1362 ));
1363 return;
1364 }
1365 _ => {}
1366 }
1367 }
1368
1369 if let Some(f) = &assertion.field {
1371 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1372 out.push_str(&crate::template_env::render(
1373 "php/synthetic_assertion.jinja",
1374 minijinja::context! {
1375 assertion_kind => "skipped",
1376 field_name => f,
1377 },
1378 ));
1379 return;
1380 }
1381 }
1382
1383 if result_is_simple {
1386 if let Some(f) = &assertion.field {
1387 let f_lower = f.to_lowercase();
1388 if !f.is_empty()
1389 && f_lower != "content"
1390 && (f_lower.starts_with("metadata")
1391 || f_lower.starts_with("document")
1392 || f_lower.starts_with("structure"))
1393 {
1394 out.push_str(&crate::template_env::render(
1395 "php/synthetic_assertion.jinja",
1396 minijinja::context! {
1397 assertion_kind => "result_is_simple",
1398 field_name => f,
1399 },
1400 ));
1401 return;
1402 }
1403 }
1404 }
1405
1406 let field_expr = match &assertion.field {
1407 Some(f) if !f.is_empty() => field_resolver.accessor(f, "php", &format!("${result_var}")),
1408 _ if result_is_simple => {
1409 field_resolver.accessor("content", "php", &format!("${result_var}"))
1411 }
1412 _ => format!("${result_var}"),
1413 };
1414
1415 let field_is_array = assertion.field.as_ref().map_or(result_is_array, |f| {
1418 if f.is_empty() {
1419 result_is_array
1420 } else {
1421 field_resolver.is_array(f)
1422 }
1423 });
1424
1425 let trimmed_field_expr_for = |expected: &serde_json::Value| -> String {
1429 if expected.is_string() {
1430 format!("trim({})", field_expr)
1431 } else {
1432 field_expr.clone()
1433 }
1434 };
1435
1436 let assertion_type = assertion.assertion_type.as_str();
1438 let has_php_val = assertion.value.is_some();
1439 let php_val = match assertion.value.as_ref() {
1443 Some(v) => json_to_php(v),
1444 None if assertion_type == "equals" => "null".to_string(),
1445 None => String::new(),
1446 };
1447 let trimmed_field_expr = trimmed_field_expr_for(assertion.value.as_ref().unwrap_or(&serde_json::Value::Null));
1448 let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1449 let values_php: Vec<String> = assertion
1450 .values
1451 .as_ref()
1452 .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1453 let contains_any_checks: Vec<String> = assertion
1454 .values
1455 .as_ref()
1456 .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1457 let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1458
1459 let call_expr = if let Some(method_name) = &assertion.method {
1461 build_php_method_call(result_var, method_name, assertion.args.as_ref())
1462 } else {
1463 String::new()
1464 };
1465 let check = assertion.check.as_deref().unwrap_or("is_true");
1466 let has_php_check_val = matches!(assertion.assertion_type.as_str(), "method_result") && assertion.value.is_some();
1467 let php_check_val = if matches!(assertion.assertion_type.as_str(), "method_result") {
1468 assertion.value.as_ref().map(json_to_php).unwrap_or_default()
1469 } else {
1470 String::new()
1471 };
1472 let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1473 let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1474 let bool_is_true = assertion.value.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
1475
1476 if matches!(assertion_type, "not_error" | "error") {
1478 if assertion_type == "not_error" {
1479 }
1481 return;
1483 }
1484
1485 let rendered = crate::template_env::render(
1486 "php/assertion.jinja",
1487 minijinja::context! {
1488 assertion_type => assertion_type,
1489 field_expr => field_expr,
1490 php_val => php_val,
1491 has_php_val => has_php_val,
1492 trimmed_field_expr => trimmed_field_expr,
1493 is_string_val => is_string_val,
1494 field_is_array => field_is_array,
1495 values_php => values_php,
1496 contains_any_checks => contains_any_checks,
1497 n => n,
1498 call_expr => call_expr,
1499 check => check,
1500 php_check_val => php_check_val,
1501 has_php_check_val => has_php_check_val,
1502 check_n => check_n,
1503 is_bool_val => is_bool_val,
1504 bool_is_true => bool_is_true,
1505 },
1506 );
1507 let _ = write!(out, " {}", rendered);
1508}
1509
1510fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1517 let extra_args = if let Some(args_val) = args {
1518 args_val
1519 .as_object()
1520 .map(|obj| {
1521 obj.values()
1522 .map(|v| match v {
1523 serde_json::Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1524 serde_json::Value::Bool(true) => "true".to_string(),
1525 serde_json::Value::Bool(false) => "false".to_string(),
1526 serde_json::Value::Number(n) => n.to_string(),
1527 serde_json::Value::Null => "null".to_string(),
1528 other => format!("\"{}\"", other.to_string().replace('\\', "\\\\").replace('"', "\\\"")),
1529 })
1530 .collect::<Vec<_>>()
1531 .join(", ")
1532 })
1533 .unwrap_or_default()
1534 } else {
1535 String::new()
1536 };
1537
1538 if extra_args.is_empty() {
1539 format!("${result_var}->{method_name}()")
1540 } else {
1541 format!("${result_var}->{method_name}({extra_args})")
1542 }
1543}
1544
1545fn filter_empty_enum_strings(value: &serde_json::Value) -> serde_json::Value {
1549 match value {
1550 serde_json::Value::Object(map) => {
1551 let filtered: serde_json::Map<String, serde_json::Value> = map
1552 .iter()
1553 .filter_map(|(k, v)| {
1554 if let serde_json::Value::String(s) = v {
1556 if s.is_empty() {
1557 return None;
1558 }
1559 }
1560 Some((k.clone(), filter_empty_enum_strings(v)))
1562 })
1563 .collect();
1564 serde_json::Value::Object(filtered)
1565 }
1566 serde_json::Value::Array(arr) => {
1567 let filtered: Vec<serde_json::Value> = arr.iter().map(filter_empty_enum_strings).collect();
1568 serde_json::Value::Array(filtered)
1569 }
1570 other => other.clone(),
1571 }
1572}
1573
1574fn json_to_php(value: &serde_json::Value) -> String {
1576 match value {
1577 serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1578 serde_json::Value::Bool(true) => "true".to_string(),
1579 serde_json::Value::Bool(false) => "false".to_string(),
1580 serde_json::Value::Number(n) => n.to_string(),
1581 serde_json::Value::Null => "null".to_string(),
1582 serde_json::Value::Array(arr) => {
1583 let items: Vec<String> = arr.iter().map(json_to_php).collect();
1584 format!("[{}]", items.join(", "))
1585 }
1586 serde_json::Value::Object(map) => {
1587 let items: Vec<String> = map
1588 .iter()
1589 .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1590 .collect();
1591 format!("[{}]", items.join(", "))
1592 }
1593 }
1594}
1595
1596fn json_to_php_camel_keys(value: &serde_json::Value) -> String {
1601 match value {
1602 serde_json::Value::Object(map) => {
1603 let items: Vec<String> = map
1604 .iter()
1605 .map(|(k, v)| {
1606 let camel_key = k.to_lower_camel_case();
1607 format!("\"{}\" => {}", escape_php(&camel_key), json_to_php_camel_keys(v))
1608 })
1609 .collect();
1610 format!("[{}]", items.join(", "))
1611 }
1612 serde_json::Value::Array(arr) => {
1613 let items: Vec<String> = arr.iter().map(json_to_php_camel_keys).collect();
1614 format!("[{}]", items.join(", "))
1615 }
1616 _ => json_to_php(value),
1617 }
1618}
1619
1620fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1626 setup_lines.push("$visitor = new class {".to_string());
1627 for (method_name, action) in &visitor_spec.callbacks {
1628 emit_php_visitor_method(setup_lines, method_name, action);
1629 }
1630 setup_lines.push("};".to_string());
1631}
1632
1633fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
1635 let params = match method_name {
1636 "visit_link" => "$ctx, $href, $text, $title",
1637 "visit_image" => "$ctx, $src, $alt, $title",
1638 "visit_heading" => "$ctx, $level, $text, $id",
1639 "visit_code_block" => "$ctx, $lang, $code",
1640 "visit_code_inline"
1641 | "visit_strong"
1642 | "visit_emphasis"
1643 | "visit_strikethrough"
1644 | "visit_underline"
1645 | "visit_subscript"
1646 | "visit_superscript"
1647 | "visit_mark"
1648 | "visit_button"
1649 | "visit_summary"
1650 | "visit_figcaption"
1651 | "visit_definition_term"
1652 | "visit_definition_description" => "$ctx, $text",
1653 "visit_text" => "$ctx, $text",
1654 "visit_list_item" => "$ctx, $ordered, $marker, $text",
1655 "visit_blockquote" => "$ctx, $content, $depth",
1656 "visit_table_row" => "$ctx, $cells, $isHeader",
1657 "visit_custom_element" => "$ctx, $tagName, $html",
1658 "visit_form" => "$ctx, $actionUrl, $method",
1659 "visit_input" => "$ctx, $input_type, $name, $value",
1660 "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
1661 "visit_details" => "$ctx, $isOpen",
1662 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
1663 "visit_list_start" => "$ctx, $ordered",
1664 "visit_list_end" => "$ctx, $ordered, $output",
1665 _ => "$ctx",
1666 };
1667
1668 let (action_type, action_value) = match action {
1669 CallbackAction::Skip => ("skip", String::new()),
1670 CallbackAction::Continue => ("continue", String::new()),
1671 CallbackAction::PreserveHtml => ("preserve_html", String::new()),
1672 CallbackAction::Custom { output } => ("custom", escape_php(output)),
1673 CallbackAction::CustomTemplate { template } => ("custom_template", escape_php(template)),
1674 };
1675
1676 let rendered = crate::template_env::render(
1677 "php/visitor_method.jinja",
1678 minijinja::context! {
1679 method_name => method_name,
1680 params => params,
1681 action_type => action_type,
1682 action_value => action_value,
1683 },
1684 );
1685 for line in rendered.lines() {
1686 setup_lines.push(line.to_string());
1687 }
1688}
1689
1690fn is_php_reserved_type(name: &str) -> bool {
1692 matches!(
1693 name.to_ascii_lowercase().as_str(),
1694 "string"
1695 | "int"
1696 | "integer"
1697 | "float"
1698 | "double"
1699 | "bool"
1700 | "boolean"
1701 | "array"
1702 | "object"
1703 | "null"
1704 | "void"
1705 | "callable"
1706 | "iterable"
1707 | "never"
1708 | "self"
1709 | "parent"
1710 | "static"
1711 | "true"
1712 | "false"
1713 | "mixed"
1714 )
1715}