| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\Confirmation; |
| 4 |
|
| 5 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 6 |
use IvyForms\Repository\Confirmation\ConfirmationRepositoryInterface; |
| 7 |
use IvyForms\Services\Translations\BackendStrings; |
| 8 |
|
| 9 |
class ConfirmationOrderService |
| 10 |
{ |
| 11 |
private ConfirmationRepositoryInterface $confirmationRepository; |
| 12 |
|
| 13 |
public function __construct(ConfirmationRepositoryInterface $confirmationRepository) |
| 14 |
{ |
| 15 |
$this->confirmationRepository = $confirmationRepository; |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* @param int $formId |
| 20 |
* @param array<int, int> $orderedIds |
| 21 |
* @return void |
| 22 |
*/ |
| 23 |
public function applyOrder(int $formId, array $orderedIds): void |
| 24 |
{ |
| 25 |
$this->confirmationRepository->updatePositions($formId, $orderedIds); |
| 26 |
|
| 27 |
if (!empty($orderedIds)) { |
| 28 |
$this->confirmationRepository->syncDefaultFlag($formId, (int) $orderedIds[0]); |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* @param int $formId |
| 34 |
* @param array<int, int> $orderedIds |
| 35 |
* @return void |
| 36 |
* @throws InvalidArgumentException |
| 37 |
*/ |
| 38 |
public function validateReorderIds(int $formId, array $orderedIds): void |
| 39 |
{ |
| 40 |
if (empty($orderedIds)) { |
| 41 |
throw new InvalidArgumentException( |
| 42 |
BackendStrings::getExceptionStrings()['invalid_request_data'] |
| 43 |
); |
| 44 |
} |
| 45 |
|
| 46 |
foreach ($orderedIds as $id) { |
| 47 |
if ((int) $id <= 0) { |
| 48 |
throw new InvalidArgumentException( |
| 49 |
BackendStrings::getExceptionStrings()['invalid_request_data'] |
| 50 |
); |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
if (count($orderedIds) !== count(array_unique($orderedIds))) { |
| 55 |
throw new InvalidArgumentException( |
| 56 |
BackendStrings::getExceptionStrings()['invalid_request_data'] |
| 57 |
); |
| 58 |
} |
| 59 |
|
| 60 |
$existing = $this->confirmationRepository->getAllById($formId); |
| 61 |
$existingIds = array_map(static fn ($confirmation) => $confirmation->getId(), $existing); |
| 62 |
sort($existingIds); |
| 63 |
|
| 64 |
$normalizedIds = array_map('intval', $orderedIds); |
| 65 |
sort($normalizedIds); |
| 66 |
|
| 67 |
if ($normalizedIds !== $existingIds) { |
| 68 |
throw new InvalidArgumentException( |
| 69 |
BackendStrings::getExceptionStrings()['invalid_request_data'] |
| 70 |
); |
| 71 |
} |
| 72 |
} |
| 73 |
} |
| 74 |
|