From 5146d5319d6c047a52cebc8f37f6afbb50504e7f Mon Sep 17 00:00:00 2001 From: davidmolinacano Date: Mon, 7 Oct 2024 09:19:26 +0200 Subject: [PATCH] feat: Convert variables to camelCase + namespaces in Api classes --- lib/DoofinderApi.php | 87 +++++++++---------- ...er_api_index.php => DoofinderApiIndex.php} | 29 +++---- ...er_api_items.php => DoofinderApiItems.php} | 21 +++-- ...cript.php => DoofinderApiUniqueScript.php} | 11 ++- ...allation.php => DoofinderInstallation.php} | 18 ++-- lib/DoofinderLayerApi.php | 39 +++++++++ lib/SearchEngine.php | 9 +- lib/UpdateOnSave.php | 20 ++--- lib/doofinder_layer_api.php | 62 ------------- upgrade/upgrade-4.8.2.php | 5 +- 10 files changed, 133 insertions(+), 168 deletions(-) rename lib/{doofinder_api_index.php => DoofinderApiIndex.php} (54%) rename lib/{doofinder_api_items.php => DoofinderApiItems.php} (76%) rename lib/{doofinder_api_unique_script.php => DoofinderApiUniqueScript.php} (86%) rename lib/{doofinder_installation.php => DoofinderInstallation.php} (94%) create mode 100644 lib/DoofinderLayerApi.php delete mode 100644 lib/doofinder_layer_api.php diff --git a/lib/DoofinderApi.php b/lib/DoofinderApi.php index e3f8183..e2b2d31 100644 --- a/lib/DoofinderApi.php +++ b/lib/DoofinderApi.php @@ -37,16 +37,16 @@ class DoofinderApi const DEFAULT_API_VERSION = '6'; const VERSION = '5.2.3'; - private $api_key; // user API_KEY + private $apiKey; // user API_KEY private $hashid; // hashid of the doofinder account private $apiVersion; private $url; private $results; private $query; - private $search_options = []; // assoc. array with doofinder options to be sent as request parameters + private $searchOptions = []; // assoc. array with doofinder options to be sent as request parameters private $page = 1; // the page of the search results we're at - private $queryName; // the name of the last successfull query made - private $lastQuery; // the last successfull query made + private $queryName; // the name of the last successful query made + private $lastQuery; // the last successful query made private $total; // total number of results obtained private $maxScore; private $paramsPrefix = self::DEFAULT_PARAMS_PREFIX; @@ -69,10 +69,10 @@ class DoofinderApi * -'restrictedRequest'(default: $_REQUEST): =>restrict request object * to look for params when unserializing. either 'get' or 'post' */ - public function __construct($hashid, $api_key, $fromParams = false, $init_options = []) + public function __construct($hashid, $apiKey, $fromParams = false, $init_options = []) { - $zone_key_array = explode('-', $api_key); - $this->api_key = end($zone_key_array); + $zone_key_array = explode('-', $apiKey); + $this->apiKey = end($zone_key_array); $this->zone = \Configuration::get('DF_REGION'); $this->url = UrlManager::getRegionalUrl(DoofinderConstants::DOOPHOENIX_REGION_URL, $this->zone); @@ -150,7 +150,7 @@ private function reqHeaders() $headers = []; $headers[] = 'Expect:'; // Fixes the HTTP/1.1 417 Expectation Failed $authHeaderName = $this->apiVersion == '4' ? 'API Token: ' : 'authorization: '; - $headers[] = $authHeaderName . $this->api_key; // API Authorization + $headers[] = $authHeaderName . $this->apiKey; // API Authorization return $headers; } @@ -211,16 +211,16 @@ public function getOptions() public function query($query = null, $page = null, $options = []) { if ($query) { - $this->search_options['query'] = $query; + $this->searchOptions['query'] = $query; } if ($page) { - $this->search_options['page'] = (int) $page; + $this->searchOptions['page'] = (int) $page; } foreach ($options as $optionName => $optionValue) { - $this->search_options[$optionName] = $options[$optionName]; + $this->searchOptions[$optionName] = $options[$optionName]; } - $params = $this->search_options; + $params = $this->searchOptions; // translate filters if (!empty($params['filter'])) { @@ -230,7 +230,7 @@ public function query($query = null, $page = null, $options = []) } // no query? then match all documents - if (!$this->optionExists('query') || !trim($this->search_options['query'])) { + if (!$this->optionExists('query') || !trim($this->searchOptions['query'])) { $params['query_name'] = 'match_all'; } @@ -245,7 +245,7 @@ public function query($query = null, $page = null, $options = []) $dfResults = new DoofinderResults($this->apiCall('search', $params)); $this->page = $dfResults->getProperty('page'); $this->total = $dfResults->getProperty('total'); - $this->search_options['query'] = $dfResults->getProperty('query'); + $this->searchOptions['query'] = $dfResults->getProperty('query'); $this->maxScore = $dfResults->getProperty('max_score'); $this->queryName = $dfResults->getProperty('query_name'); $this->lastQuery = $dfResults->getProperty('query'); @@ -297,9 +297,9 @@ public function getPage() public function setFilter($filterName, $filter) { if (!$this->optionExists('filter')) { - $this->search_options['filter'] = []; + $this->searchOptions['filter'] = []; } - $this->search_options['filter'][$filterName] = $filter; + $this->searchOptions['filter'][$filterName] = $filter; } /** @@ -315,7 +315,7 @@ public function setFilter($filterName, $filter) */ public function getFilter($filterName) { - if ($this->optionExists('filter') && isset($this->search_options['filter'][$filterName])) { + if ($this->optionExists('filter') && isset($this->searchOptions['filter'][$filterName])) { return $this->filter[$filterName]; } @@ -331,8 +331,8 @@ public function getFilter($filterName) */ public function getFilters() { - if (isset($this->search_options['filter'])) { - return $this->search_options['filter']; + if (isset($this->searchOptions['filter'])) { + return $this->searchOptions['filter']; } else { return false; } @@ -349,14 +349,14 @@ public function getFilters() public function addTerm($filterName, $term) { if (!$this->optionExists('filter')) { - $this->search_options['filter'] = [$filterName => []]; + $this->searchOptions['filter'] = [$filterName => []]; } - if (!isset($this->search_options['filter'][$filterName])) { + if (!isset($this->searchOptions['filter'][$filterName])) { $this->filter[$filterName] = []; - $this->search_options['filter'][$filterName] = []; + $this->searchOptions['filter'][$filterName] = []; } $this->filter[$filterName][] = $term; - $this->search_options['filter'][$filterName][] = $term; + $this->searchOptions['filter'][$filterName][] = $term; } /** @@ -369,8 +369,8 @@ public function addTerm($filterName, $term) */ public function removeTerm($filterName, $term) { - if ($this->optionExists('filter') && isset($this->search_options['filter'][$filterName]) - && in_array($term, $this->search_options['filter'][$filterName]) + if ($this->optionExists('filter') && isset($this->searchOptions['filter'][$filterName]) + && in_array($term, $this->searchOptions['filter'][$filterName]) ) { function filter_me($value) { @@ -379,8 +379,8 @@ function filter_me($value) return $value != $term; } - $this->search_options['filter'][$filterName] = - array_filter($this->search_options['filter'][$filterName], 'filter_me'); + $this->searchOptions['filter'][$filterName] = + array_filter($this->searchOptions['filter'][$filterName], 'filter_me'); } } @@ -396,16 +396,16 @@ function filter_me($value) public function setRange($filterName, $from = null, $to = null) { if (!$this->optionExists('filter')) { - $this->search_options['filter'] = [$filterName => []]; + $this->searchOptions['filter'] = [$filterName => []]; } - if (!isset($this->search_options['filter'][$filterName])) { - $this->search_options['filter'][$filterName] = []; + if (!isset($this->searchOptions['filter'][$filterName])) { + $this->searchOptions['filter'][$filterName] = []; } if ($from) { - $this->search_options['filter'][$filterName]['from'] = $from; + $this->searchOptions['filter'][$filterName]['from'] = $from; } if ($to) { - $this->search_options['filter'][$filterName]['to'] = $from; + $this->searchOptions['filter'][$filterName]['to'] = $from; } } @@ -418,7 +418,7 @@ public function setRange($filterName, $from = null, $to = null) */ public function toQuerystring($page = null) { - foreach ($this->search_options as $paramName => $paramValue) { + foreach ($this->searchOptions as $paramName => $paramValue) { if ($paramName == 'query') { $toParams[$this->queryParameter] = $paramValue; } else { @@ -446,12 +446,11 @@ public function fromQuerystring() $doofinderReqParams = array_filter(array_keys($this->serializationArray), [$this, 'belongsToDoofinder']); foreach ($doofinderReqParams as $dfReqParam) { - if ($dfReqParam == $this->queryParameter) { - $keey = 'query'; - } else { - $keey = substr($dfReqParam, strlen($this->paramsPrefix)); + $key = 'query'; + if ($dfReqParam !== $this->queryParameter) { + $key = substr($dfReqParam, strlen($this->paramsPrefix)); } - $this->search_options[$keey] = $this->serializationArray[$dfReqParam]; + $this->searchOptions[$key] = $this->serializationArray[$dfReqParam]; } } @@ -499,7 +498,7 @@ private function belongsToDoofinder($paramName) /** * optionExists * - * checks whether a search option is defined in $this->search_options + * checks whether a search option is defined in $this->searchOptions * * @param string $optionName * @@ -507,7 +506,7 @@ private function belongsToDoofinder($paramName) */ private function optionExists($optionName) { - return array_key_exists($optionName, $this->search_options); + return array_key_exists($optionName, $this->searchOptions); } /** @@ -556,7 +555,7 @@ public function numPages() public function getRpp() { - $rpp = $this->optionExists('rpp') ? $this->search_options['rpp'] : null; + $rpp = $this->optionExists('rpp') ? $this->searchOptions['rpp'] : null; $rpp = $rpp ? $rpp : self::DEFAULT_RPP; return $rpp; @@ -614,9 +613,9 @@ public function test($translationFunction, $onlyOneLang = false) foreach (\Language::getLanguages(true, $context->shop->id) as $lang) { if (!$onlyOneLang || ($onlyOneLang && $lang['iso_code'])) { $lang_iso = \Tools::strtoupper($lang['iso_code']); - $hash_id = \Configuration::get('DF_HASHID_' . $currency . '_' . $lang_iso); - $api_key = \Configuration::get('DF_API_KEY'); - if ($hash_id && $api_key) { + $hashid = \Configuration::get('DF_HASHID_' . $currency . '_' . $lang_iso); + $apiKey = \Configuration::get('DF_API_KEY'); + if ($hashid && $apiKey) { try { $dfOptions = $this->getOptions(); if ($dfOptions) { diff --git a/lib/doofinder_api_index.php b/lib/DoofinderApiIndex.php similarity index 54% rename from lib/doofinder_api_index.php rename to lib/DoofinderApiIndex.php index 80430f6..a88db34 100644 --- a/lib/doofinder_api_index.php +++ b/lib/DoofinderApiIndex.php @@ -12,37 +12,36 @@ * @copyright Doofinder * @license GPLv3 */ -use PrestaShop\Module\Doofinder\Lib\EasyREST; + +namespace PrestaShop\Module\Doofinder\Lib; if (!defined('_PS_VERSION_')) { exit; } -const API_URL = 'https://{region}-plugins.doofinder.com'; - class DoofinderApiIndex { - private $api_key; - private $api_url; + private $apiKey; + private $apiUrl; - public function __construct($api_key, $region) + public function __construct($apiKey, $region) { - $this->api_key = $api_key; - $this->api_url = str_replace('{region}', $region, API_URL); + $this->apiKey = $apiKey; + $this->apiUrl = UrlManager::getRegionalUrl(DoofinderConstants::DOOPLUGINS_REGION_URL, $region); } /** * Make a request to the plugins API to reprocess all the feeds * - * @param string $installation_id - * @param string $callback_url + * @param string $installationId + * @param string $callbackUrl */ - public function invokeReindexing($installation_id, $callback_url = '') + public function invokeReindexing($installationId, $callbackUrl = '') { - $api_endpoint = $this->api_url . '/process-feed'; - $json_data = json_encode(['store_id' => $installation_id, 'callback_url' => $callback_url]); + $apiEndpoint = $this->apiUrl . '/process-feed'; + $jsonData = json_encode(['store_id' => $installationId, 'callback_url' => $callbackUrl]); - return $this->post($api_endpoint, $json_data); + return $this->post($apiEndpoint, $jsonData); } private function post($url, $payload) @@ -55,7 +54,7 @@ private function post($url, $payload) false, false, 'application/json', - ['Authorization: Token ' . $this->api_key] + ['Authorization: Token ' . $this->apiKey] ); return json_decode($response->response, true); diff --git a/lib/doofinder_api_items.php b/lib/DoofinderApiItems.php similarity index 76% rename from lib/doofinder_api_items.php rename to lib/DoofinderApiItems.php index 08ecb48..daac617 100644 --- a/lib/doofinder_api_items.php +++ b/lib/DoofinderApiItems.php @@ -12,26 +12,25 @@ * @copyright Doofinder * @license GPLv3 */ -use PrestaShop\Module\Doofinder\Lib\EasyREST; + +namespace PrestaShop\Module\Doofinder\Lib; if (!defined('_PS_VERSION_')) { exit; } -const API_URL = 'https://{region}-plugins.doofinder.com'; - class DoofinderApiItems { private $hashid; - private $api_key; - private $api_url; + private $apiKey; + private $apiUrl; private $type; - public function __construct($hashid, $api_key, $region, $type = 'product') + public function __construct($hashid, $apiKey, $region, $type = 'product') { $this->hashid = $hashid; - $this->api_key = $api_key; - $this->api_url = str_replace('{region}', $region, API_URL); + $this->apiKey = $apiKey; + $this->apiUrl = UrlManager::getRegionalUrl(DoofinderConstants::DOOPLUGINS_REGION_URL, $region); $this->type = $type; } @@ -44,7 +43,7 @@ public function updateBulk($payload) { $endpoint = '/item/' . $this->hashid . '/' . $this->type . '?platform=prestashop&action=update'; - $url = $this->api_url . $endpoint; + $url = $this->apiUrl . $endpoint; return $this->post($url, $payload); } @@ -58,7 +57,7 @@ public function deleteBulk($payload) { $endpoint = '/item/' . $this->hashid . '/' . $this->type . '?platform=prestashop&action=delete'; - $url = $this->api_url . $endpoint; + $url = $this->apiUrl . $endpoint; return $this->post($url, $payload); } @@ -73,7 +72,7 @@ private function post($url, $payload) false, false, 'application/json', - ['Authorization: Token ' . $this->api_key] + ['Authorization: Token ' . $this->apiKey] ); return json_decode($response->response, true); diff --git a/lib/doofinder_api_unique_script.php b/lib/DoofinderApiUniqueScript.php similarity index 86% rename from lib/doofinder_api_unique_script.php rename to lib/DoofinderApiUniqueScript.php index 57a5df8..1606ee3 100644 --- a/lib/doofinder_api_unique_script.php +++ b/lib/DoofinderApiUniqueScript.php @@ -12,14 +12,13 @@ * @copyright Doofinder * @license GPLv3 */ -use PrestaShop\Module\Doofinder\Lib\EasyREST; + +namespace PrestaShop\Module\Doofinder\Lib; if (!defined('_PS_VERSION_')) { exit; } -const API_URL = 'https://{region}-plugins.doofinder.com'; - class DoofinderApiUniqueScript { private $installationId; @@ -30,7 +29,7 @@ public function __construct($installationId, $region, $apiKey) { $this->installationId = $installationId; $this->apiKey = $apiKey; - $this->apiUrl = str_replace('{region}', $region, API_URL); + $this->apiUrl = UrlManager::getRegionalUrl(DoofinderConstants::DOOPLUGINS_REGION_URL, $region); } /** @@ -57,11 +56,11 @@ private function post($url) 'installation_id' => $this->installationId, ]; - $json_store_data = json_encode($body); + $jsonStoreData = json_encode($body); $response = $client->post( $url, - $json_store_data, + $jsonStoreData, false, false, 'application/json', diff --git a/lib/doofinder_installation.php b/lib/DoofinderInstallation.php similarity index 94% rename from lib/doofinder_installation.php rename to lib/DoofinderInstallation.php index 7554bb8..1ec1574 100644 --- a/lib/doofinder_installation.php +++ b/lib/DoofinderInstallation.php @@ -15,8 +15,6 @@ namespace PrestaShop\Module\Doofinder\Lib; -use Doofinder; - if (!defined('_PS_VERSION_')) { exit; } @@ -197,10 +195,10 @@ private static function _createStore($shop) exit('ko'); } } else { - $error_msg = "Create Store failed with code {$response->getResponseCode()} and message '{$response->getResponseMessage()}'"; - $response_msg = 'Response: ' . print_r($response->response, true); - DoofinderConfig::debug($error_msg); - DoofinderConfig::debug($response_msg); + $errorMsg = "Create Store failed with code {$response->getResponseCode()} and message '{$response->getResponseMessage()}'"; + $responseMsg = 'Response: ' . print_r($response->response, true); + DoofinderConfig::debug($errorMsg); + DoofinderConfig::debug($responseMsg); echo $response->response; exit; } @@ -240,7 +238,7 @@ public static function uninstallTabs() */ public static function deleteConfigVars() { - $config_vars = [ + $configVars = [ 'DF_AI_ADMIN_ENDPOINT', 'DF_AI_API_ENDPOINT', 'DF_AI_APIKEY', @@ -283,15 +281,15 @@ public static function deleteConfigVars() 'DF_FEED_INDEXED', ]; - $hashid_vars = array_column( + $hashidVars = array_column( \Db::getInstance()->executeS(' SELECT name FROM ' . _DB_PREFIX_ . "configuration where name like 'DF_HASHID_%'"), 'name' ); - $config_vars = array_merge($config_vars, $hashid_vars); + $configVars = array_merge($configVars, $hashidVars); - foreach ($config_vars as $var) { + foreach ($configVars as $var) { \Configuration::deleteByName($var); } diff --git a/lib/DoofinderLayerApi.php b/lib/DoofinderLayerApi.php new file mode 100644 index 0000000..ca0c2a0 --- /dev/null +++ b/lib/DoofinderLayerApi.php @@ -0,0 +1,39 @@ +get( + $apiEndpoint, + null, + false, + false, + 'application/json', + ['Authorization: Token ' . $apiKey] + ); + + return json_decode($response->response, true); + } +} diff --git a/lib/SearchEngine.php b/lib/SearchEngine.php index 5874e05..6b5007b 100644 --- a/lib/SearchEngine.php +++ b/lib/SearchEngine.php @@ -52,14 +52,11 @@ public static function getHashId($idLang, $idCurrency) */ public static function setSearchEnginesByConfig() { - if (!class_exists('DoofinderLayerApi')) { - require_once 'doofinder_layer_api.php'; - } $installationID = \Configuration::get('DF_INSTALLATION_ID'); $apiKey = \Configuration::get('DF_API_KEY'); $region = \Configuration::get('DF_REGION'); - $data = \DoofinderLayerApi::getInstallationData($installationID, $apiKey, $region); + $data = DoofinderLayerApi::getInstallationData($installationID, $apiKey, $region); foreach ($data['config']['search_engines'] as $lang => $currencies) { foreach ($currencies as $currency => $hashid) { @@ -96,8 +93,8 @@ protected static function getLanguageCode($code) { // $code is in the form of 'xx-YY' where xx is the language code // and 'YY' a country code identifying a variant of the language. - $lang_country = explode('-', $code); + $langCountry = explode('-', $code); - return $lang_country[0]; + return $langCountry[0]; } } diff --git a/lib/UpdateOnSave.php b/lib/UpdateOnSave.php index 126fd62..f01305b 100644 --- a/lib/UpdateOnSave.php +++ b/lib/UpdateOnSave.php @@ -29,15 +29,15 @@ class UpdateOnSave public static function allowProcessItemsQueue() { if (\Configuration::get('DF_UPDATE_ON_SAVE_DELAY')) { - $last_exec = \Configuration::get('DF_UPDATE_ON_SAVE_LAST_EXEC', null, null, null, 0); + $lastExec = \Configuration::get('DF_UPDATE_ON_SAVE_LAST_EXEC', null, null, null, 0); $delay = (int) \Configuration::get('DF_UPDATE_ON_SAVE_DELAY', null, null, null, 30); if (is_int($delay)) { - $last_exec_ts = strtotime($last_exec); + $lastExecTs = strtotime($lastExec); - $diff_min = (time() - $last_exec_ts) / 60; + $diffMin = (time() - $lastExecTs) / 60; - if ($diff_min > $delay) { + if ($diffMin > $delay) { return true; } } @@ -264,12 +264,10 @@ private static function updateItemsApi($hashid, $type, $payload) return; } - require_once 'doofinder_api_items.php'; - $apikey = explode('-', \Configuration::get('DF_API_KEY'))[1]; $region = \Configuration::get('DF_REGION'); - $api = new \DoofinderApiItems($hashid, $apikey, $region, $type); + $api = new DoofinderApiItems($hashid, $apikey, $region, $type); $response = $api->updateBulk($payload); if (isset($response['error']) && !empty($response['error'])) { @@ -295,12 +293,10 @@ private static function deleteItemsApi($hashid, $type, $payload) return; } - require_once 'doofinder_api_items.php'; - $apikey = explode('-', \Configuration::get('DF_API_KEY'))[1]; $region = \Configuration::get('DF_REGION'); - $api = new \DoofinderApiItems($hashid, $apikey, $region, $type); + $api = new DoofinderApiItems($hashid, $apikey, $region, $type); $response = $api->deleteBulk(json_encode($payload)); if (isset($response['error']) && !empty($response['error'])) { @@ -319,11 +315,9 @@ private static function deleteItemsApi($hashid, $type, $payload) */ public static function indexApiInvokeReindexing() { - require_once 'doofinder_api_index.php'; - $region = \Configuration::get('DF_REGION'); $api_key = \Configuration::get('DF_API_KEY'); - $api = new \DoofinderApiIndex($api_key, $region); + $api = new DoofinderApiIndex($api_key, $region); $response = $api->invokeReindexing(\Configuration::get('DF_INSTALLATION_ID'), UrlManager::getProcessCallbackUrl()); if (empty($response) || 200 !== $response['status']) { DoofinderConfig::debug('Error while invoking reindexing: ' . json_encode($response)); diff --git a/lib/doofinder_layer_api.php b/lib/doofinder_layer_api.php deleted file mode 100644 index 220e99e..0000000 --- a/lib/doofinder_layer_api.php +++ /dev/null @@ -1,62 +0,0 @@ -get($api_endpoint); - - if ((int) $response->headers['code'] === 200) { - $options = json_decode($response->response)->options; - if ($currency === $options->currency && $language === $options->language) { - return $options->hashid; - } - } - - return null; - } - - public static function getInstallationData($installationID, $api_key, $region = 'eu1') - { - $api_endpoint = 'https://' . $region . '-plugins.doofinder.com/installations/' . $installationID; - - $client = new EasyREST(); - $response = $client->get( - $api_endpoint, - null, - false, - false, - 'application/json', - ['Authorization: Token ' . $api_key] - ); - - return json_decode($response->response, true); - } -} diff --git a/upgrade/upgrade-4.8.2.php b/upgrade/upgrade-4.8.2.php index ddbf059..85dc3be 100644 --- a/upgrade/upgrade-4.8.2.php +++ b/upgrade/upgrade-4.8.2.php @@ -23,11 +23,14 @@ * @license https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0) * International Registered Trademark & Property of PrestaShop SA */ + +use PrestaShop\Module\Doofinder\Lib\DoofinderApiUniqueScript; + if (!defined('_PS_VERSION_')) { exit; } -require_once _PS_MODULE_DIR_ . 'doofinder/lib/doofinder_api_unique_script.php'; +require_once _PS_MODULE_DIR_ . 'doofinder/autoloader.php'; function upgrade_module_4_8_2($module) {