| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Common\Helpers\Import; |
| 4 |
|
| 5 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 6 |
use IvyForms\Services\Translations\BackendStrings; |
| 7 |
|
| 8 |
/** |
| 9 |
* Registry of form import sources. |
| 10 |
* |
| 11 |
* Sources are tried in registration order; the first match wins. |
| 12 |
*/ |
| 13 |
class FormImportSourceRegistry |
| 14 |
{ |
| 15 |
/** |
| 16 |
* @var array<int, FormImportSourceInterface> |
| 17 |
*/ |
| 18 |
private array $sources = []; |
| 19 |
|
| 20 |
/** |
| 21 |
* Register an import source. |
| 22 |
* |
| 23 |
* @param FormImportSourceInterface $source |
| 24 |
* @return void |
| 25 |
*/ |
| 26 |
public function register(FormImportSourceInterface $source): void |
| 27 |
{ |
| 28 |
$this->sources[] = $source; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* @return array<int, FormImportSourceInterface> |
| 33 |
*/ |
| 34 |
public function getAll(): array |
| 35 |
{ |
| 36 |
return $this->sources; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Find the first registered source that matches the payload. |
| 41 |
* |
| 42 |
* @param array<string|int, mixed> $importData |
| 43 |
* @return FormImportSourceInterface|null |
| 44 |
*/ |
| 45 |
public function findMatching(array $importData): ?FormImportSourceInterface |
| 46 |
{ |
| 47 |
foreach ($this->sources as $source) { |
| 48 |
if ($source->matches($importData)) { |
| 49 |
return $source; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
return null; |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Normalize a payload using the first matching registered source. |
| 58 |
* |
| 59 |
* @param array<string|int, mixed> $importData |
| 60 |
* @return array<string, mixed> |
| 61 |
* @throws InvalidArgumentException |
| 62 |
*/ |
| 63 |
public function normalize(array $importData): array |
| 64 |
{ |
| 65 |
$source = $this->findMatching($importData); |
| 66 |
if ($source === null) { |
| 67 |
throw new InvalidArgumentException( |
| 68 |
BackendStrings::getExceptionStrings()['unsupported_import_format'] |
| 69 |
); |
| 70 |
} |
| 71 |
|
| 72 |
return $source->normalize($importData); |
| 73 |
} |
| 74 |
} |
| 75 |
|