| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Common\Helpers; |
| 4 |
|
| 5 |
// phpcs:disable PSR1.Files.SideEffects |
| 6 |
if (!defined('ABSPATH')) { |
| 7 |
exit; // Exit if accessed directly |
| 8 |
} |
| 9 |
|
| 10 |
use IvyForms\Common\Exceptions\ValidationException; |
| 11 |
use IvyForms\Entity\FieldOptions\FieldOptions; |
| 12 |
use IvyForms\Factory\FieldOptions\FieldOptionsFactory; |
| 13 |
use IvyForms\Repository\FieldOptions\FieldOptionsRepositoryInterface; |
| 14 |
|
| 15 |
/** |
| 16 |
* General helper utilities related to Field processing. |
| 17 |
*/ |
| 18 |
class FieldHelper |
| 19 |
{ |
| 20 |
/** |
| 21 |
* Resolve parentId using fieldIndex -> parentId map if needed. |
| 22 |
* |
| 23 |
* @param array<string,mixed> $data Passed by reference; parentId modified in place. |
| 24 |
* @param array<int,int> $parentMap Map of fieldIndex => newly created parent field id. |
| 25 |
*/ |
| 26 |
public static function resolveParentId(array &$data, array $parentMap): void |
| 27 |
{ |
| 28 |
if (!array_key_exists('parentId', $data)) { |
| 29 |
return; |
| 30 |
} |
| 31 |
|
| 32 |
$parentId = $data['parentId']; |
| 33 |
$needsResolve = ($parentId === 0 || $parentId === '0' || $parentId === null); |
| 34 |
if ($needsResolve && isset($data['fieldIndex']) && isset($parentMap[$data['fieldIndex']])) { |
| 35 |
$data['parentId'] = $parentMap[$data['fieldIndex']]; |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Partition field options into new, update, and submitted IDs. |
| 41 |
* |
| 42 |
* @param array<string, mixed> $fieldData |
| 43 |
* @param array<int> $existingOptionIds |
| 44 |
* @return array{ |
| 45 |
* newOptions: array<int, FieldOptions>, |
| 46 |
* updateOptions: array<int, FieldOptions>, |
| 47 |
* submittedOptionIds: array<int, int> |
| 48 |
* } |
| 49 |
* @throws ValidationException |
| 50 |
*/ |
| 51 |
public static function partitionFieldOptions(array $fieldData, array $existingOptionIds): array |
| 52 |
{ |
| 53 |
$newOptions = []; |
| 54 |
$updateOptions = []; |
| 55 |
$submittedOptionIds = []; |
| 56 |
foreach ($fieldData['fieldOptions'] as $optionData) { |
| 57 |
$option = FieldOptionsFactory::create($optionData); |
| 58 |
if ( |
| 59 |
isset($optionData['id']) && $optionData['id'] > 0 |
| 60 |
&& in_array($optionData['id'], $existingOptionIds, true) |
| 61 |
) { |
| 62 |
$updateOptions[] = $option; |
| 63 |
$submittedOptionIds[] = $optionData['id']; |
| 64 |
continue; |
| 65 |
} |
| 66 |
$newOptions[] = $option; |
| 67 |
} |
| 68 |
return [ |
| 69 |
'newOptions' => $newOptions, |
| 70 |
'updateOptions' => $updateOptions, |
| 71 |
'submittedOptionIds' => $submittedOptionIds, |
| 72 |
]; |
| 73 |
} |
| 74 |
} |
| 75 |
|