1use crate::config::E2eConfig;
8use crate::escape::{escape_php, sanitize_filename};
9use crate::field_access::{FieldResolver, PhpGetterMap};
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::ir::TypeRef;
18use alef_core::template_versions as tv;
19use anyhow::Result;
20use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
21use std::collections::{HashMap, HashSet};
22use std::fmt::Write as FmtWrite;
23use std::path::PathBuf;
24
25use super::E2eCodegen;
26use super::client;
27
28pub struct PhpCodegen;
30
31impl E2eCodegen for PhpCodegen {
32 fn generate(
33 &self,
34 groups: &[FixtureGroup],
35 e2e_config: &E2eConfig,
36 config: &ResolvedCrateConfig,
37 type_defs: &[alef_core::ir::TypeDef],
38 enums: &[alef_core::ir::EnumDef],
39 ) -> Result<Vec<GeneratedFile>> {
40 let lang = self.language_name();
41 let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
42
43 let mut files = Vec::new();
44
45 let call = &e2e_config.call;
49 let overrides = call.overrides.get(lang);
50 let extension_name = config.php_extension_name();
51 let class_name = overrides
52 .and_then(|o| o.class.as_ref())
53 .cloned()
54 .map(|cn| cn.split('\\').next_back().unwrap_or(&cn).to_string())
55 .unwrap_or_else(|| extension_name.to_upper_camel_case());
56 let namespace = overrides.and_then(|o| o.module.as_ref()).cloned().unwrap_or_else(|| {
57 if extension_name.contains('_') {
58 extension_name
59 .split('_')
60 .map(|p| p.to_upper_camel_case())
61 .collect::<Vec<_>>()
62 .join("\\")
63 } else {
64 extension_name.to_upper_camel_case()
65 }
66 });
67 let empty_enum_fields = HashMap::new();
68 let enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&empty_enum_fields);
69 let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
70 let php_client_factory = overrides.and_then(|o| o.php_client_factory.as_deref());
71 let options_via = overrides.and_then(|o| o.options_via.as_deref()).unwrap_or("array");
72
73 let php_pkg = e2e_config.resolve_package("php");
75 let pkg_name = php_pkg
76 .as_ref()
77 .and_then(|p| p.name.as_ref())
78 .cloned()
79 .unwrap_or_else(|| {
80 let org = config
83 .try_github_repo()
84 .ok()
85 .as_deref()
86 .and_then(alef_core::config::derive_repo_org)
87 .unwrap_or_else(|| config.name.clone());
88 format!("{org}/{}", call.module.replace('_', "-"))
89 });
90 let pkg_path = php_pkg
91 .as_ref()
92 .and_then(|p| p.path.as_ref())
93 .cloned()
94 .unwrap_or_else(|| "../../packages/php".to_string());
95 let pkg_version = php_pkg
96 .as_ref()
97 .and_then(|p| p.version.as_ref())
98 .cloned()
99 .or_else(|| config.resolved_version())
100 .unwrap_or_else(|| "0.1.0".to_string());
101
102 let e2e_vendor = pkg_name.split('/').next().unwrap_or(&pkg_name).to_string();
107 let e2e_pkg_name = format!("{e2e_vendor}/e2e-php");
108 let php_namespace_escaped = php_autoload_namespace(config).replace('\\', "\\\\");
113 let e2e_autoload_ns = format!("{php_namespace_escaped}\\\\E2e\\\\");
114
115 files.push(GeneratedFile {
117 path: output_base.join("composer.json"),
118 content: render_composer_json(
119 &e2e_pkg_name,
120 &e2e_autoload_ns,
121 &pkg_name,
122 &pkg_path,
123 &pkg_version,
124 e2e_config.dep_mode,
125 ),
126 generated_header: false,
127 });
128
129 files.push(GeneratedFile {
131 path: output_base.join("phpunit.xml"),
132 content: render_phpunit_xml(),
133 generated_header: false,
134 });
135
136 let has_http_fixtures = groups
139 .iter()
140 .flat_map(|g| g.fixtures.iter())
141 .any(|f| f.needs_mock_server());
142
143 let has_file_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| {
145 let cc = e2e_config.resolve_call_for_fixture(
146 f.call.as_deref(),
147 &f.id,
148 &f.resolved_category(),
149 &f.tags,
150 &f.input,
151 );
152 cc.args
153 .iter()
154 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
155 });
156
157 files.push(GeneratedFile {
159 path: output_base.join("bootstrap.php"),
160 content: render_bootstrap(
161 &pkg_path,
162 has_http_fixtures,
163 has_file_fixtures,
164 &e2e_config.test_documents_relative_from(0),
165 ),
166 generated_header: true,
167 });
168
169 files.push(GeneratedFile {
171 path: output_base.join("run_tests.php"),
172 content: render_run_tests_php(&extension_name, config.php_cargo_crate_name()),
173 generated_header: true,
174 });
175
176 let tests_base = output_base.join("tests");
178
179 let php_enum_names: HashSet<String> = enums.iter().map(|e| e.name.clone()).collect();
193
194 for group in groups {
195 let active: Vec<&Fixture> = group
196 .fixtures
197 .iter()
198 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
199 .collect();
200
201 if active.is_empty() {
202 continue;
203 }
204
205 let test_class = format!("{}Test", sanitize_filename(&group.category).to_upper_camel_case());
206 let filename = format!("{test_class}.php");
207 let content = render_test_file(
208 &group.category,
209 &active,
210 e2e_config,
211 lang,
212 &namespace,
213 &class_name,
214 &test_class,
215 type_defs,
216 &php_enum_names,
217 enum_fields,
218 result_is_simple,
219 php_client_factory,
220 options_via,
221 &config.adapters,
222 );
223 files.push(GeneratedFile {
224 path: tests_base.join(filename),
225 content,
226 generated_header: true,
227 });
228 }
229
230 Ok(files)
231 }
232
233 fn language_name(&self) -> &'static str {
234 "php"
235 }
236}
237
238fn build_php_getter_map(
264 type_defs: &[alef_core::ir::TypeDef],
265 enum_names: &HashSet<String>,
266 call: &alef_core::config::e2e::CallConfig,
267 result_fields: &HashSet<String>,
268) -> PhpGetterMap {
269 let mut getters: HashMap<String, HashSet<String>> = HashMap::new();
270 let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
271 let mut all_fields: HashMap<String, HashSet<String>> = HashMap::new();
272 for td in type_defs {
273 let mut getter_fields: HashSet<String> = HashSet::new();
274 let mut field_type_map: HashMap<String, String> = HashMap::new();
275 let mut td_all_fields: HashSet<String> = HashSet::new();
276 for f in &td.fields {
277 td_all_fields.insert(f.name.clone());
278 if !is_php_scalar(&f.ty, enum_names) {
279 getter_fields.insert(f.name.clone());
280 }
281 if let Some(named) = inner_named(&f.ty) {
282 field_type_map.insert(f.name.clone(), named);
283 }
284 }
285 getters.insert(td.name.clone(), getter_fields);
286 all_fields.insert(td.name.clone(), td_all_fields);
287 if !field_type_map.is_empty() {
288 field_types.insert(td.name.clone(), field_type_map);
289 }
290 }
291 let root_type = derive_root_type(call, type_defs, result_fields);
292 PhpGetterMap {
293 getters,
294 field_types,
295 root_type,
296 all_fields,
297 }
298}
299
300fn inner_named(ty: &TypeRef) -> Option<String> {
303 match ty {
304 TypeRef::Named(n) => Some(n.clone()),
305 TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
306 _ => None,
307 }
308}
309
310fn derive_root_type(
321 call: &alef_core::config::e2e::CallConfig,
322 type_defs: &[alef_core::ir::TypeDef],
323 result_fields: &HashSet<String>,
324) -> Option<String> {
325 const LOOKUP_LANGS: &[&str] = &["php", "c", "csharp", "java", "kotlin", "go"];
326 for lang in LOOKUP_LANGS {
327 if let Some(o) = call.overrides.get(*lang)
328 && let Some(rt) = o.result_type.as_deref()
329 && !rt.is_empty()
330 && type_defs.iter().any(|td| td.name == rt)
331 {
332 return Some(rt.to_string());
333 }
334 }
335 if result_fields.is_empty() {
336 return None;
337 }
338 let matches: Vec<&alef_core::ir::TypeDef> = type_defs
339 .iter()
340 .filter(|td| {
341 let names: HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
342 result_fields.iter().all(|rf| names.contains(rf.as_str()))
343 })
344 .collect();
345 if matches.len() == 1 {
346 return Some(matches[0].name.clone());
347 }
348 None
349}
350
351fn is_php_scalar(ty: &TypeRef, enum_names: &HashSet<String>) -> bool {
352 match ty {
353 TypeRef::Primitive(_) | TypeRef::String | TypeRef::Char | TypeRef::Duration | TypeRef::Path => true,
354 TypeRef::Optional(inner) => is_php_scalar(inner, enum_names),
355 TypeRef::Vec(inner) => {
356 matches!(inner.as_ref(), TypeRef::Primitive(_) | TypeRef::String | TypeRef::Char)
357 || matches!(inner.as_ref(), TypeRef::Named(n) if enum_names.contains(n))
358 }
359 TypeRef::Named(n) if enum_names.contains(n) => true,
360 TypeRef::Named(_) | TypeRef::Map(_, _) | TypeRef::Json | TypeRef::Bytes | TypeRef::Unit => false,
361 }
362}
363
364fn render_composer_json(
369 e2e_pkg_name: &str,
370 e2e_autoload_ns: &str,
371 pkg_name: &str,
372 pkg_path: &str,
373 pkg_version: &str,
374 dep_mode: crate::config::DependencyMode,
375) -> String {
376 let (require_section, autoload_section) = match dep_mode {
377 crate::config::DependencyMode::Registry => {
378 let require = format!(
379 r#" "require": {{
380 "{pkg_name}": "{pkg_version}"
381 }},
382 "require-dev": {{
383 "phpunit/phpunit": "{phpunit}",
384 "guzzlehttp/guzzle": "{guzzle}"
385 }},"#,
386 phpunit = tv::packagist::PHPUNIT,
387 guzzle = tv::packagist::GUZZLE,
388 );
389 (require, String::new())
390 }
391 crate::config::DependencyMode::Local => {
392 let require = format!(
393 r#" "require-dev": {{
394 "phpunit/phpunit": "{phpunit}",
395 "guzzlehttp/guzzle": "{guzzle}"
396 }},"#,
397 phpunit = tv::packagist::PHPUNIT,
398 guzzle = tv::packagist::GUZZLE,
399 );
400 let pkg_namespace = pkg_name
403 .split('/')
404 .nth(1)
405 .unwrap_or(pkg_name)
406 .split('-')
407 .map(heck::ToUpperCamelCase::to_upper_camel_case)
408 .collect::<Vec<_>>()
409 .join("\\");
410 let autoload = format!(
411 r#"
412 "autoload": {{
413 "psr-4": {{
414 "{}\\": "{}/src/"
415 }}
416 }},"#,
417 pkg_namespace.replace('\\', "\\\\"),
418 pkg_path
419 );
420 (require, autoload)
421 }
422 };
423
424 crate::template_env::render(
425 "php/composer.json.jinja",
426 minijinja::context! {
427 e2e_pkg_name => e2e_pkg_name,
428 e2e_autoload_ns => e2e_autoload_ns,
429 require_section => require_section,
430 autoload_section => autoload_section,
431 },
432 )
433}
434
435fn render_phpunit_xml() -> String {
436 crate::template_env::render("php/phpunit.xml.jinja", minijinja::context! {})
437}
438
439fn render_bootstrap(
440 pkg_path: &str,
441 has_http_fixtures: bool,
442 has_file_fixtures: bool,
443 test_documents_path: &str,
444) -> String {
445 let header = hash::header(CommentStyle::DoubleSlash);
446 crate::template_env::render(
447 "php/bootstrap.php.jinja",
448 minijinja::context! {
449 header => header,
450 pkg_path => pkg_path,
451 has_http_fixtures => has_http_fixtures,
452 has_file_fixtures => has_file_fixtures,
453 test_documents_path => test_documents_path,
454 },
455 )
456}
457
458fn render_run_tests_php(extension_name: &str, cargo_crate_name: Option<&str>) -> String {
459 let header = hash::header(CommentStyle::DoubleSlash);
460 let ext_lib_name = if let Some(crate_name) = cargo_crate_name {
461 format!("lib{}", crate_name.replace('-', "_"))
464 } else {
465 format!("lib{extension_name}_php")
466 };
467 format!(
468 r#"#!/usr/bin/env php
469<?php
470{header}
471declare(strict_types=1);
472
473// Determine platform-specific extension suffix.
474$extSuffix = match (PHP_OS_FAMILY) {{
475 'Darwin' => '.dylib',
476 default => '.so',
477}};
478$extPath = __DIR__ . '/../../target/release/{ext_lib_name}' . $extSuffix;
479
480// If the locally-built extension exists and we have not already restarted with it,
481// re-exec PHP with no system ini (-n) to avoid conflicts with any system-installed
482// version of the extension, then load the local build explicitly.
483if (file_exists($extPath) && !getenv('ALEF_PHP_LOCAL_EXT_LOADED')) {{
484 putenv('ALEF_PHP_LOCAL_EXT_LOADED=1');
485 $php = PHP_BINARY;
486 $phpunitPath = __DIR__ . '/vendor/bin/phpunit';
487
488 $cmd = array_merge(
489 [$php, '-n', '-d', 'extension=' . $extPath],
490 [$phpunitPath],
491 array_slice($GLOBALS['argv'], 1)
492 );
493
494 passthru(implode(' ', array_map('escapeshellarg', $cmd)), $exitCode);
495 exit($exitCode);
496}}
497
498// Extension is now loaded (via the restart above with -n flag).
499// Invoke PHPUnit normally.
500$phpunitPath = __DIR__ . '/vendor/bin/phpunit';
501if (!file_exists($phpunitPath)) {{
502 echo "PHPUnit not found at $phpunitPath. Run 'composer install' first.\n";
503 exit(1);
504}}
505
506require $phpunitPath;
507"#
508 )
509}
510
511#[allow(clippy::too_many_arguments)]
512fn render_test_file(
513 category: &str,
514 fixtures: &[&Fixture],
515 e2e_config: &E2eConfig,
516 lang: &str,
517 namespace: &str,
518 class_name: &str,
519 test_class: &str,
520 type_defs: &[alef_core::ir::TypeDef],
521 php_enum_names: &HashSet<String>,
522 enum_fields: &HashMap<String, String>,
523 result_is_simple: bool,
524 php_client_factory: Option<&str>,
525 options_via: &str,
526 adapters: &[alef_core::config::extras::AdapterConfig],
527) -> String {
528 let header = hash::header(CommentStyle::DoubleSlash);
529
530 let needs_crawl_config_import = fixtures.iter().any(|f| {
532 let call =
533 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
534 call.args.iter().filter(|a| a.arg_type == "handle").any(|a| {
535 let v = f.input.get(&a.field).unwrap_or(&serde_json::Value::Null);
536 !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty()))
537 })
538 });
539
540 let has_http_tests = fixtures.iter().any(|f| f.is_http_test());
542
543 let mut options_type_imports: Vec<String> = fixtures
545 .iter()
546 .flat_map(|f| {
547 let call = e2e_config.resolve_call_for_fixture(
548 f.call.as_deref(),
549 &f.id,
550 &f.resolved_category(),
551 &f.tags,
552 &f.input,
553 );
554 let php_override = call.overrides.get(lang);
555 let opt_type = php_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
556 e2e_config
557 .call
558 .overrides
559 .get(lang)
560 .and_then(|o| o.options_type.as_deref())
561 });
562 let element_types: Vec<String> = call
563 .args
564 .iter()
565 .filter_map(|a| a.element_type.as_ref().map(|t| t.to_string()))
566 .filter(|t| !is_php_reserved_type(t))
567 .collect();
568 opt_type.map(|t| t.to_string()).into_iter().chain(element_types)
569 })
570 .collect::<std::collections::HashSet<_>>()
571 .into_iter()
572 .collect();
573 options_type_imports.sort();
574
575 let mut imports_use: Vec<String> = Vec::new();
577 if needs_crawl_config_import {
578 imports_use.push(format!("use {namespace}\\CrawlConfig;"));
579 }
580 for type_name in &options_type_imports {
581 if type_name != class_name {
582 imports_use.push(format!("use {namespace}\\{type_name};"));
583 }
584 }
585
586 let mut fixtures_body = String::new();
588 for (i, fixture) in fixtures.iter().enumerate() {
589 if fixture.is_http_test() {
590 render_http_test_method(&mut fixtures_body, fixture, fixture.http.as_ref().unwrap());
591 } else {
592 render_test_method(
593 &mut fixtures_body,
594 fixture,
595 e2e_config,
596 lang,
597 namespace,
598 class_name,
599 type_defs,
600 php_enum_names,
601 enum_fields,
602 result_is_simple,
603 php_client_factory,
604 options_via,
605 adapters,
606 );
607 }
608 if i + 1 < fixtures.len() {
609 fixtures_body.push('\n');
610 }
611 }
612
613 crate::template_env::render(
614 "php/test_file.jinja",
615 minijinja::context! {
616 header => header,
617 namespace => namespace,
618 class_name => class_name,
619 test_class => test_class,
620 category => category,
621 imports_use => imports_use,
622 has_http_tests => has_http_tests,
623 fixtures_body => fixtures_body,
624 },
625 )
626}
627
628struct PhpTestClientRenderer;
636
637impl client::TestClientRenderer for PhpTestClientRenderer {
638 fn language_name(&self) -> &'static str {
639 "php"
640 }
641
642 fn sanitize_test_name(&self, id: &str) -> String {
644 sanitize_filename(id)
645 }
646
647 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
653 let escaped_reason = skip_reason.map(escape_php);
654 let rendered = crate::template_env::render(
655 "php/http_test_open.jinja",
656 minijinja::context! {
657 fn_name => fn_name,
658 description => description,
659 skip_reason => escaped_reason,
660 },
661 );
662 out.push_str(&rendered);
663 }
664
665 fn render_test_close(&self, out: &mut String) {
667 let rendered = crate::template_env::render("php/http_test_close.jinja", minijinja::context! {});
668 out.push_str(&rendered);
669 }
670
671 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
676 let method = ctx.method.to_uppercase();
677
678 let mut opts: Vec<String> = Vec::new();
680
681 if let Some(body) = ctx.body {
682 let php_body = json_to_php(body);
683 opts.push(format!("'json' => {php_body}"));
684 }
685
686 let mut header_pairs: Vec<String> = Vec::new();
688 if let Some(ct) = ctx.content_type {
689 if !ctx.headers.keys().any(|k| k.to_lowercase() == "content-type") {
691 header_pairs.push(format!("\"Content-Type\" => \"{}\"", escape_php(ct)));
692 }
693 }
694 for (k, v) in ctx.headers {
695 header_pairs.push(format!("\"{}\" => \"{}\"", escape_php(k), escape_php(v)));
696 }
697 if !header_pairs.is_empty() {
698 opts.push(format!("'headers' => [{}]", header_pairs.join(", ")));
699 }
700
701 if !ctx.cookies.is_empty() {
702 let cookie_str = ctx
703 .cookies
704 .iter()
705 .map(|(k, v)| format!("{}={}", k, v))
706 .collect::<Vec<_>>()
707 .join("; ");
708 opts.push(format!("'headers' => ['Cookie' => \"{}\"]", escape_php(&cookie_str)));
709 }
710
711 if !ctx.query_params.is_empty() {
712 let pairs: Vec<String> = ctx
713 .query_params
714 .iter()
715 .map(|(k, v)| {
716 let val_str = match v {
717 serde_json::Value::String(s) => s.clone(),
718 other => other.to_string(),
719 };
720 format!("\"{}\" => \"{}\"", escape_php(k), escape_php(&val_str))
721 })
722 .collect();
723 opts.push(format!("'query' => [{}]", pairs.join(", ")));
724 }
725
726 let path_lit = format!("\"{}\"", escape_php(ctx.path));
727
728 let rendered = crate::template_env::render(
729 "php/http_request.jinja",
730 minijinja::context! {
731 method => method,
732 path => path_lit,
733 opts => opts,
734 response_var => ctx.response_var,
735 },
736 );
737 out.push_str(&rendered);
738 }
739
740 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
742 let rendered = crate::template_env::render(
743 "php/http_assertions.jinja",
744 minijinja::context! {
745 response_var => "",
746 status_code => status,
747 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
748 body_assertion => String::new(),
749 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
750 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
751 },
752 );
753 out.push_str(&rendered);
754 }
755
756 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
761 let header_key = name.to_lowercase();
762 let header_key_lit = format!("\"{}\"", escape_php(&header_key));
763 let assertion_code = match expected {
764 "<<present>>" => {
765 format!("$this->assertTrue($response->hasHeader({header_key_lit}));")
766 }
767 "<<absent>>" => {
768 format!("$this->assertFalse($response->hasHeader({header_key_lit}));")
769 }
770 "<<uuid>>" => {
771 format!(
772 "$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}));"
773 )
774 }
775 literal => {
776 let val_lit = format!("\"{}\"", escape_php(literal));
777 format!("$this->assertEquals({val_lit}, $response->getHeaderLine({header_key_lit}));")
778 }
779 };
780
781 let mut headers = vec![std::collections::HashMap::new()];
782 headers[0].insert("assertion_code", assertion_code);
783
784 let rendered = crate::template_env::render(
785 "php/http_assertions.jinja",
786 minijinja::context! {
787 response_var => "",
788 status_code => 0u16,
789 headers => headers,
790 body_assertion => String::new(),
791 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
792 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
793 },
794 );
795 out.push_str(&rendered);
796 }
797
798 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
804 let body_assertion = match expected {
805 serde_json::Value::String(s) if !s.is_empty() => {
806 let php_val = format!("\"{}\"", escape_php(s));
807 format!("$this->assertEquals({php_val}, (string) $response->getBody());")
808 }
809 _ => {
810 let php_val = json_to_php(expected);
811 format!(
812 "$body = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);\n $this->assertEquals({php_val}, $body);"
813 )
814 }
815 };
816
817 let rendered = crate::template_env::render(
818 "php/http_assertions.jinja",
819 minijinja::context! {
820 response_var => "",
821 status_code => 0u16,
822 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
823 body_assertion => body_assertion,
824 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
825 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
826 },
827 );
828 out.push_str(&rendered);
829 }
830
831 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
833 if let Some(obj) = expected.as_object() {
834 let mut partial_body: Vec<std::collections::HashMap<&str, String>> = Vec::new();
835 for (key, val) in obj {
836 let php_key = format!("\"{}\"", escape_php(key));
837 let php_val = json_to_php(val);
838 let assertion_code = format!("$this->assertEquals({php_val}, $body[{php_key}]);");
839 let mut entry = std::collections::HashMap::new();
840 entry.insert("assertion_code", assertion_code);
841 partial_body.push(entry);
842 }
843
844 let rendered = crate::template_env::render(
845 "php/http_assertions.jinja",
846 minijinja::context! {
847 response_var => "",
848 status_code => 0u16,
849 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
850 body_assertion => String::new(),
851 partial_body => partial_body,
852 validation_errors => Vec::<std::collections::HashMap<&str, String>>::new(),
853 },
854 );
855 out.push_str(&rendered);
856 }
857 }
858
859 fn render_assert_validation_errors(
862 &self,
863 out: &mut String,
864 _response_var: &str,
865 errors: &[ValidationErrorExpectation],
866 ) {
867 let mut validation_errors: Vec<std::collections::HashMap<&str, String>> = Vec::new();
868 for err in errors {
869 let msg_lit = format!("\"{}\"", escape_php(&err.msg));
870 let assertion_code =
871 format!("$this->assertStringContainsString({msg_lit}, json_encode($body, JSON_UNESCAPED_SLASHES));");
872 let mut entry = std::collections::HashMap::new();
873 entry.insert("assertion_code", assertion_code);
874 validation_errors.push(entry);
875 }
876
877 let rendered = crate::template_env::render(
878 "php/http_assertions.jinja",
879 minijinja::context! {
880 response_var => "",
881 status_code => 0u16,
882 headers => Vec::<std::collections::HashMap<&str, String>>::new(),
883 body_assertion => String::new(),
884 partial_body => Vec::<std::collections::HashMap<&str, String>>::new(),
885 validation_errors => validation_errors,
886 },
887 );
888 out.push_str(&rendered);
889 }
890}
891
892fn render_http_test_method(out: &mut String, fixture: &Fixture, http: &HttpFixture) {
897 if http.expected_response.status_code == 101 {
901 let method_name = sanitize_filename(&fixture.id);
902 let description = &fixture.description;
903 out.push_str(&crate::template_env::render(
904 "php/http_test_skip_101.jinja",
905 minijinja::context! {
906 method_name => method_name,
907 description => description,
908 },
909 ));
910 return;
911 }
912
913 client::http_call::render_http_test(out, &PhpTestClientRenderer, fixture);
914}
915
916#[allow(clippy::too_many_arguments)]
921fn render_test_method(
922 out: &mut String,
923 fixture: &Fixture,
924 e2e_config: &E2eConfig,
925 lang: &str,
926 namespace: &str,
927 class_name: &str,
928 type_defs: &[alef_core::ir::TypeDef],
929 php_enum_names: &HashSet<String>,
930 enum_fields: &HashMap<String, String>,
931 result_is_simple: bool,
932 php_client_factory: Option<&str>,
933 options_via: &str,
934 adapters: &[alef_core::config::extras::AdapterConfig],
935) {
936 let call_config = e2e_config.resolve_call_for_fixture(
938 fixture.call.as_deref(),
939 &fixture.id,
940 &fixture.resolved_category(),
941 &fixture.tags,
942 &fixture.input,
943 );
944 let per_call_getter_map = build_php_getter_map(
946 type_defs,
947 php_enum_names,
948 call_config,
949 e2e_config.effective_result_fields(call_config),
950 );
951 let call_field_resolver = FieldResolver::new_with_php_getters(
952 e2e_config.effective_fields(call_config),
953 e2e_config.effective_fields_optional(call_config),
954 e2e_config.effective_result_fields(call_config),
955 e2e_config.effective_fields_array(call_config),
956 &HashSet::new(),
957 &HashMap::new(),
958 per_call_getter_map,
959 );
960 let field_resolver = &call_field_resolver;
961 let call_overrides = call_config.overrides.get(lang);
962 let has_override = call_overrides.is_some_and(|o| o.function.is_some());
963 let result_is_simple = call_overrides.is_some_and(|o| o.result_is_simple) || result_is_simple;
967 let mut function_name = call_overrides
968 .and_then(|o| o.function.as_ref())
969 .cloned()
970 .unwrap_or_else(|| call_config.function.clone());
971 if !has_override {
976 function_name = function_name.to_lower_camel_case();
977 }
978 let result_var = &call_config.result_var;
979 let args = &call_config.args;
980
981 let method_name = sanitize_filename(&fixture.id);
982 let description = &fixture.description;
983 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
984
985 let call_options_type = call_overrides.and_then(|o| o.options_type.as_deref()).or_else(|| {
987 e2e_config
988 .call
989 .overrides
990 .get(lang)
991 .and_then(|o| o.options_type.as_deref())
992 });
993
994 let adapter_request_type: Option<String> = adapters
995 .iter()
996 .find(|a| a.name == call_config.function.as_str())
997 .and_then(|a| a.request_type.as_deref())
998 .map(|rt| rt.rsplit("::").next().unwrap_or(rt).to_string());
999 let (mut setup_lines, args_str) = build_args_and_setup(
1000 &fixture.input,
1001 args,
1002 class_name,
1003 enum_fields,
1004 fixture,
1005 options_via,
1006 call_options_type,
1007 adapter_request_type.as_deref(),
1008 );
1009
1010 let skip_test = call_config.skip_languages.iter().any(|l| l == "php");
1012 if skip_test {
1013 let rendered = crate::template_env::render(
1014 "php/test_method.jinja",
1015 minijinja::context! {
1016 method_name => method_name,
1017 description => description,
1018 client_factory => String::new(),
1019 setup_lines => Vec::<String>::new(),
1020 expects_error => false,
1021 skip_test => true,
1022 has_usable_assertions => false,
1023 call_expr => String::new(),
1024 result_var => result_var,
1025 assertions_body => String::new(),
1026 },
1027 );
1028 out.push_str(&rendered);
1029 return;
1030 }
1031
1032 let mut options_already_created = !args_str.is_empty() && args_str == "$options";
1034 if let Some(visitor_spec) = &fixture.visitor {
1035 build_php_visitor(&mut setup_lines, visitor_spec);
1036 if !options_already_created {
1037 let options_type = call_options_type.unwrap_or("ConversionOptions");
1038 setup_lines.push(format!("$builder = \\{namespace}\\{options_type}::builder();"));
1039 setup_lines.push("$options = $builder->visitor($visitor)->build();".to_string());
1040 options_already_created = true;
1041 }
1042 }
1043
1044 let final_args = if options_already_created {
1045 if args_str.is_empty() || args_str == "$options" {
1046 "$options".to_string()
1047 } else {
1048 format!("{args_str}, $options")
1049 }
1050 } else {
1051 args_str
1052 };
1053
1054 let call_expr = if php_client_factory.is_some() {
1055 format!("$client->{function_name}({final_args})")
1056 } else {
1057 format!("{class_name}::{function_name}({final_args})")
1058 };
1059
1060 let has_mock = fixture.mock_response.is_some() || fixture.http.is_some();
1061 let api_key_var = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref());
1062 let client_factory = if let Some(factory) = php_client_factory {
1063 let fixture_id = &fixture.id;
1064 if let Some(var) = api_key_var.filter(|_| has_mock) {
1065 format!(
1066 "$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);"
1067 )
1068 } else if has_mock {
1069 let base_url_expr = if fixture.has_host_root_route() {
1070 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1071 format!("(getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}')")
1072 } else {
1073 format!("getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}'")
1074 };
1075 format!("$client = \\{namespace}\\{class_name}::{factory}('test-key', {base_url_expr});")
1076 } else if let Some(var) = api_key_var {
1077 format!(
1078 "$apiKey = getenv('{var}');\n if (!$apiKey) {{ $this->markTestSkipped('{var} not set'); return; }}\n $client = \\{namespace}\\{class_name}::{factory}($apiKey);"
1079 )
1080 } else {
1081 format!("$client = \\{namespace}\\{class_name}::{factory}('test-key');")
1082 }
1083 } else {
1084 String::new()
1085 };
1086
1087 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
1089
1090 let has_usable_assertions = fixture.assertions.iter().any(|a| {
1093 if a.assertion_type == "error" || a.assertion_type == "not_error" {
1094 return false;
1095 }
1096 match &a.field {
1097 Some(f) if !f.is_empty() => {
1098 if is_streaming && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1099 return true;
1100 }
1101 field_resolver.is_valid_for_result(f)
1102 }
1103 _ => true,
1104 }
1105 });
1106
1107 let collect_snippet = if is_streaming {
1109 crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet("php", result_var, "chunks")
1110 .unwrap_or_default()
1111 } else {
1112 String::new()
1113 };
1114
1115 let mut fields_array_bindings = std::collections::HashMap::new();
1118 for assertion in &fixture.assertions {
1119 if let Some(f) = &assertion.field {
1120 if !f.is_empty() && field_resolver.is_array(f) {
1121 if !fields_array_bindings.contains_key(f.as_str()) {
1123 let accessor = field_resolver.accessor(f, "php", &format!("${result_var}"));
1124 let var_name = f.to_lower_camel_case();
1125 fields_array_bindings.insert(f.clone(), (var_name, accessor));
1126 }
1127 }
1128 }
1129 }
1130
1131 let mut field_bindings = String::new();
1133 for (field_name, (var_name, accessor)) in &fields_array_bindings {
1134 if field_name == "chunks" || field_name == "imports" || field_name == "structure" {
1135 field_bindings.push_str(&format!(" ${} = {};\n", var_name, accessor));
1136 }
1137 }
1138
1139 let mut assertions_body = String::new();
1141 for assertion in &fixture.assertions {
1142 render_assertion(
1143 &mut assertions_body,
1144 assertion,
1145 result_var,
1146 field_resolver,
1147 result_is_simple,
1148 call_config.result_is_array,
1149 &fields_array_bindings,
1150 );
1151 }
1152
1153 if is_streaming && !expects_error && assertions_body.trim().is_empty() {
1159 assertions_body.push_str(" $this->assertTrue(is_array($chunks), 'expected drained chunks list');\n");
1160 }
1161
1162 let rendered = crate::template_env::render(
1163 "php/test_method.jinja",
1164 minijinja::context! {
1165 method_name => method_name,
1166 description => description,
1167 client_factory => client_factory,
1168 setup_lines => setup_lines,
1169 expects_error => expects_error,
1170 skip_test => fixture.assertions.is_empty(),
1171 has_usable_assertions => has_usable_assertions || is_streaming,
1172 call_expr => call_expr,
1173 result_var => result_var,
1174 collect_snippet => collect_snippet,
1175 field_bindings => field_bindings,
1176 assertions_body => assertions_body,
1177 },
1178 );
1179 out.push_str(&rendered);
1180}
1181
1182fn emit_php_batch_item_array(arr: &serde_json::Value, elem_type: &str) -> String {
1195 if let Some(items) = arr.as_array() {
1196 let item_strs: Vec<String> = items
1197 .iter()
1198 .filter_map(|item| {
1199 if let Some(obj) = item.as_object() {
1200 match elem_type {
1201 "BatchBytesItem" => {
1202 let content = obj.get("content").and_then(|v| v.as_array());
1203 let mime_type = obj.get("mime_type").and_then(|v| v.as_str()).unwrap_or("text/plain");
1204 let content_code = if let Some(arr) = content {
1205 let bytes: Vec<String> = arr
1206 .iter()
1207 .filter_map(|v| v.as_u64())
1208 .map(|n| format!("\\x{:02x}", n))
1209 .collect();
1210 format!("\"{}\"", bytes.join(""))
1211 } else {
1212 "\"\"".to_string()
1213 };
1214 Some(format!(
1215 "new {}(content: {}, mimeType: \"{}\")",
1216 elem_type, content_code, mime_type
1217 ))
1218 }
1219 "BatchFileItem" => {
1220 let path = obj.get("path").and_then(|v| v.as_str()).unwrap_or("");
1221 Some(format!("new {}(path: \"{}\")", elem_type, path))
1222 }
1223 _ => None,
1224 }
1225 } else {
1226 None
1227 }
1228 })
1229 .collect();
1230 format!("[{}]", item_strs.join(", "))
1231 } else {
1232 "[]".to_string()
1233 }
1234}
1235
1236#[allow(clippy::too_many_arguments)]
1237fn build_args_and_setup(
1238 input: &serde_json::Value,
1239 args: &[crate::config::ArgMapping],
1240 class_name: &str,
1241 _enum_fields: &HashMap<String, String>,
1242 fixture: &crate::fixture::Fixture,
1243 options_via: &str,
1244 options_type: Option<&str>,
1245 adapter_request_type: Option<&str>,
1246) -> (Vec<String>, String) {
1247 let fixture_id = &fixture.id;
1248 if args.is_empty() {
1249 let is_empty_input = match input {
1252 serde_json::Value::Null => true,
1253 serde_json::Value::Object(m) => m.is_empty(),
1254 _ => false,
1255 };
1256 if is_empty_input {
1257 return (Vec::new(), String::new());
1258 }
1259 return (Vec::new(), json_to_php(input));
1260 }
1261
1262 let mut setup_lines: Vec<String> = Vec::new();
1263 let mut parts: Vec<String> = Vec::new();
1264
1265 let arg_has_emission = |arg: &crate::config::ArgMapping| -> bool {
1270 let val = if arg.field == "input" {
1271 Some(input)
1272 } else {
1273 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1274 input.get(field)
1275 };
1276 match val {
1277 None | Some(serde_json::Value::Null) => !arg.optional,
1278 Some(_) => true,
1279 }
1280 };
1281 let any_later_has_emission = |from_idx: usize| -> bool { args[from_idx..].iter().any(arg_has_emission) };
1282
1283 for (idx, arg) in args.iter().enumerate() {
1284 if arg.arg_type == "mock_url" {
1285 if fixture.has_host_root_route() {
1286 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_uppercase());
1287 setup_lines.push(format!(
1288 "${} = getenv('{env_key}') ?: getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1289 arg.name,
1290 ));
1291 } else {
1292 setup_lines.push(format!(
1293 "${} = getenv('MOCK_SERVER_URL') . '/fixtures/{fixture_id}';",
1294 arg.name,
1295 ));
1296 }
1297 if let Some(req_type) = adapter_request_type {
1298 let req_var = format!("${}_req", arg.name);
1299 setup_lines.push(format!("{req_var} = new {req_type}(${});", arg.name));
1300 parts.push(req_var);
1301 } else {
1302 parts.push(format!("${}", arg.name));
1303 }
1304 continue;
1305 }
1306
1307 if arg.arg_type == "handle" {
1308 let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
1310 let config_value = if arg.field == "input" {
1311 input
1312 } else {
1313 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1314 input.get(field).unwrap_or(&serde_json::Value::Null)
1315 };
1316 if config_value.is_null()
1317 || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
1318 {
1319 setup_lines.push(format!("${} = {class_name}::{constructor_name}(null);", arg.name,));
1320 } else {
1321 let name = &arg.name;
1322 let filtered_config = filter_empty_enum_strings(config_value);
1327 setup_lines.push(format!(
1328 "${name}_config = CrawlConfig::from_json(json_encode({}));",
1329 json_to_php_camel_keys(&filtered_config)
1330 ));
1331 setup_lines.push(format!(
1332 "${} = {class_name}::{constructor_name}(${name}_config);",
1333 arg.name,
1334 ));
1335 }
1336 parts.push(format!("${}", arg.name));
1337 continue;
1338 }
1339
1340 let val = if arg.field == "input" {
1341 Some(input)
1342 } else {
1343 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1344 input.get(field)
1345 };
1346
1347 if arg.arg_type == "bytes" {
1351 match val {
1352 None | Some(serde_json::Value::Null) => {
1353 if arg.optional {
1354 parts.push("null".to_string());
1355 } else {
1356 parts.push("\"\"".to_string());
1357 }
1358 }
1359 Some(serde_json::Value::String(s)) => {
1360 let var_name = format!("{}Bytes", arg.name);
1361 setup_lines.push(format!(
1362 "${var_name} = file_get_contents(\"{path}\");\n if (${var_name} === false) {{ $this->fail(\"failed to read fixture: {path}\"); }}",
1363 path = s.replace('"', "\\\"")
1364 ));
1365 parts.push(format!("${var_name}"));
1366 }
1367 Some(serde_json::Value::Array(arr)) => {
1368 let bytes: String = arr
1369 .iter()
1370 .filter_map(|v| v.as_u64())
1371 .map(|n| format!("\\x{:02x}", n))
1372 .collect();
1373 parts.push(format!("\"{bytes}\""));
1374 }
1375 Some(other) => {
1376 parts.push(json_to_php(other));
1377 }
1378 }
1379 continue;
1380 }
1381
1382 match val {
1383 None | Some(serde_json::Value::Null) if arg.arg_type == "json_object" && arg.name == "config" => {
1384 let type_name = if arg.name == "config" {
1390 "ExtractionConfig".to_string()
1391 } else {
1392 format!("{}Config", arg.name.to_upper_camel_case())
1393 };
1394 parts.push(format!("{type_name}::from_json('{{}}')"));
1395 continue;
1396 }
1397 None | Some(serde_json::Value::Null) if arg.optional => {
1398 if any_later_has_emission(idx + 1) {
1403 parts.push("null".to_string());
1404 }
1405 continue;
1406 }
1407 None | Some(serde_json::Value::Null) => {
1408 let default_val = match arg.arg_type.as_str() {
1410 "string" => "\"\"".to_string(),
1411 "int" | "integer" => "0".to_string(),
1412 "float" | "number" => "0.0".to_string(),
1413 "bool" | "boolean" => "false".to_string(),
1414 "json_object" if options_via == "json" => "null".to_string(),
1415 _ => "null".to_string(),
1416 };
1417 parts.push(default_val);
1418 }
1419 Some(v) => {
1420 if arg.arg_type == "json_object" && !v.is_null() {
1421 if let Some(elem_type) = &arg.element_type {
1423 if (elem_type == "BatchBytesItem" || elem_type == "BatchFileItem") && v.is_array() {
1424 parts.push(emit_php_batch_item_array(v, elem_type));
1425 continue;
1426 }
1427 if v.is_array() && is_php_reserved_type(elem_type) {
1431 parts.push(json_to_php(v));
1432 continue;
1433 }
1434 }
1435 match options_via {
1436 "json" => {
1437 let filtered_v = filter_empty_enum_strings(v);
1440
1441 if let serde_json::Value::Object(obj) = &filtered_v {
1443 if obj.is_empty() {
1444 parts.push("null".to_string());
1445 continue;
1446 }
1447 }
1448
1449 parts.push(format!("json_encode({})", json_to_php_camel_keys(&filtered_v)));
1450 continue;
1451 }
1452 _ => {
1453 if let Some(type_name) = options_type {
1454 let filtered_v = filter_empty_enum_strings(v);
1459
1460 if let serde_json::Value::Object(obj) = &filtered_v {
1463 if obj.is_empty() {
1464 let arg_var = format!("${}", arg.name);
1465 setup_lines.push(format!("{arg_var} = {type_name}::from_json('{{}}');"));
1466 parts.push(arg_var);
1467 continue;
1468 }
1469 }
1470
1471 let arg_var = format!("${}", arg.name);
1472 setup_lines.push(format!(
1476 "{arg_var} = {type_name}::from_json(json_encode({}));",
1477 json_to_php_camel_keys(&filtered_v)
1478 ));
1479 parts.push(arg_var);
1480 continue;
1481 }
1482 if let Some(obj) = v.as_object() {
1486 setup_lines.push("$builder = $this->createDefaultOptionsBuilder();".to_string());
1487 for (k, vv) in obj {
1488 let snake_key = k.to_snake_case();
1489 if snake_key == "preprocessing" {
1490 if let Some(prep_obj) = vv.as_object() {
1491 let enabled =
1492 prep_obj.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);
1493 let preset =
1494 prep_obj.get("preset").and_then(|v| v.as_str()).unwrap_or("Minimal");
1495 let remove_navigation = prep_obj
1496 .get("remove_navigation")
1497 .and_then(|v| v.as_bool())
1498 .unwrap_or(true);
1499 let remove_forms =
1500 prep_obj.get("remove_forms").and_then(|v| v.as_bool()).unwrap_or(true);
1501 setup_lines.push(format!(
1502 "$preprocessing = $this->createPreprocessingOptions({}, {}, {}, {});",
1503 if enabled { "true" } else { "false" },
1504 json_to_php(&serde_json::Value::String(preset.to_string())),
1505 if remove_navigation { "true" } else { "false" },
1506 if remove_forms { "true" } else { "false" }
1507 ));
1508 setup_lines.push(
1509 "$builder = $builder->preprocessing($preprocessing);".to_string(),
1510 );
1511 }
1512 }
1513 }
1514 setup_lines.push("$options = $builder->build();".to_string());
1515 parts.push("$options".to_string());
1516 continue;
1517 }
1518 }
1519 }
1520 }
1521 parts.push(json_to_php(v));
1522 }
1523 }
1524 }
1525
1526 (setup_lines, parts.join(", "))
1527}
1528
1529fn render_assertion(
1530 out: &mut String,
1531 assertion: &Assertion,
1532 result_var: &str,
1533 field_resolver: &FieldResolver,
1534 result_is_simple: bool,
1535 result_is_array: bool,
1536 fields_array_bindings: &std::collections::HashMap<String, (String, String)>,
1537) {
1538 if let Some(f) = &assertion.field {
1541 match f.as_str() {
1542 "chunks_have_content" => {
1543 let pred = format!(
1544 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->content), true)"
1545 );
1546 out.push_str(&crate::template_env::render(
1547 "php/synthetic_assertion.jinja",
1548 minijinja::context! {
1549 assertion_kind => "chunks_content",
1550 assertion_type => assertion.assertion_type.as_str(),
1551 pred => pred,
1552 field_name => f,
1553 },
1554 ));
1555 return;
1556 }
1557 "chunks_have_embeddings" => {
1558 let pred = format!(
1559 "array_reduce(${result_var}->chunks ?? [], fn($carry, $c) => $carry && !empty($c->embedding), true)"
1560 );
1561 out.push_str(&crate::template_env::render(
1562 "php/synthetic_assertion.jinja",
1563 minijinja::context! {
1564 assertion_kind => "chunks_embeddings",
1565 assertion_type => assertion.assertion_type.as_str(),
1566 pred => pred,
1567 field_name => f,
1568 },
1569 ));
1570 return;
1571 }
1572 "embeddings" => {
1576 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1577 out.push_str(&crate::template_env::render(
1578 "php/synthetic_assertion.jinja",
1579 minijinja::context! {
1580 assertion_kind => "embeddings",
1581 assertion_type => assertion.assertion_type.as_str(),
1582 php_val => php_val,
1583 result_var => result_var,
1584 },
1585 ));
1586 return;
1587 }
1588 "embedding_dimensions" => {
1589 let expr = format!("(empty(${result_var}) ? 0 : count(${result_var}[0]))");
1590 let php_val = assertion.value.as_ref().map(json_to_php).unwrap_or_default();
1591 out.push_str(&crate::template_env::render(
1592 "php/synthetic_assertion.jinja",
1593 minijinja::context! {
1594 assertion_kind => "embedding_dimensions",
1595 assertion_type => assertion.assertion_type.as_str(),
1596 expr => expr,
1597 php_val => php_val,
1598 },
1599 ));
1600 return;
1601 }
1602 "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
1603 let pred = match f.as_str() {
1604 "embeddings_valid" => {
1605 format!("array_reduce(${result_var}, fn($carry, $e) => $carry && count($e) > 0, true)")
1606 }
1607 "embeddings_finite" => {
1608 format!(
1609 "array_reduce(${result_var}, fn($carry, $e) => $carry && array_reduce($e, fn($c, $v) => $c && is_finite($v), true), true)"
1610 )
1611 }
1612 "embeddings_non_zero" => {
1613 format!(
1614 "array_reduce(${result_var}, fn($carry, $e) => $carry && count(array_filter($e, fn($v) => $v !== 0.0)) > 0, true)"
1615 )
1616 }
1617 "embeddings_normalized" => {
1618 format!(
1619 "array_reduce(${result_var}, fn($carry, $e) => $carry && abs(array_sum(array_map(fn($v) => $v * $v, $e)) - 1.0) < 1e-3, true)"
1620 )
1621 }
1622 _ => unreachable!(),
1623 };
1624 let assertion_kind = format!("embeddings_{}", f.strip_prefix("embeddings_").unwrap_or(f));
1625 out.push_str(&crate::template_env::render(
1626 "php/synthetic_assertion.jinja",
1627 minijinja::context! {
1628 assertion_kind => assertion_kind,
1629 assertion_type => assertion.assertion_type.as_str(),
1630 pred => pred,
1631 field_name => f,
1632 },
1633 ));
1634 return;
1635 }
1636 "keywords" | "keywords_count" => {
1639 out.push_str(&crate::template_env::render(
1640 "php/synthetic_assertion.jinja",
1641 minijinja::context! {
1642 assertion_kind => "keywords",
1643 field_name => f,
1644 },
1645 ));
1646 return;
1647 }
1648 _ => {}
1649 }
1650 }
1651
1652 if let Some(f) = &assertion.field {
1655 if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1656 if let Some(expr) =
1657 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "php", "chunks")
1658 {
1659 let line = match assertion.assertion_type.as_str() {
1660 "count_min" => {
1661 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1662 format!(
1663 " $this->assertGreaterThanOrEqual({n}, count({expr}), 'expected >= {n} chunks');\n"
1664 )
1665 } else {
1666 String::new()
1667 }
1668 }
1669 "count_equals" => {
1670 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1671 format!(" $this->assertCount({n}, {expr});\n")
1672 } else {
1673 String::new()
1674 }
1675 }
1676 "equals" => {
1677 if let Some(serde_json::Value::String(s)) = &assertion.value {
1678 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1679 format!(" $this->assertEquals('{escaped}', {expr});\n")
1680 } else if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1681 format!(" $this->assertEquals({n}, {expr});\n")
1682 } else {
1683 String::new()
1684 }
1685 }
1686 "not_empty" => format!(" $this->assertNotEmpty({expr});\n"),
1687 "is_empty" => format!(" $this->assertEmpty({expr});\n"),
1688 "is_true" => format!(" $this->assertTrue({expr});\n"),
1689 "is_false" => format!(" $this->assertFalse({expr});\n"),
1690 "greater_than" => {
1691 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1692 format!(" $this->assertGreaterThan({n}, {expr});\n")
1693 } else {
1694 String::new()
1695 }
1696 }
1697 "greater_than_or_equal" => {
1698 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1699 format!(" $this->assertGreaterThanOrEqual({n}, {expr});\n")
1700 } else {
1701 String::new()
1702 }
1703 }
1704 "contains" => {
1705 if let Some(serde_json::Value::String(s)) = &assertion.value {
1706 let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");
1707 format!(" $this->assertStringContainsString('{escaped}', {expr});\n")
1708 } else {
1709 String::new()
1710 }
1711 }
1712 _ => format!(
1713 " // streaming field '{f}': assertion type '{}' not rendered\n",
1714 assertion.assertion_type
1715 ),
1716 };
1717 if !line.is_empty() {
1718 out.push_str(&line);
1719 }
1720 }
1721 return;
1722 }
1723 }
1724
1725 if let Some(f) = &assertion.field {
1727 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1728 out.push_str(&crate::template_env::render(
1729 "php/synthetic_assertion.jinja",
1730 minijinja::context! {
1731 assertion_kind => "skipped",
1732 field_name => f,
1733 },
1734 ));
1735 return;
1736 }
1737 }
1738
1739 if result_is_simple {
1742 if let Some(f) = &assertion.field {
1743 let f_lower = f.to_lowercase();
1744 if !f.is_empty()
1745 && f_lower != "content"
1746 && (f_lower.starts_with("metadata")
1747 || f_lower.starts_with("document")
1748 || f_lower.starts_with("structure"))
1749 {
1750 out.push_str(&crate::template_env::render(
1751 "php/synthetic_assertion.jinja",
1752 minijinja::context! {
1753 assertion_kind => "result_is_simple",
1754 field_name => f,
1755 },
1756 ));
1757 return;
1758 }
1759 }
1760 }
1761
1762 let field_expr = match &assertion.field {
1763 _ if result_is_simple => format!("${result_var}"),
1767 Some(f) if !f.is_empty() => {
1768 if let Some((var_name, _)) = fields_array_bindings.get(f) {
1770 format!("${}", var_name)
1771 } else {
1772 field_resolver.accessor(f, "php", &format!("${result_var}"))
1773 }
1774 }
1775 _ => format!("${result_var}"),
1776 };
1777
1778 let field_is_array = assertion.field.as_ref().map_or(result_is_array, |f| {
1781 if f.is_empty() {
1782 result_is_array
1783 } else {
1784 field_resolver.is_array(f)
1785 }
1786 });
1787
1788 let trimmed_field_expr_for = |expected: &serde_json::Value| -> String {
1792 if expected.is_string() {
1793 format!("trim({})", field_expr)
1794 } else {
1795 field_expr.clone()
1796 }
1797 };
1798
1799 let assertion_type = assertion.assertion_type.as_str();
1801 let has_php_val = assertion.value.is_some();
1802 let php_val = match assertion.value.as_ref() {
1806 Some(v) => json_to_php(v),
1807 None if assertion_type == "equals" => "null".to_string(),
1808 None => String::new(),
1809 };
1810 let trimmed_field_expr = trimmed_field_expr_for(assertion.value.as_ref().unwrap_or(&serde_json::Value::Null));
1811 let is_string_val = assertion.value.as_ref().is_some_and(|v| v.is_string());
1812 let values_php: Vec<String> = assertion
1816 .values
1817 .as_ref()
1818 .map(|vals| vals.iter().map(json_to_php).collect::<Vec<_>>())
1819 .or_else(|| assertion.value.as_ref().map(|v| vec![json_to_php(v)]))
1820 .unwrap_or_default();
1821 let contains_any_checks: Vec<String> = assertion
1822 .values
1823 .as_ref()
1824 .map_or(Vec::new(), |vals| vals.iter().map(json_to_php).collect());
1825 let n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1826
1827 let call_expr = if let Some(method_name) = &assertion.method {
1829 build_php_method_call(result_var, method_name, assertion.args.as_ref())
1830 } else {
1831 String::new()
1832 };
1833 let check = assertion.check.as_deref().unwrap_or("is_true");
1834 let has_php_check_val = matches!(assertion.assertion_type.as_str(), "method_result") && assertion.value.is_some();
1835 let php_check_val = if matches!(assertion.assertion_type.as_str(), "method_result") {
1836 assertion.value.as_ref().map(json_to_php).unwrap_or_default()
1837 } else {
1838 String::new()
1839 };
1840 let check_n = assertion.value.as_ref().and_then(|v| v.as_u64()).unwrap_or(0);
1841 let is_bool_val = assertion.value.as_ref().is_some_and(|v| v.is_boolean());
1842 let bool_is_true = assertion.value.as_ref().and_then(|v| v.as_bool()).unwrap_or(false);
1843
1844 if matches!(assertion_type, "not_error" | "error") {
1846 if assertion_type == "not_error" {
1847 }
1849 return;
1851 }
1852
1853 let rendered = crate::template_env::render(
1854 "php/assertion.jinja",
1855 minijinja::context! {
1856 assertion_type => assertion_type,
1857 field_expr => field_expr,
1858 php_val => php_val,
1859 has_php_val => has_php_val,
1860 trimmed_field_expr => trimmed_field_expr,
1861 is_string_val => is_string_val,
1862 field_is_array => field_is_array,
1863 values_php => values_php,
1864 contains_any_checks => contains_any_checks,
1865 n => n,
1866 call_expr => call_expr,
1867 check => check,
1868 php_check_val => php_check_val,
1869 has_php_check_val => has_php_check_val,
1870 check_n => check_n,
1871 is_bool_val => is_bool_val,
1872 bool_is_true => bool_is_true,
1873 },
1874 );
1875 let _ = write!(out, " {}", rendered);
1876}
1877
1878fn build_php_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1885 let extra_args = if let Some(args_val) = args {
1886 args_val
1887 .as_object()
1888 .map(|obj| {
1889 obj.values()
1890 .map(|v| match v {
1891 serde_json::Value::String(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
1892 serde_json::Value::Bool(true) => "true".to_string(),
1893 serde_json::Value::Bool(false) => "false".to_string(),
1894 serde_json::Value::Number(n) => n.to_string(),
1895 serde_json::Value::Null => "null".to_string(),
1896 other => format!("\"{}\"", other.to_string().replace('\\', "\\\\").replace('"', "\\\"")),
1897 })
1898 .collect::<Vec<_>>()
1899 .join(", ")
1900 })
1901 .unwrap_or_default()
1902 } else {
1903 String::new()
1904 };
1905
1906 if extra_args.is_empty() {
1907 format!("${result_var}->{method_name}()")
1908 } else {
1909 format!("${result_var}->{method_name}({extra_args})")
1910 }
1911}
1912
1913fn filter_empty_enum_strings(value: &serde_json::Value) -> serde_json::Value {
1917 match value {
1918 serde_json::Value::Object(map) => {
1919 let filtered: serde_json::Map<String, serde_json::Value> = map
1920 .iter()
1921 .filter_map(|(k, v)| {
1922 if let serde_json::Value::String(s) = v {
1924 if s.is_empty() {
1925 return None;
1926 }
1927 }
1928 Some((k.clone(), filter_empty_enum_strings(v)))
1930 })
1931 .collect();
1932 serde_json::Value::Object(filtered)
1933 }
1934 serde_json::Value::Array(arr) => {
1935 let filtered: Vec<serde_json::Value> = arr.iter().map(filter_empty_enum_strings).collect();
1936 serde_json::Value::Array(filtered)
1937 }
1938 other => other.clone(),
1939 }
1940}
1941
1942fn json_to_php(value: &serde_json::Value) -> String {
1944 match value {
1945 serde_json::Value::String(s) => format!("\"{}\"", escape_php(s)),
1946 serde_json::Value::Bool(true) => "true".to_string(),
1947 serde_json::Value::Bool(false) => "false".to_string(),
1948 serde_json::Value::Number(n) => n.to_string(),
1949 serde_json::Value::Null => "null".to_string(),
1950 serde_json::Value::Array(arr) => {
1951 let items: Vec<String> = arr.iter().map(json_to_php).collect();
1952 format!("[{}]", items.join(", "))
1953 }
1954 serde_json::Value::Object(map) => {
1955 let items: Vec<String> = map
1956 .iter()
1957 .map(|(k, v)| format!("\"{}\" => {}", escape_php(k), json_to_php(v)))
1958 .collect();
1959 format!("[{}]", items.join(", "))
1960 }
1961 }
1962}
1963
1964fn json_to_php_camel_keys(value: &serde_json::Value) -> String {
1969 match value {
1970 serde_json::Value::Object(map) => {
1971 let items: Vec<String> = map
1972 .iter()
1973 .map(|(k, v)| {
1974 let camel_key = k.to_lower_camel_case();
1975 format!("\"{}\" => {}", escape_php(&camel_key), json_to_php_camel_keys(v))
1976 })
1977 .collect();
1978 format!("[{}]", items.join(", "))
1979 }
1980 serde_json::Value::Array(arr) => {
1981 let items: Vec<String> = arr.iter().map(json_to_php_camel_keys).collect();
1982 format!("[{}]", items.join(", "))
1983 }
1984 _ => json_to_php(value),
1985 }
1986}
1987
1988fn build_php_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1994 setup_lines.push("$visitor = new class {".to_string());
1995 for (method_name, action) in &visitor_spec.callbacks {
1996 emit_php_visitor_method(setup_lines, method_name, action);
1997 }
1998 setup_lines.push("};".to_string());
1999}
2000
2001fn emit_php_visitor_method(setup_lines: &mut Vec<String>, method_name: &str, action: &CallbackAction) {
2003 let params = match method_name {
2004 "visit_link" => "$ctx, $href, $text, $title",
2005 "visit_image" => "$ctx, $src, $alt, $title",
2006 "visit_heading" => "$ctx, $level, $text, $id",
2007 "visit_code_block" => "$ctx, $lang, $code",
2008 "visit_code_inline"
2009 | "visit_strong"
2010 | "visit_emphasis"
2011 | "visit_strikethrough"
2012 | "visit_underline"
2013 | "visit_subscript"
2014 | "visit_superscript"
2015 | "visit_mark"
2016 | "visit_button"
2017 | "visit_summary"
2018 | "visit_figcaption"
2019 | "visit_definition_term"
2020 | "visit_definition_description" => "$ctx, $text",
2021 "visit_text" => "$ctx, $text",
2022 "visit_list_item" => "$ctx, $ordered, $marker, $text",
2023 "visit_blockquote" => "$ctx, $content, $depth",
2024 "visit_table_row" => "$ctx, $cells, $isHeader",
2025 "visit_custom_element" => "$ctx, $tagName, $html",
2026 "visit_form" => "$ctx, $actionUrl, $method",
2027 "visit_input" => "$ctx, $input_type, $name, $value",
2028 "visit_audio" | "visit_video" | "visit_iframe" => "$ctx, $src",
2029 "visit_details" => "$ctx, $isOpen",
2030 "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "$ctx, $output",
2031 "visit_list_start" => "$ctx, $ordered",
2032 "visit_list_end" => "$ctx, $ordered, $output",
2033 _ => "$ctx",
2034 };
2035
2036 let (action_type, action_value, return_form) = match action {
2037 CallbackAction::Skip => ("skip", String::new(), "dict"),
2038 CallbackAction::Continue => ("continue", String::new(), "dict"),
2039 CallbackAction::PreserveHtml => ("preserve_html", String::new(), "dict"),
2040 CallbackAction::Custom { output } => ("custom", escape_php(output), "dict"),
2041 CallbackAction::CustomTemplate { template, return_form } => {
2042 let form = match return_form {
2043 TemplateReturnForm::Dict => "dict",
2044 TemplateReturnForm::BareString => "bare_string",
2045 };
2046 ("custom_template", escape_php(template), form)
2047 }
2048 };
2049
2050 let rendered = crate::template_env::render(
2051 "php/visitor_method.jinja",
2052 minijinja::context! {
2053 method_name => method_name,
2054 params => params,
2055 action_type => action_type,
2056 action_value => action_value,
2057 return_form => return_form,
2058 },
2059 );
2060 for line in rendered.lines() {
2061 setup_lines.push(line.to_string());
2062 }
2063}
2064
2065fn is_php_reserved_type(name: &str) -> bool {
2067 matches!(
2068 name.to_ascii_lowercase().as_str(),
2069 "string"
2070 | "int"
2071 | "integer"
2072 | "float"
2073 | "double"
2074 | "bool"
2075 | "boolean"
2076 | "array"
2077 | "object"
2078 | "null"
2079 | "void"
2080 | "callable"
2081 | "iterable"
2082 | "never"
2083 | "self"
2084 | "parent"
2085 | "static"
2086 | "true"
2087 | "false"
2088 | "mixed"
2089 )
2090}