| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\GoogleSheets\Helpers; |
| 4 |
|
| 5 |
use IvyForms\Common\Helpers\FieldHelper; |
| 6 |
|
| 7 |
/** |
| 8 |
* Maps form-builder placeholder keys (type_fieldIndex) to submission formatter keys (type, type_1, ...). |
| 9 |
*/ |
| 10 |
class GoogleSheetsFieldKeyHelper |
| 11 |
{ |
| 12 |
/** |
| 13 |
* @param array<mixed> $formFields |
| 14 |
* @param array<string, mixed> $fieldData |
| 15 |
* @return array<string, mixed> |
| 16 |
*/ |
| 17 |
public static function buildFieldIndexAliases(array $formFields, array $fieldData): array |
| 18 |
{ |
| 19 |
$aliases = []; |
| 20 |
$typeCounters = []; |
| 21 |
|
| 22 |
foreach ($formFields as $field) { |
| 23 |
if (!self::isRootFormField($field)) { |
| 24 |
continue; |
| 25 |
} |
| 26 |
|
| 27 |
$type = $field->getType(); |
| 28 |
|
| 29 |
if (!isset($typeCounters[$type])) { |
| 30 |
$typeCounters[$type] = 0; |
| 31 |
} |
| 32 |
|
| 33 |
$count = $typeCounters[$type]; |
| 34 |
$alias = self::buildAliasForField($field, $type, $count, $fieldData); |
| 35 |
|
| 36 |
if ($alias !== null) { |
| 37 |
$aliases = array_merge($aliases, $alias); |
| 38 |
} |
| 39 |
|
| 40 |
$typeCounters[$type]++; |
| 41 |
} |
| 42 |
|
| 43 |
return $aliases; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* @param mixed $field |
| 48 |
*/ |
| 49 |
private static function isRootFormField($field): bool |
| 50 |
{ |
| 51 |
if (!is_object($field) || !method_exists($field, 'getType')) { |
| 52 |
return false; |
| 53 |
} |
| 54 |
|
| 55 |
if (FieldHelper::isSecurityField($field->getType())) { |
| 56 |
return false; |
| 57 |
} |
| 58 |
|
| 59 |
return !(method_exists($field, 'getParentId') && $field->getParentId() > 0); |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* @param mixed $field |
| 64 |
* @param array<string, mixed> $fieldData |
| 65 |
* @return array<string, mixed>|null |
| 66 |
*/ |
| 67 |
private static function buildAliasForField($field, string $type, int $count, array $fieldData): ?array |
| 68 |
{ |
| 69 |
if (!method_exists($field, 'getIndex')) { |
| 70 |
return null; |
| 71 |
} |
| 72 |
|
| 73 |
$fieldIndex = $field->getIndex(); |
| 74 |
|
| 75 |
if ($fieldIndex === null) { |
| 76 |
return null; |
| 77 |
} |
| 78 |
|
| 79 |
$counterKey = $count === 0 ? $type : "{$type}_{$count}"; |
| 80 |
$fieldIndexKey = "{$type}_{$fieldIndex}"; |
| 81 |
|
| 82 |
if (!array_key_exists($counterKey, $fieldData)) { |
| 83 |
return null; |
| 84 |
} |
| 85 |
|
| 86 |
return [$fieldIndexKey => $fieldData[$counterKey]]; |
| 87 |
} |
| 88 |
} |
| 89 |
|