WebhookHandler.php
56 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Reach\Api\Webhooks\Handlers; |
| 4 | |
| 5 | use Hostinger\Reach\Api\Handlers\ReachApiHandler; |
| 6 | use Hostinger\Reach\Repositories\FormRepository; |
| 7 | |
| 8 | abstract class WebhookHandler { |
| 9 | |
| 10 | protected ReachApiHandler $reach_api_handler; |
| 11 | protected FormRepository $form_repository; |
| 12 | |
| 13 | public function __construct( ReachApiHandler $reach_api_handler, FormRepository $form_repository ) { |
| 14 | $this->reach_api_handler = $reach_api_handler; |
| 15 | $this->form_repository = $form_repository; |
| 16 | } |
| 17 | |
| 18 | public function init(): void { |
| 19 | add_action( 'init', array( $this, 'init_hooks' ) ); |
| 20 | } |
| 21 | |
| 22 | public function is_enabled(): bool { |
| 23 | return $this->reach_api_handler->is_connected() && $this->is_automation_active(); |
| 24 | } |
| 25 | |
| 26 | public function is_automation_active(): bool { |
| 27 | return $this->form_repository->is_form_active( $this->get_name() ); |
| 28 | } |
| 29 | |
| 30 | public function increase_automation_submission_counter(): bool { |
| 31 | return $this->form_repository->submit( array( 'form_id' => $this->get_name() ) ); |
| 32 | } |
| 33 | |
| 34 | public function handle( string $email, mixed $data ): bool { |
| 35 | $webhook_payload = array( |
| 36 | 'name' => $this->get_name(), |
| 37 | 'contact' => array( |
| 38 | 'email' => $email, |
| 39 | ), |
| 40 | 'metadata' => $this->get_metadata( $data ), |
| 41 | ); |
| 42 | |
| 43 | $response = $this->reach_api_handler->post_webhook_event( $webhook_payload ); |
| 44 | if ( ! $response->is_error() ) { |
| 45 | $this->increase_automation_submission_counter(); |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | return false; |
| 50 | } |
| 51 | |
| 52 | abstract public function init_hooks(): void; |
| 53 | abstract public function get_metadata( mixed $data ): array; |
| 54 | abstract public function get_name(): string; |
| 55 | } |
| 56 |