1. <?php
  2. /**
  3. * Maps fields of text blocks for batch processing.
  4. *
  5. * @param array $textBlocks An array of text blocks, each with fields to map.
  6. * @param array $fieldMappings An array of field mappings, defining how to extract data from the text blocks.
  7. * @return array An array of processed text blocks, with the mapped fields.
  8. */
  9. function mapTextBlocks(array $textBlocks, array $fieldMappings): array
  10. {
  11. $processedBlocks = [];
  12. foreach ($textBlocks as $block) {
  13. $processedBlock = []; // Initialize processed block
  14. foreach ($fieldMappings as $fieldName => $mapping) {
  15. $value = extractFieldValue($block, $mapping); // Extract field value using mapping
  16. $processedBlock[$fieldName] = $value; // Assign to processed block
  17. }
  18. $processedBlocks[] = $processedBlock; // Add to results
  19. }
  20. return $processedBlocks;
  21. }
  22. /**
  23. * Extracts a field value from a text block based on a mapping.
  24. *
  25. * @param array $block The text block to extract from.
  26. * @param array $mapping The mapping for the field.
  27. * @return mixed The extracted field value, or null if not found.
  28. */
  29. function extractFieldValue(array $block, array $mapping)
  30. {
  31. foreach ($mapping as $selector => $path) {
  32. try {
  33. $value = pathToValue($block, $path);
  34. return $value;
  35. } catch (Exception $e) {
  36. // Ignore if path is invalid
  37. }
  38. }
  39. return null; // Field not found
  40. }
  41. /**
  42. * Traverses the text block structure to extract a value.
  43. *
  44. * @param array $block The text block to traverse.
  45. * @param string $path The path to the value (e.g., 'block.field1.subfield2').
  46. * @return mixed The extracted value.
  47. * @throws Exception If the path is invalid.
  48. */
  49. function pathToValue(array $block, string $path)
  50. {
  51. $pathParts = explode('.', $path);
  52. $current = $block;
  53. foreach ($pathParts as $part) {
  54. if (is_array($current) && isset($current[$part])) {
  55. $current = $current[$part];
  56. } else {
  57. throw new Exception("Invalid path: " . $path); // Throw exception for invalid paths
  58. }
  59. }
  60. return $current;
  61. }
  62. ?>

Add your comment