WebhookActionHandler.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Kirki\App\FormActions\Actions; |
| 4 | |
| 5 | defined('ABSPATH') || exit; |
| 6 | |
| 7 | use Kirki\App\Constants\Form\FormWebhookMethods; |
| 8 | use Kirki\App\Contracts\FormActionHandler; |
| 9 | use Kirki\App\DTO\Form\FormConfigDTO; |
| 10 | use Kirki\Framework\Supports\Facades\Http; |
| 11 | |
| 12 | /** |
| 13 | * Delivers a submission to a single configured webhook endpoint. |
| 14 | * |
| 15 | * Unlike the other channels, a webhook transport failure marks the whole |
| 16 | * submission as failed, so this is the only handler whose return value can be |
| 17 | * false. |
| 18 | */ |
| 19 | class WebhookActionHandler implements FormActionHandler |
| 20 | { |
| 21 | public function handle(array $webhook, array $form_data, FormConfigDTO $form_config) |
| 22 | { |
| 23 | if (!isset($webhook['action'], $webhook['method'])) { |
| 24 | return false; |
| 25 | } |
| 26 | |
| 27 | if ($webhook['method'] === FormWebhookMethods::GET) { |
| 28 | return $this->send_get($webhook['action'], $form_data); |
| 29 | } |
| 30 | |
| 31 | if ($webhook['method'] === FormWebhookMethods::POST) { |
| 32 | return $this->send_post($webhook['action'], $form_data); |
| 33 | } |
| 34 | |
| 35 | return false; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Send a GET webhook request. |
| 40 | * |
| 41 | * @param string $url Webhook URL. |
| 42 | * @param array $form_data Form data. |
| 43 | * @return bool Success status. |
| 44 | */ |
| 45 | protected function send_get($url, $form_data) |
| 46 | { |
| 47 | $query_string = http_build_query($form_data); |
| 48 | $url = rtrim($url, '/'); |
| 49 | $url .= '/'; |
| 50 | |
| 51 | $response = Http::get($url . '?' . $query_string); |
| 52 | |
| 53 | return $response->status() !== 0; |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Send a POST webhook request. |
| 58 | * |
| 59 | * @param string $url Webhook URL. |
| 60 | * @param array $form_data Form data. |
| 61 | * @return bool Success status. |
| 62 | */ |
| 63 | protected function send_post($url, $form_data) |
| 64 | { |
| 65 | $response = Http::as_form()->post($url, $form_data); |
| 66 | |
| 67 | return $response->status() !== 0; |
| 68 | } |
| 69 | } |
| 70 |