From 7dcc979461090ecf8e865f1f2cf0b94e9291f7d6 Mon Sep 17 00:00:00 2001 From: David Remer Date: Wed, 8 Jul 2020 13:49:31 +0300 Subject: [PATCH] delete webhook when resetting settings --- .../src/Settings/SettingsListener.php | 14 ++++++++++--- .../ppcp-webhooks/src/WebhookRegistrar.php | 20 ++++++++++++++++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/modules.local/ppcp-wc-gateway/src/Settings/SettingsListener.php b/modules.local/ppcp-wc-gateway/src/Settings/SettingsListener.php index d9b699324..41b67dd7a 100644 --- a/modules.local/ppcp-wc-gateway/src/Settings/SettingsListener.php +++ b/modules.local/ppcp-wc-gateway/src/Settings/SettingsListener.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Inpsyde\PayPalCommerce\WcGateway\Settings; use Inpsyde\PayPalCommerce\Onboarding\State; +use Inpsyde\PayPalCommerce\Webhooks\WebhookRegistrar; class SettingsListener { @@ -12,10 +13,15 @@ class SettingsListener public const NONCE = 'ppcp-settings'; private $settings; private $settingFields; - public function __construct(Settings $settings, array $settingFields) - { + private $webhookRegistrar; + public function __construct( + Settings $settings, + array $settingFields, + WebhookRegistrar $webhookRegistrar + ) { $this->settings = $settings; $this->settingFields = $settingFields; + $this->webhookRegistrar = $webhookRegistrar; } public function listen() @@ -32,6 +38,7 @@ class SettingsListener if (isset($_POST['save']) && sanitize_text_field(wp_unslash($_POST['save'])) === 'reset') { $this->settings->reset(); $this->settings->persist(); + $this->webhookRegistrar->unregister(); return; } @@ -74,9 +81,10 @@ class SettingsListener $settings[$key] = $valuesToSave; break; case 'select': + $options = array_keys($config['options']); $settings[$key] = isset($rawData[$key]) && in_array( sanitize_text_field($rawData[$key]), - $config['options'], + $options, true ) ? sanitize_text_field($rawData[$key]) : null; break; diff --git a/modules.local/ppcp-webhooks/src/WebhookRegistrar.php b/modules.local/ppcp-webhooks/src/WebhookRegistrar.php index 87fcc4e44..5807739d8 100644 --- a/modules.local/ppcp-webhooks/src/WebhookRegistrar.php +++ b/modules.local/ppcp-webhooks/src/WebhookRegistrar.php @@ -41,7 +41,7 @@ class WebhookRegistrar } update_option( self::KEY, - $webhook->toArray() + $created->toArray() ); return true; } catch (RuntimeException $error) { @@ -52,4 +52,22 @@ class WebhookRegistrar return false; } } + + public function unregister() : bool { + $data = (array) get_option(self::KEY, []); + if (! $data) { + return false; + } + try { + $webhook = $this->webhookFactory->fromArray($data); + $success = $this->endpoint->delete($webhook); + } catch (RuntimeException $error) { + return false; + } + + if ($success) { + delete_option(self::KEY); + } + return $success; + } } \ No newline at end of file