diff --git a/CHANGELOG.md b/CHANGELOG.md index 3aaf032..115a63b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2022-11-09 4.5.2 +* Add validator for CRM URL + ## 2022-11-09 4.5.1 * Correction of RAM overflow during ICMP product catalog generation. diff --git a/VERSION b/VERSION index 99523d4..689f7fb 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -4.5.1 \ No newline at end of file +4.5.2 \ No newline at end of file diff --git a/resources/pot/retailcrm-es_ES.pot b/resources/pot/retailcrm-es_ES.pot index dcab8f6..18d23f1 100644 --- a/resources/pot/retailcrm-es_ES.pot +++ b/resources/pot/retailcrm-es_ES.pot @@ -64,9 +64,6 @@ msgstr "Los clientes y pedidos están subidos" msgid "Enter the correct API key" msgstr "Introduce la llave API correcta" -msgid "Enter the correct URL of Simla.com" -msgstr "Introduce el enlace del Simla.com correcto" - msgid "This functionality allows to generate ICML products catalog for uploading to Simla.com" msgstr "Esta función permite generar los catálogos de pedidos ICML para subida al Simla.com" @@ -163,7 +160,7 @@ msgstr "Ajustes de API" msgid "Enter your API key. You can find it in the administration section of Simla.com" msgstr "Introduce la llave API. Puede encontrarla en apartado administrativo del Simla.com" -msgid "Enter API of URL (https://yourdomain.simla.com)" +msgid "Enter API URL (https://yourdomain.simla.com)" msgstr "Introduce enlace de API (https://yourdomain.simla.com)" msgid "Integration with Simla.com management system" @@ -341,4 +338,34 @@ msgid "Cron tasks cleared" msgstr "Trabajos cron borrados" msgid "Untitled" -msgstr "Intitulado" \ No newline at end of file +msgstr "Intitulado" + +msgid "Incorrect protocol. Only https is allowed." +msgstr "Protocolo incorrecto. Sólo se permite https." + +msgid "The domain path must be empty." +msgstr "La ruta del dominio debe estar vacía." + +msgid "An invalid domain is specified." +msgstr "Se especifica un dominio no válido." + +msgid "The port does not need to be specified." +msgstr "No es necesario especificar el puerto." + +msgid "Incorrect Host URL." +msgstr "URL del Host incorrecta." + +msgid "Incorrect URL." +msgstr "URL incorrecta." + +msgid "The query must be blank." +msgstr "La consulta debe estar en blanco." + +msgid "The fragment should be blank." +msgstr "El fragmento debe estar en blanco." + +msgid "No need to provide authorization data." +msgstr "No es necesario proporcionar datos de autorización." + +msgid "Unable to obtain reference values." +msgstr "No se pueden obtener valores de referencia." diff --git a/resources/pot/retailcrm-ru_RU.pot b/resources/pot/retailcrm-ru_RU.pot index 375680b..8817fb2 100644 --- a/resources/pot/retailcrm-ru_RU.pot +++ b/resources/pot/retailcrm-ru_RU.pot @@ -73,9 +73,6 @@ msgstr "Клиенты и заказы были выгружены" msgid "Enter the correct API key" msgstr "Введите корректный API ключ" -msgid "Enter the correct URL of Simla.com" -msgstr "Введите корректный адрес Simla.com" - msgid "This functionality allows to generate ICML products catalog for uploading to Simla.com" msgstr "Эта функция позволяет сгенерировать ICML каталог товаров для выгрузки в Simla.com" @@ -172,7 +169,7 @@ msgstr "Настройки API" msgid "Enter your API key. You can find it in the administration section of Simla.com" msgstr "Введите API ключ. Вы можете найти его в административном разделе Simla.com" -msgid "Enter API of URL (https://yourdomain.simla.com)" +msgid "Enter API URL (https://yourdomain.simla.com)" msgstr "Введите API URL (https://yourdomain.simla.com)" msgid "Integration with Simla.com management system" @@ -352,3 +349,32 @@ msgstr "Cron задачи очищены" msgid "Untitled" msgstr "Без названия" +msgid "Incorrect protocol. Only https is allowed." +msgstr "Некорректный протокол. Допускается только https." + +msgid "The domain path must be empty." +msgstr "Путь к домену должен быть пустым." + +msgid "An invalid domain is specified." +msgstr "Указан недопустимый домен." + +msgid "The port does not need to be specified." +msgstr "Не нужно указывать порт." + +msgid "Incorrect Host URL." +msgstr "Некорректный URL хоста" + +msgid "Incorrect URL." +msgstr "Некорректный URL." + +msgid "The query must be blank." +msgstr "Запрос должен быть пустым." + +msgid "The fragment should be blank." +msgstr "Фрагмент должен быть пустым." + +msgid "No need to provide authorization data." +msgstr "Нет необходимости предоставлять авторизационные данные." + +msgid "Unable to obtain reference values." +msgstr "Не удалось получить эталонное значение" diff --git a/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php b/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php index 841c92c..dfa3ba6 100644 --- a/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php +++ b/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php @@ -22,6 +22,12 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration /** @var string */ public static $option_key; + /** @var WC_Retailcrm_Url_Validator*/ + private $urlValidator; + + /** @var string */ + private $crmUrl; + /** * WC_Retailcrm_Abstracts_Settings constructor. */ @@ -39,6 +45,9 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration ) { add_action('init', [$this, 'init_settings_fields'], 99); } + + // Initialization validator + $this->urlValidator = new WC_Retailcrm_Url_Validator(); } /** @@ -75,7 +84,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration 'api_url' => [ 'title' => __('API of URL', 'retailcrm'), 'type' => 'text', - 'description' => __( 'Enter API of URL (https://yourdomain.simla.com)', 'retailcrm' ), + 'description' => __('Enter API URL (https://yourdomain.simla.com)', 'retailcrm'), 'desc_tip' => true, 'default' => '' ], @@ -88,10 +97,6 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration ] ]; - $post = $this->get_post_data(); - $apiUrl = !empty($post[$this->plugin_id . $this->id . '_api_url']) ? $post[$this->plugin_id . $this->id . '_api_url'] : null; - $apiKey = !empty($post[$this->plugin_id . $this->id . '_api_key']) ? $post[$this->plugin_id . $this->id . '_api_key'] : null; - if ($this->apiClient) { if ( isset($_GET['page']) && $_GET['page'] == 'wc-settings' @@ -153,7 +158,6 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration 'type' => 'checkbox', 'desc_tip' => true, ]; - } /** @@ -579,18 +583,6 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration 'id' => 'clear_cron_tasks' ]; } - } elseif (empty($apiUrl) === false && empty($apiKey) === false) { - $api = new WC_Retailcrm_Proxy( - $apiUrl, - $apiKey, - $this->get_option('corporate_enabled', 'no') === 'yes' - ); - - $response = $api->apiVersions(); - - if ($response->isSuccessful()) { - header("Refresh:0"); - } } } @@ -686,7 +678,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration } /** - * Validate API url + * Validate CRM URL. * * @param string $key * @param string $value @@ -697,14 +689,17 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration */ public function validate_api_url_field($key, $value) { - $crmUrl = validateUrl($value); + $validateMessage = $this->urlValidator->validateUrl($value); - if (validateUrl($crmUrl) == '') { - WC_Admin_Settings::add_error(esc_html__('Enter the correct URL of Simla.com', 'retailcrm')); - header("Refresh:3"); + if ('' !== $validateMessage) { + $value = ''; + + WC_Admin_Settings::add_error(esc_html__($validateMessage, 'retailcrm')); } - return $crmUrl; + $this->crmUrl = $value; + + return $value; } /** @@ -719,30 +714,20 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration */ public function validate_api_key_field($key, $value) { - $crmUrl = $_POST['woocommerce_integration-retailcrm_api_url']; - // If entered the wrong URL, don't need to validate the API key. - if (validateUrl($crmUrl) == '') { + if ('' === $this->crmUrl) { return $value; } - $api = new WC_Retailcrm_Proxy( - $crmUrl, - $value, - $this->get_option('corporate_enabled', 'no') === 'yes' - ); - + $api = new WC_Retailcrm_Proxy($this->crmUrl, $value); $response = $api->apiVersions(); - if (!is_object($response)) { - $value = ''; - } - if (empty($response) || !$response->isSuccessful()) { - WC_Admin_Settings::add_error(esc_html__('Enter the correct API key', 'retailcrm')); - header("Refresh:3"); - $value = ''; + + WC_Admin_Settings::add_error(esc_html__('Enter the correct API key', 'retailcrm')); + } else { + header("Refresh:0"); } return $value; diff --git a/src/include/api/class-wc-retailcrm-client-v5.php b/src/include/api/class-wc-retailcrm-client-v5.php index a988b21..35ec6a4 100644 --- a/src/include/api/class-wc-retailcrm-client-v5.php +++ b/src/include/api/class-wc-retailcrm-client-v5.php @@ -35,9 +35,6 @@ class WC_Retailcrm_Client_V5 * @param string $url api url * @param string $apiKey api key * @param string $site site code - * - * @throws InvalidArgumentException - * */ public function __construct($url, $apiKey, $site = null) { diff --git a/src/include/api/class-wc-retailcrm-proxy.php b/src/include/api/class-wc-retailcrm-proxy.php index 8670f8e..f44f69c 100644 --- a/src/include/api/class-wc-retailcrm-proxy.php +++ b/src/include/api/class-wc-retailcrm-proxy.php @@ -138,4 +138,4 @@ if (!class_exists('WC_Retailcrm_Proxy')) : return !empty($response) ? $response : new WC_Retailcrm_Response(900, '{}'); } } -endif; \ No newline at end of file +endif; diff --git a/src/include/api/class-wc-retailcrm-request.php b/src/include/api/class-wc-retailcrm-request.php index 82d14d3..f21e3b1 100644 --- a/src/include/api/class-wc-retailcrm-request.php +++ b/src/include/api/class-wc-retailcrm-request.php @@ -33,16 +33,9 @@ class WC_Retailcrm_Request * @param string $url api url * @param array $defaultParameters array of parameters * - * @throws \InvalidArgumentException */ - public function __construct($url, array $defaultParameters = array()) + public function __construct($url, array $defaultParameters = []) { - if (false === stripos($url, 'https://')) { - throw new \InvalidArgumentException( - 'API schema requires HTTPS protocol' - ); - } - $this->url = $url; $this->defaultParameters = $defaultParameters; } diff --git a/src/include/functions.php b/src/include/functions.php index 95bf7fe..663d273 100644 --- a/src/include/functions.php +++ b/src/include/functions.php @@ -137,19 +137,6 @@ function is_wplogin() ); } - -/** - * Validate API url. - * - * @param string $url URL of Simla.com. - * - * @return string - */ -function validateUrl(string $url) -{ - return (preg_match("/https:\/\/(.*).(retailcrm.(pro|ru|es)|simla.com)/", $url)) ? $url : ''; -} - /** * Get shipping rate. * diff --git a/src/include/validators/class-wc-retailcrm-validator-exception.php b/src/include/validators/class-wc-retailcrm-validator-exception.php new file mode 100644 index 0000000..c7c882e --- /dev/null +++ b/src/include/validators/class-wc-retailcrm-validator-exception.php @@ -0,0 +1,10 @@ + + * @license http://retailcrm.ru Proprietary + * @link http://retailcrm.ru + * @see http://help.retailcrm.ru + */ + class WC_Retailcrm_Url_Constraint + { + /** + * @var string + */ + public $schemeFail = 'Incorrect protocol. Only https is allowed.'; + + /** + * @var string + */ + public $pathFail = 'The domain path must be empty.'; + + /** + * @var string + */ + public $portFail = 'The port does not need to be specified.'; + + /** + * @var string + */ + public $domainFail = 'An invalid domain is specified.'; + + /** + * @var string + */ + public $noValidUrlHost = 'Incorrect Host URL.'; + + /** + * @var string + */ + public $noValidUrl = 'Incorrect URL.'; + + /** + * @var string + */ + public $queryFail = 'The query must be blank.'; + + /** + * @var string + */ + public $fragmentFail = 'The fragment should be blank.'; + + /** + * @var string + */ + public $authFail = 'No need to provide authorization data.'; + + /** + * @var string + */ + public $getFileError = 'Unable to obtain reference values.'; + } +endif; diff --git a/src/include/validators/url-validator/class-wc-retailcrm-url-validator.php b/src/include/validators/url-validator/class-wc-retailcrm-url-validator.php new file mode 100644 index 0000000..0f1b245 --- /dev/null +++ b/src/include/validators/url-validator/class-wc-retailcrm-url-validator.php @@ -0,0 +1,205 @@ + + * @license http://retailcrm.ru Proprietary + * @link http://retailcrm.ru + * @see http://help.retailcrm.ru + */ + class WC_Retailcrm_Url_Validator extends WC_Retailcrm_Url_Constraint + { + const CRM_DOMAINS_URL = 'https://infra-data.retailcrm.tech/crm-domains.json'; + const BOX_DOMAINS_URL = 'https://infra-data.retailcrm.tech/box-domains.json'; + + /** + * @param string $crmUrl + * + * @return string + */ + public function validateUrl(string $crmUrl): string + { + $validateMessage = ''; + + try { + $filteredUrl = filter_var($crmUrl, FILTER_VALIDATE_URL); + + if (false === $filteredUrl) { + throw new ValidatorException($this->noValidUrl, 400); + } + + $urlArray = parse_url($filteredUrl); + + $this->validateUrlFormat($urlArray); + $this->validateUrlDomains($urlArray); + } catch (ValidatorException $exception) { + $validateMessage = $exception->getMessage(); + } + + return $validateMessage; + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function validateUrlFormat(array $crmUrl) + { + $this->checkHost($crmUrl); + $this->checkScheme($crmUrl); + $this->checkAuth($crmUrl); + $this->checkFragment($crmUrl); + $this->checkPath($crmUrl); + $this->checkPort($crmUrl); + $this->checkQuery($crmUrl); + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function validateUrlDomains(array $crmUrl) + { + $mainDomain = $this->getMainDomain($crmUrl['host']); + $existInCrm = $this->checkDomains(self::CRM_DOMAINS_URL, $mainDomain); + $existInBox = $this->checkDomains(self::BOX_DOMAINS_URL, $crmUrl['host']); + + if (false === $existInCrm && false === $existInBox) { + throw new ValidatorException($this->domainFail); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkHost(array $crmUrl) + { + if (empty($crmUrl['host'])) { + throw new ValidatorException($this->noValidUrlHost); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkScheme(array $crmUrl) + { + if (!empty($crmUrl['scheme']) && 'https' !== $crmUrl['scheme']) { + throw new ValidatorException($this->schemeFail); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkQuery(array $crmUrl) + { + if (!empty($crmUrl['query'])) { + throw new ValidatorException($this->queryFail); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkAuth(array $crmUrl) + { + if (!empty($crmUrl['pass']) || !empty($crmUrl['user'])) { + throw new ValidatorException($this->authFail); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkFragment(array $crmUrl) + { + if (!empty($crmUrl['fragment'])) { + throw new ValidatorException($this->fragmentFail); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkPort(array $crmUrl) + { + if (!empty($crmUrl['port'])) { + throw new ValidatorException($this->portFail); + } + } + + /** + * @param array $crmUrl + * + * @throws ValidatorException + */ + private function checkPath(array $crmUrl) + { + if (!empty($crmUrl['path']) && '/' !== $crmUrl['path']) { + throw new ValidatorException($this->pathFail); + } + } + + /** + * @param string $domainUrl + * + * @return array + * @throws ValidatorException + */ + private function getValidDomains(string $domainUrl): array + { + try { + $content = json_decode(file_get_contents($domainUrl), true); + + return array_column($content['domains'], 'domain'); + } catch (Exception $exception) { + throw new ValidatorException($this->getFileError); + } + } + + /** + * @param string $host + * + * @return string + */ + private function getMainDomain(string $host): string + { + $hostArray = explode('.', $host); + unset($hostArray[0]); + + return implode('.', $hostArray); + } + + /** + * @param string $crmDomainsUrl + * @param string $domainHost + * + * @return bool + * @throws ValidatorException + */ + private function checkDomains(string $crmDomainsUrl, string $domainHost): bool + { + return in_array($domainHost, $this->getValidDomains($crmDomainsUrl), true); + } + } +endif; diff --git a/src/languages/retailcrm-es_ES.mo b/src/languages/retailcrm-es_ES.mo index 8c7c8b1..be30a9f 100644 Binary files a/src/languages/retailcrm-es_ES.mo and b/src/languages/retailcrm-es_ES.mo differ diff --git a/src/languages/retailcrm-ru_RU.mo b/src/languages/retailcrm-ru_RU.mo index 9b8246d..35011bf 100644 Binary files a/src/languages/retailcrm-ru_RU.mo and b/src/languages/retailcrm-ru_RU.mo differ diff --git a/src/readme.txt b/src/readme.txt index 69f2979..4aef4a0 100644 --- a/src/readme.txt +++ b/src/readme.txt @@ -5,7 +5,7 @@ Tags: Интеграция, Simla.com, simla Requires PHP: 7.0 Requires at least: 5.3 Tested up to: 6.0 -Stable tag: 4.5.1 +Stable tag: 4.5.2 License: GPLv1 or later License URI: http://www.gnu.org/licenses/gpl-1.0.html @@ -82,6 +82,9 @@ Asegúrate de tener una clave API específica para cada tienda. Las siguientes i == Changelog == += 4.5.2 = +* Add validator for CRM URL + = 4.5.1 = * Correction of RAM overflow during ICMP product catalog generation. diff --git a/src/retailcrm.php b/src/retailcrm.php index 1cca569..62799a0 100644 --- a/src/retailcrm.php +++ b/src/retailcrm.php @@ -5,7 +5,7 @@ * Description: Integration plugin for WooCommerce & Simla.com * Author: RetailDriver LLC * Author URI: http://retailcrm.pro/ - * Version: 4.5.1 + * Version: 4.5.2 * Tested up to: 6.0 * WC requires at least: 5.4 * WC tested up to: 6.9 @@ -127,6 +127,9 @@ if (!class_exists( 'WC_Integration_Retailcrm')) : require_once(self::checkCustomFile('include/class-wc-retailcrm-base.php')); require_once(self::checkCustomFile('include/class-wc-retailcrm-uploader.php')); require_once(self::checkCustomFile('include/functions.php')); + require_once(self::checkCustomFile('include/validators/url-validator/class-wc-retailcrm-url-constraint.php')); + require_once(self::checkCustomFile('include/validators/url-validator/class-wc-retailcrm-url-validator.php')); + require_once(self::checkCustomFile('include/validators/class-wc-retailcrm-validator-exception.php')); } /** diff --git a/src/uninstall.php b/src/uninstall.php index 756cd67..d24f6ea 100644 --- a/src/uninstall.php +++ b/src/uninstall.php @@ -16,7 +16,7 @@ * * @link https://wordpress.org/plugins/woo-retailcrm/ * - * @version 4.5.1 + * @version 4.5.2 * * @package RetailCRM */ diff --git a/tests/datasets/data-base-retailcrm.php b/tests/datasets/data-base-retailcrm.php index bc2f880..aafe15a 100644 --- a/tests/datasets/data-base-retailcrm.php +++ b/tests/datasets/data-base-retailcrm.php @@ -15,6 +15,23 @@ namespace datasets; */ class DataBaseRetailCrm { + public static function getResponseCustomFields() + { + return [ + 'success' => true, + 'customFields' => [ + [ + 'name' => 'Test_Upload', + 'code' => 'test_upload', + ], + [ + 'name' => 'test123', + 'code' => 'test', + ], + ] + ]; + } + public static function getResponseStatuses() { return [ diff --git a/tests/helpers/class-wc-retailcrm-test-case-helper.php b/tests/helpers/class-wc-retailcrm-test-case-helper.php index a1f2a4c..217665f 100644 --- a/tests/helpers/class-wc-retailcrm-test-case-helper.php +++ b/tests/helpers/class-wc-retailcrm-test-case-helper.php @@ -20,7 +20,7 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case { $options = [ 'api_url' => 'https://example.retailcrm.ru', - 'api_key' => 'test_key', + 'api_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1', 'corporate_enabled' => 'yes', 'online_assistant' => 'code', 'p_draft' => 'no', diff --git a/tests/test-wc-retailcrm-base.php b/tests/test-wc-retailcrm-base.php index 4a81fcc..47f9860 100644 --- a/tests/test-wc-retailcrm-base.php +++ b/tests/test-wc-retailcrm-base.php @@ -20,34 +20,37 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper protected $responseMockDeliveryTypes; protected $responseMockPaymentTypes; protected $responseMockStatuses; + protected $responseMockCustomFields; protected $dataOptions; private $baseRetailcrm; public function setUp() { - $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') - ->disableOriginalConstructor() - ->setMethods( - [ - 'orderMethodsList', - 'deliveryTypesList', - 'paymentTypesList', - 'statusesList', - 'customFieldsList', - ] - ) - ->getMock(); + $this->apiMock = $this + ->getMockBuilder('\WC_Retailcrm_Proxy') + ->disableOriginalConstructor() + ->setMethods( + [ + 'orderMethodsList', + 'deliveryTypesList', + 'paymentTypesList', + 'statusesList', + 'customFieldsList', + ] + ) + ->getMock(); $this->setMockOrderMethods(); $this->setMockDeliveryTypes(); $this->setMockPaymentTypes(); $this->setMockStatuses(); + $this->setMockCustomFields(); $_GET['page'] = 'wc-settings'; $_GET['tab'] = 'integration'; $this->dataOptions = $this->setOptions(); - $this->baseRetailcrm = new \WC_Retailcrm_Base($this->apiMock); + $this->baseRetailcrm = new WC_Retailcrm_Base($this->apiMock); } public function test_retailcrm_form_fields() @@ -158,14 +161,14 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper public function test_option_cron_disabled() { $settings = $this->baseRetailcrm->api_sanitized( - array( + [ 'api_url' => 'https://example.retailcrm.ru', - 'api_key' => 'test_key', + 'api_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1', 'corporate_enabled' => 'yes', 'sync' => 'no', 'icml' => 'no', 'history' => 'no', - ) + ] ); $history = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_history')); @@ -180,7 +183,7 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper $this->assertArrayHasKey('api_url', $settings); $this->assertEquals('https://example.retailcrm.ru', $settings['api_url']); $this->assertArrayHasKey('api_key', $settings); - $this->assertEquals('test_key', $settings['api_key']); + $this->assertEquals('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1', $settings['api_key']); $this->assertArrayHasKey('corporate_enabled', $settings); $this->assertEquals('yes', $settings['corporate_enabled']); $this->assertArrayHasKey('sync', $settings); @@ -214,7 +217,7 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper public function test_get_cron_info_off() { - $this->baseRetailcrm->settings = array('sync' => 'no', 'icml' => 'no', 'history' => 'no'); + $this->baseRetailcrm->settings = ['sync' => 'no', 'icml' => 'no', 'history' => 'no']; ob_start(); $this->baseRetailcrm->get_cron_info(); @@ -263,11 +266,11 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper public function test_initialize_whatsapp_off() { - $this->baseRetailcrm->settings = array( + $this->baseRetailcrm->settings = [ 'whatsapp_active' => 'no', 'whatsapp_location_icon' => 'no', 'whatsapp_number' => '', - ); + ]; ob_start(); $this->baseRetailcrm->initialize_whatsapp(); @@ -278,7 +281,7 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper public function test_initialize_daemon_collector_off() { - $this->baseRetailcrm->settings = array('daemon_collector' => 'no', 'daemon_collector_key' => ''); + $this->baseRetailcrm->settings = ['daemon_collector' => 'no', 'daemon_collector_key' => '']; ob_start(); $this->baseRetailcrm->initialize_daemon_collector(); @@ -301,7 +304,7 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper public function test_initialize_analytics_off() { - $this->baseRetailcrm->settings = array('ua' => '', 'ua_code' => '', 'ua_custom' => ''); + $this->baseRetailcrm->settings = ['ua' => '', 'ua_code' => '', 'ua_custom' => '']; ob_start(); $this->baseRetailcrm->initialize_analytics(); @@ -312,31 +315,6 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper public function test_set_meta_fields() { - $responseApiMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') - ->disableOriginalConstructor() - ->setMethods(['isSuccessful']) - ->getMock(); - - $this->setMockResponse($responseApiMock, 'isSuccessful', true); - - $responseApiMock->setResponse( - [ - 'success' => true, - 'customFields' => [ - [ - 'name' => 'Test_Upload', - 'code' => 'test_upload', - ], - [ - 'name' => 'test123', - 'code' => 'test', - ], - ] - ] - ); - - $this->setMockResponse($this->apiMock, 'customFieldsList', $responseApiMock); - ob_start(); $this->baseRetailcrm->set_meta_fields(); @@ -378,6 +356,35 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper ob_end_clean(); } + public function test_validate_crm_url() + { + $this->assertEquals( + 'https://test.simla.com', + $this->baseRetailcrm->validate_api_url_field('', 'https://test.simla.com') + ); + $this->assertEquals( + 'https://test.retailcrm.ru', + $this->baseRetailcrm->validate_api_url_field('', 'https://test.retailcrm.ru') + ); + $this->assertEquals( + 'https://test.retailcrm.pro', + $this->baseRetailcrm->validate_api_url_field('', 'https://test.retailcrm.pro') + ); + $this->assertEquals( + '', + $this->baseRetailcrm->validate_api_url_field('', 'https://test.test.pro') + ); + + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', '')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'https://tedsast.simla.comssd')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'http://test.retailcrm.pro')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'https://test.simla.com?query=test')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'https://pass:user@test.simla.com')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'https://test.simla.com#fragment')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'https://test.simla.com:12345')); + $this->assertEquals('', $this->baseRetailcrm->validate_api_url_field('', 'https://test.simla.com/test')); + } + private function getJsonData($text) { preg_match('/{.*}/', $text, $matches); @@ -387,10 +394,12 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper private function setMockOrderMethods() { - $this->responseMockOrderMethods = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') - ->disableOriginalConstructor() - ->setMethods(array('isSuccessful')) - ->getMock(); + $this->responseMockOrderMethods = $this + ->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(['isSuccessful']) + ->getMock(); + $this->setMockResponse($this->responseMockOrderMethods, 'isSuccessful', true); $this->responseMockOrderMethods->setResponse(DataBaseRetailCrm::getResponseOrderMethods()); @@ -399,10 +408,12 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper private function setMockDeliveryTypes() { - $this->responseMockDeliveryTypes = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') - ->disableOriginalConstructor() - ->setMethods(array('isSuccessful')) - ->getMock(); + $this->responseMockDeliveryTypes = $this + ->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(['isSuccessful']) + ->getMock(); + $this->setMockResponse($this->responseMockDeliveryTypes, 'isSuccessful', true); $this->responseMockDeliveryTypes->setResponse(DataBaseRetailCrm::getResponseDeliveryTypes()); @@ -411,10 +422,12 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper private function setMockPaymentTypes() { - $this->responseMockPaymentTypes = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') - ->disableOriginalConstructor() - ->setMethods(array('isSuccessful')) - ->getMock(); + $this->responseMockPaymentTypes = $this + ->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(['isSuccessful']) + ->getMock(); + $this->setMockResponse($this->responseMockPaymentTypes, 'isSuccessful', true); $this->responseMockPaymentTypes->setResponse(DataBaseRetailCrm::getResponsePaymentTypes()); @@ -423,13 +436,30 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper private function setMockStatuses() { - $this->responseMockStatuses = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') - ->disableOriginalConstructor() - ->setMethods(array('isSuccessful')) - ->getMock(); + $this->responseMockStatuses = $this + ->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(['isSuccessful']) + ->getMock(); + $this->setMockResponse($this->responseMockStatuses, 'isSuccessful', true); $this->responseMockStatuses->setResponse(DataBaseRetailCrm::getResponseStatuses()); $this->setMockResponse($this->apiMock, 'statusesList', $this->responseMockStatuses); } + + private function setMockCustomFields() + { + $this->responseMockCustomFields = $this + ->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(['isSuccessful']) + ->getMock(); + + $this->setMockResponse($this->responseMockCustomFields, 'isSuccessful', true); + + $this->responseMockCustomFields->setResponse(DataBaseRetailCrm::getResponseCustomFields()); + + $this->setMockResponse($this->apiMock, 'customFieldsList', $this->responseMockCustomFields); + } } diff --git a/tests/test-wc-retailcrm-orders.php b/tests/test-wc-retailcrm-orders.php index 2107226..2b904a6 100644 --- a/tests/test-wc-retailcrm-orders.php +++ b/tests/test-wc-retailcrm-orders.php @@ -429,14 +429,6 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper $this->assertEquals(null, $rate); } - public function test_validate_url() - { - $this->assertEquals('https://test.simla.com', validateUrl('https://test.simla.com')); - - // Not valid url - $this->assertEquals('', validateUrl('https://test.com')); - } - public function test_is_corporate_crm_order() { $this->assertEquals(