| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Factory\GoogleSheets; |
| 4 |
|
| 5 |
use DateTime; |
| 6 |
use IvyForms\Entity\GoogleSheets\GoogleSheetIntegration; |
| 7 |
use IvyForms\ValueObjects\GoogleSheets\GoogleSheetIntegration as GoogleSheetIntegrationValueObject; |
| 8 |
|
| 9 |
/** |
| 10 |
* Creates Google Sheet integration entities from database rows. |
| 11 |
*/ |
| 12 |
class GoogleSheetIntegrationFactory |
| 13 |
{ |
| 14 |
/** |
| 15 |
* @param array<string, mixed> $row |
| 16 |
*/ |
| 17 |
public static function create(array $row): GoogleSheetIntegration |
| 18 |
{ |
| 19 |
$valueObject = new GoogleSheetIntegrationValueObject( |
| 20 |
isset($row['id']) ? (int) $row['id'] : null, |
| 21 |
(int) $row['form_id'], |
| 22 |
(string) $row['spreadsheet_id'], |
| 23 |
(string) ($row['spreadsheet_name'] ?? ''), |
| 24 |
(string) $row['worksheet_name'], |
| 25 |
self::parseFieldMapping($row), |
| 26 |
self::parseSmartLogic($row), |
| 27 |
(bool) $row['enabled'], |
| 28 |
!empty($row['last_status']) ? (string) $row['last_status'] : null, |
| 29 |
self::parseDateTime($row, 'last_run_at'), |
| 30 |
self::parseDateTime($row, 'created_at'), |
| 31 |
self::parseDateTime($row, 'updated_at') |
| 32 |
); |
| 33 |
|
| 34 |
return new GoogleSheetIntegration($valueObject); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* @param array<string, mixed> $row |
| 39 |
* @return list<array{column: string, value: string}> |
| 40 |
*/ |
| 41 |
private static function parseFieldMapping(array $row): array |
| 42 |
{ |
| 43 |
$fieldMapping = json_decode($row['field_mapping'] ?? '[]', true); |
| 44 |
|
| 45 |
if (!is_array($fieldMapping)) { |
| 46 |
return []; |
| 47 |
} |
| 48 |
|
| 49 |
$normalized = []; |
| 50 |
foreach ($fieldMapping as $item) { |
| 51 |
if (!is_array($item) || empty($item['column'])) { |
| 52 |
continue; |
| 53 |
} |
| 54 |
|
| 55 |
$normalized[] = [ |
| 56 |
'column' => (string) $item['column'], |
| 57 |
'value' => (string) ($item['value'] ?? ''), |
| 58 |
]; |
| 59 |
} |
| 60 |
|
| 61 |
return $normalized; |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* @param array<string, mixed> $row |
| 66 |
* @return array<string, mixed> |
| 67 |
*/ |
| 68 |
private static function parseSmartLogic(array $row): array |
| 69 |
{ |
| 70 |
$smartLogic = json_decode($row['smart_logic'] ?? '[]', true); |
| 71 |
|
| 72 |
return is_array($smartLogic) ? $smartLogic : []; |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* @param array<string, mixed> $row |
| 77 |
*/ |
| 78 |
private static function parseDateTime(array $row, string $field): ?DateTime |
| 79 |
{ |
| 80 |
if (empty($row[$field])) { |
| 81 |
return null; |
| 82 |
} |
| 83 |
|
| 84 |
return new DateTime((string) $row[$field]); |
| 85 |
} |
| 86 |
} |
| 87 |
|