FormActionDispatcher.php
59 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Kirki\App\FormActions; |
| 4 | |
| 5 | defined('ABSPATH') || exit; |
| 6 | |
| 7 | use Kirki\App\DTO\Form\FormConfigDTO; |
| 8 | |
| 9 | use function Kirki\Framework\app; |
| 10 | |
| 11 | /** |
| 12 | * Routes each configured form action to the handler registered for its type. |
| 13 | * |
| 14 | * Only the types a submission actually configures are resolved, so a form that |
| 15 | * uses one action type never instantiates the others' handlers. |
| 16 | */ |
| 17 | class FormActionDispatcher |
| 18 | { |
| 19 | /** |
| 20 | * @var array<string, class-string> Action type => handler class. |
| 21 | */ |
| 22 | protected $handler_map; |
| 23 | |
| 24 | /** |
| 25 | * @param array<string, class-string> $handler_map Action type => handler class. |
| 26 | */ |
| 27 | public function __construct(array $handler_map) |
| 28 | { |
| 29 | $this->handler_map = $handler_map; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Dispatch every configured action to its handler. |
| 34 | * |
| 35 | * @param array $form_data The submission data. |
| 36 | * @param FormConfigDTO $form_config The form configuration. |
| 37 | * @return bool Whether every dispatched action succeeded. |
| 38 | * @throws Exception on error |
| 39 | */ |
| 40 | public function dispatch(array $form_data, FormConfigDTO $form_config) |
| 41 | { |
| 42 | $success = true; |
| 43 | $handlers = []; |
| 44 | |
| 45 | foreach ($form_config->actions as $action) { |
| 46 | $type = $action['type'] ?? null; |
| 47 | |
| 48 | if (!$type || !isset($this->handler_map[$type])) { |
| 49 | continue; |
| 50 | } |
| 51 | |
| 52 | $handler = $handlers[$type] ?? ($handlers[$type] = app($this->handler_map[$type])); |
| 53 | $success = $handler->handle($action, $form_data, $form_config) && $success; |
| 54 | } |
| 55 | |
| 56 | return $success; |
| 57 | } |
| 58 | } |
| 59 |