diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..d5797f8 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,12 @@ +on: [push, pull_request] +name: Main +jobs: + php-cs-fixer: + name: PHP-CS-Fixer + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: PHP-CS-Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --config=.php-cs-fixer.php --dry-run --using-cache=no -v --diff diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..6198d4f --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,76 @@ +in([ + __DIR__.'/retailcrm', + __DIR__.'/tests', +]); + +return (new PhpCsFixer\Config()) + ->setRiskyAllowed(true) + ->setRules([ + '@Symfony' => true, + '@Symfony:risky' => true, + 'psr_autoloading' => false, + 'array_indentation' => true, + 'cast_spaces' => [ + 'space' => 'single', + ], + 'yoda_style' => [ + 'equal' => true, + 'identical' => true, + 'less_and_greater' => true + ], + + 'date_time_immutable' => true, + 'combine_consecutive_issets' => true, + 'concat_space' => [ + 'spacing' => 'one', + ], + 'error_suppression' => [ + 'mute_deprecation_error' => false, + 'noise_remaining_usages' => false, + 'noise_remaining_usages_exclude' => [], + ], + 'function_to_constant' => false, + 'method_chaining_indentation' => true, + 'no_alias_functions' => false, + 'no_superfluous_phpdoc_tags' => false, + 'non_printable_character' => [ + 'use_escape_sequences_in_strings' => true, + ], + 'phpdoc_align' => [ + 'align' => 'left', + ], + 'phpdoc_summary' => false, + 'protected_to_private' => false, + 'self_accessor' => false, + 'single_line_throw' => false, + 'no_alias_language_construct_call' => false, + 'visibility_required' => false, + 'ordered_imports' => true, + 'global_namespace_import' => [ + 'import_classes' => false, + 'import_constants' => false, + 'import_functions' => false, + ], + 'native_constant_invocation' => false, + 'native_function_invocation' => false, + 'modernize_types_casting' => true, + 'is_null' => true, + 'operator_linebreak' => [ + 'only_booleans' => true, + 'position' => 'beginning', + ], + 'ternary_to_null_coalescing' => false, + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'phpdoc_annotation_without_dot' => false, + 'logical_operators' => true, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'this'], + 'multiline_whitespace_before_semicolons' => ['strategy' => 'new_line_for_chained_calls'], + + ]) + ->setFinder($finder); diff --git a/Makefile b/Makefile index f04d4c8..ac06d52 100644 --- a/Makefile +++ b/Makefile @@ -52,6 +52,10 @@ else && bash travis-scripts/install-prestashop.sh endif +lint: + php-cs-fixer fix --config=$(ROOT_DIR)/.php-cs-fixer.php -v + + test: ifeq ($(COMPOSERV1),1) cd $(PRESTASHOP_DIR) \ diff --git a/retailcrm/bootstrap.php b/retailcrm/bootstrap.php index 24087e1..69a0731 100644 --- a/retailcrm/bootstrap.php +++ b/retailcrm/bootstrap.php @@ -43,9 +43,7 @@ * where this class resides. Additional options can be provided to control the naming * convention of the class files. * - * @package Autoloader * @license http://opensource.org/licenses/MIT MIT License - * */ class RetailcrmAutoloader { @@ -56,13 +54,11 @@ class RetailcrmAutoloader /** * The top level directory where recursion will begin. - * */ protected static $pathTop; /** * The top level directory where recursion for custom classes will begin. - * */ protected static $pathTopCustom; @@ -142,7 +138,7 @@ class RetailcrmAutoloader } } -RetailcrmAutoloader::setPath(realpath(dirname(__FILE__))); +RetailcrmAutoloader::setPath(realpath(__DIR__)); RetailcrmAutoloader::setPathCustom(realpath(_PS_MODULE_DIR_ . '/retailcrm/custom')); RetailcrmAutoloader::setFileExt('.php'); spl_autoload_register('RetailcrmAutoloader::loader'); diff --git a/retailcrm/cli.php b/retailcrm/cli.php index 22fff2c..a79b946 100644 --- a/retailcrm/cli.php +++ b/retailcrm/cli.php @@ -36,7 +36,7 @@ * to avoid any conflicts with others containers. */ -declare(ticks = 1); +declare(ticks=1); if (!isset($_SERVER['REQUEST_METHOD'])) { $_SERVER['REQUEST_METHOD'] = 'POST'; @@ -46,7 +46,7 @@ if (!isset($_SERVER['REMOTE_ADDR'])) { $_SERVER['REMOTE_ADDR'] = '0.0.0.0'; } -require_once dirname(__FILE__) . '/lib/RetailcrmCli.php'; +require_once __DIR__ . '/lib/RetailcrmCli.php'; function retailcrmCliInterruptHandler($signo) { @@ -59,9 +59,9 @@ function retailcrmCliInterruptHandler($signo) exit(1); } -if (php_sapi_name() == 'cli') { +if ('cli' == php_sapi_name()) { $cli = new RetailcrmCli(__FILE__); $cli->execute('retailcrmCliInterruptHandler'); } else { - include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'index.php'; + include_once __DIR__ . DIRECTORY_SEPARATOR . 'index.php'; } diff --git a/retailcrm/controllers/front/Consultant.php b/retailcrm/controllers/front/Consultant.php index acdd847..1d9725c 100644 --- a/retailcrm/controllers/front/Consultant.php +++ b/retailcrm/controllers/front/Consultant.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - class RetailcrmConsultantModuleFrontController extends ModuleFrontController { /** @@ -80,7 +79,8 @@ class RetailcrmConsultantModuleFrontController extends ModuleFrontController $rcctExtractor = new RetailcrmCachedSettingExtractor(); $rcct = $rcctExtractor ->setCachedAndConfigKey(RetailCRM::CONSULTANT_RCCT) - ->getData(); + ->getData() + ; if (empty($rcct)) { $script = trim(Configuration::get(RetailCRM::CONSULTANT_SCRIPT)); @@ -95,6 +95,6 @@ class RetailcrmConsultantModuleFrontController extends ModuleFrontController } } - return array('rcct' => empty($rcct) ? '' : $rcct); + return ['rcct' => empty($rcct) ? '' : $rcct]; } } diff --git a/retailcrm/controllers/front/DaemonCollector.php b/retailcrm/controllers/front/DaemonCollector.php index 52cebda..a5329ff 100644 --- a/retailcrm/controllers/front/DaemonCollector.php +++ b/retailcrm/controllers/front/DaemonCollector.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - class RetailcrmDaemonCollectorModuleFrontController extends ModuleFrontController { /** @@ -83,7 +82,7 @@ class RetailcrmDaemonCollectorModuleFrontController extends ModuleFrontControlle $siteKey = Configuration::get(RetailCRM::COLLECTOR_KEY); $collectorConfigured = $isActive && $siteKey; - $params = array('siteKey' => !$collectorConfigured ? '' : $siteKey); + $params = ['siteKey' => !$collectorConfigured ? '' : $siteKey]; if ($collectorConfigured && !empty($this->context->customer) && $this->context->customer->id) { $params['customerId'] = $this->context->customer->id; diff --git a/retailcrm/controllers/front/Jobs.php b/retailcrm/controllers/front/Jobs.php index d3143a4..dce5fd4 100644 --- a/retailcrm/controllers/front/Jobs.php +++ b/retailcrm/controllers/front/Jobs.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - class RetailcrmJobsModuleFrontController extends ModuleFrontController { /** @@ -81,6 +80,6 @@ class RetailcrmJobsModuleFrontController extends ModuleFrontController RetailcrmTools::startJobManager(); } - return array('success' => true); + return ['success' => true]; } } diff --git a/retailcrm/controllers/front/index.php b/retailcrm/controllers/front/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/controllers/front/index.php +++ b/retailcrm/controllers/front/index.php @@ -1,8 +1,9 @@ dataCrm[$key]) && !empty($this->dataCrm[$key]) ? $this->dataCrm[$key] : $default; + return isset($this->dataCrm[$key]) && !empty($this->dataCrm[$key]) ? $this->dataCrm[$key] : $default; } } diff --git a/retailcrm/lib/RetailcrmAbstractDataBuilder.php b/retailcrm/lib/RetailcrmAbstractDataBuilder.php index 23a1f49..aabe741 100644 --- a/retailcrm/lib/RetailcrmAbstractDataBuilder.php +++ b/retailcrm/lib/RetailcrmAbstractDataBuilder.php @@ -38,7 +38,7 @@ abstract class RetailcrmAbstractDataBuilder { /** - * @var mixed $data Any data type (depends on the builder) + * @var mixed Any data type (depends on the builder) */ protected $data; @@ -73,7 +73,7 @@ abstract class RetailcrmAbstractDataBuilder return RetailcrmTools::clearArray((array) $this->data); } - return array(); + return []; } /** diff --git a/retailcrm/lib/RetailcrmAddressBuilder.php b/retailcrm/lib/RetailcrmAddressBuilder.php index 0b401ba..0f22c98 100644 --- a/retailcrm/lib/RetailcrmAddressBuilder.php +++ b/retailcrm/lib/RetailcrmAddressBuilder.php @@ -52,7 +52,6 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder */ const MODE_ORDER_DELIVERY = 2; - /** * Divider for order delivery addressline1 and addressline 2 */ @@ -91,6 +90,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder public function setAddress($address) { $this->address = $address; + return $this; } @@ -102,6 +102,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder public function setIsMain($isMain) { $this->isMain = $isMain; + return $this; } @@ -113,6 +114,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder public function setMode($mode) { $this->mode = $mode; + return $this; } @@ -124,6 +126,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder public function setWithExternalId($withExternalId) { $this->withExternalId = $withExternalId; + return $this; } @@ -135,6 +138,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder public function setExternalIdSuffix($externalIdSuffix) { $this->externalIdSuffix = $externalIdSuffix; + return $this; } @@ -146,6 +150,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder public function setAddressId($addressId) { $this->address = new Address($addressId); + return $this; } @@ -158,7 +163,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder { parent::reset(); - $this->data = array(); + $this->data = []; $this->address = null; $this->mode = static::MODE_CUSTOMER; $this->isMain = false; @@ -188,17 +193,17 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder $this->buildOrderNames(); break; default: - throw new \InvalidArgumentException("Incorrect builder mode"); + throw new \InvalidArgumentException('Incorrect builder mode'); } } $this->data = RetailcrmTools::filter( 'RetailcrmFilterProcessAddress', $this->data, - array( + [ 'address' => $this->address, - 'mode' => $this->mode - )); + 'mode' => $this->mode, + ]); return $this; } @@ -226,7 +231,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder } } - return array(); + return []; } /** @@ -246,7 +251,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder } } - return array_filter(array( + return array_filter([ 'index' => $this->address->postcode, 'city' => $this->address->city, 'countryIso' => Country::getIsoById($this->address->id_country), @@ -256,8 +261,8 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder $this->address->address2, ])), 'notes' => $this->address->other, - 'region' => $state - )); + 'region' => $state, + ]); } /** @@ -266,11 +271,11 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder private function buildCustomerPhones() { if (!empty($this->address->phone_mobile)) { - $this->data['customer']['phones'][] = array('number'=> $this->address->phone_mobile); + $this->data['customer']['phones'][] = ['number' => $this->address->phone_mobile]; } if (!empty($this->address->phone)) { - $this->data['customer']['phones'][] = array('number'=> $this->address->phone); + $this->data['customer']['phones'][] = ['number' => $this->address->phone]; } } diff --git a/retailcrm/lib/RetailcrmBuilderInterface.php b/retailcrm/lib/RetailcrmBuilderInterface.php index 04bca43..a3dcf5f 100644 --- a/retailcrm/lib/RetailcrmBuilderInterface.php +++ b/retailcrm/lib/RetailcrmBuilderInterface.php @@ -67,4 +67,3 @@ interface RetailcrmBuilderInterface */ public function reset(); } - diff --git a/retailcrm/lib/RetailcrmCachedSettingExtractor.php b/retailcrm/lib/RetailcrmCachedSettingExtractor.php index b9bc19b..e52888e 100644 --- a/retailcrm/lib/RetailcrmCachedSettingExtractor.php +++ b/retailcrm/lib/RetailcrmCachedSettingExtractor.php @@ -63,6 +63,7 @@ class RetailcrmCachedSettingExtractor extends RetailcrmAbstractDataBuilder public function setCachedKey($cachedKey) { $this->cachedKey = $cachedKey; + return $this; } @@ -74,6 +75,7 @@ class RetailcrmCachedSettingExtractor extends RetailcrmAbstractDataBuilder public function setConfigKey($configKey) { $this->configKey = $configKey; + return $this; } @@ -86,6 +88,7 @@ class RetailcrmCachedSettingExtractor extends RetailcrmAbstractDataBuilder { $this->setCachedKey($key); $this->setConfigKey($key); + return $this; } diff --git a/retailcrm/lib/RetailcrmCartUploader.php b/retailcrm/lib/RetailcrmCartUploader.php index a3a6528..18cfea0 100644 --- a/retailcrm/lib/RetailcrmCartUploader.php +++ b/retailcrm/lib/RetailcrmCartUploader.php @@ -88,8 +88,8 @@ class RetailcrmCartUploader */ public static function setSyncDelay($time) { - if (is_numeric($time) && $time > 0) { - static::$syncDelay = (int)$time; + if (is_numeric($time) && 0 < $time) { + static::$syncDelay = (int) $time; } else { static::$syncDelay = 0; } @@ -101,12 +101,12 @@ class RetailcrmCartUploader public static function init() { static::$api = null; - static::$cartsIds = array(); - static::$paymentTypes = array(); + static::$cartsIds = []; + static::$paymentTypes = []; static::$syncDelay = 0; static::$allowedUpdateInterval = 86400; static::$syncStatus = ''; - static::$now = new \DateTime(); + static::$now = new \DateTimeImmutable(); static::$context = Context::getContext(); } @@ -134,7 +134,7 @@ class RetailcrmCartUploader } if (!empty($cart->date_upd)) { - $cartLastUpdateDate = \DateTime::createFromFormat('Y-m-d H:i:s', $cart->date_upd); + $cartLastUpdateDate = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $cart->date_upd); } if (!static::isAbandonedCartShouldBeUpdated( @@ -160,7 +160,7 @@ class RetailcrmCartUploader continue; } - if (static::$api->ordersCreate($order) !== false) { + if (false !== static::$api->ordersCreate($order)) { $cart->date_upd = date('Y-m-d H:i:s'); $cart->save(); } @@ -175,7 +175,7 @@ class RetailcrmCartUploader continue; } - if (static::$api->ordersEdit($order) !== false) { + if (false !== static::$api->ordersEdit($order)) { static::registerAbandonedCartSync($cart->id); } } @@ -219,15 +219,15 @@ class RetailcrmCartUploader try { $currentCartTotal = $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); - if ($currentCartTotal == 0) { + if (0 == $currentCartTotal) { $shouldBeUploaded = false; } } catch (\Exception $exception) { RetailcrmLogger::writeCaller( __METHOD__, - sprintf("Failure while trying to get cart total (cart id=%d)", $cart->id) + sprintf('Failure while trying to get cart total (cart id=%d)', $cart->id) ); - RetailcrmLogger::writeCaller(__METHOD__, "Error message and stacktrace will be printed below"); + RetailcrmLogger::writeCaller(__METHOD__, 'Error message and stacktrace will be printed below'); RetailcrmLogger::writeCaller(__METHOD__, $exception->getMessage()); RetailcrmLogger::writeNoCaller($exception->getTraceAsString()); @@ -236,15 +236,15 @@ class RetailcrmCartUploader try { // Don't upload empty cartsIds. - if (count($cart->getProducts(true)) == 0 || !$shouldBeUploaded) { + if (0 == count($cart->getProducts(true)) || !$shouldBeUploaded) { return true; } } catch (\Exception $exception) { RetailcrmLogger::writeCaller( __METHOD__, - sprintf("Failure while trying to get cart products (cart id=%d)", $cart->id) + sprintf('Failure while trying to get cart products (cart id=%d)', $cart->id) ); - RetailcrmLogger::writeCaller(__METHOD__, "Error message and stacktrace will be printed below"); + RetailcrmLogger::writeCaller(__METHOD__, 'Error message and stacktrace will be printed below'); RetailcrmLogger::writeCaller(__METHOD__, $exception->getMessage()); RetailcrmLogger::writeNoCaller($exception->getTraceAsString()); @@ -264,7 +264,7 @@ class RetailcrmCartUploader */ private static function buildCartOrder($cart, $cartExternalId) { - $order = array(); + $order = []; try { $order = RetailcrmOrderBuilder::buildCrmOrderFromCart( @@ -318,7 +318,7 @@ class RetailcrmCartUploader return null; } - return \DateTime::createFromFormat('Y-m-d H:i:s', $when); + return \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $when); } /** @@ -326,12 +326,12 @@ class RetailcrmCartUploader */ private static function loadAbandonedCartsIds() { - $sql = 'SELECT c.id_cart, c.date_upd + $sql = 'SELECT c.id_cart, c.date_upd FROM ' . _DB_PREFIX_ . 'cart AS c LEFT JOIN ' . _DB_PREFIX_ . 'customer cus ON c.id_customer = cus.id_customer - WHERE c.id_customer != 0 + WHERE c.id_customer != 0 AND cus.is_guest = 0 ' . Shop::addSqlRestriction(false, 'c') . ' AND TIME_TO_SEC(TIMEDIFF(\'' . pSQL(static::$now->format('Y-m-d H:i:s')) @@ -359,7 +359,7 @@ class RetailcrmCartUploader ob_clean(); ob_end_flush(); - if (is_null($lastUploadDate) || is_null($lastUpdatedDate)) { + if (null === $lastUploadDate || null === $lastUpdatedDate) { return true; } @@ -374,8 +374,8 @@ class RetailcrmCartUploader private static function validateState() { if (empty(static::$syncStatus) - || (count(static::$paymentTypes) < 1) - || is_null(static::$now) + || (1 > count(static::$paymentTypes)) + || null === static::$now || !static::$api ) { return false; diff --git a/retailcrm/lib/RetailcrmCatalog.php b/retailcrm/lib/RetailcrmCatalog.php index b5e2e6a..2c8a956 100644 --- a/retailcrm/lib/RetailcrmCatalog.php +++ b/retailcrm/lib/RetailcrmCatalog.php @@ -38,7 +38,6 @@ */ class RetailcrmCatalog { - public $default_lang; public $default_currency; public $default_country; @@ -49,11 +48,11 @@ class RetailcrmCatalog public function __construct() { - $this->default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); - $this->default_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT'); - $this->default_country = (int)Configuration::get('PS_COUNTRY_DEFAULT'); + $this->default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); + $this->default_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); + $this->default_country = (int) Configuration::get('PS_COUNTRY_DEFAULT'); - $this->protocol = (Configuration::get('PS_SSL_ENABLED')) ? "https://" : "http://"; + $this->protocol = (Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://'; $this->version = substr(_PS_VERSION_, 0, 3); $this->link = new Link(); $this->home_category = Configuration::get('PS_HOME_CATEGORY'); @@ -61,13 +60,13 @@ class RetailcrmCatalog public function getData() { - return array($this->getCategories(), $this->getOffers()); + return [$this->getCategories(), $this->getOffers()]; } public function getCategories() { - $categories = array(); - $categoriesIds = array(); + $categories = []; + $categoriesIds = []; $types = Category::getCategories($this->default_lang, true, false); @@ -76,19 +75,18 @@ class RetailcrmCatalog ? $category['id'] : $category['id_category']; if (!self::isCategoryActive(new Category($categoryId))) { - continue; } $picture = $this->link->getCatImageLink($category['link_rewrite'], $categoryId, 'category_default'); $categoriesIds[] = $categoryId; - $categories[] = array( + $categories[] = [ 'id' => $categoryId, 'parentId' => self::getParentCategoryId($categoryId, $category['id_parent']), 'name' => htmlspecialchars($category['name']), - 'picture' => $picture ? $this->protocol . $picture : '' - ); + 'picture' => $picture ? $this->protocol . $picture : '', + ]; } foreach ($categories as $key => $innerCategory) { @@ -136,7 +134,7 @@ class RetailcrmCatalog $start = 0; $count = self::getProductsCount($id_lang); - if ($count > 0) + if (0 < $count) { do { $products = Product::getProducts($id_lang, $start, $limit, 'name', 'asc'); @@ -160,9 +158,9 @@ class RetailcrmCatalog if (empty($categoriesLeft)) { continue; } - $productsCount++; + ++$productsCount; - if ($this->version == "1.3") { + if ('1.3' == $this->version) { $available_for_order = $product['active'] && $product['quantity']; } else { $available_for_order = $product['active'] && $product['available_for_order']; @@ -194,7 +192,7 @@ class RetailcrmCatalog } $weight = round($product['weight'], 2); - if ($weight === 0.0) { + if (0.0 === $weight) { $weight = null; } @@ -202,8 +200,8 @@ class RetailcrmCatalog $height = round($product['height'], 3); $depth = round($product['depth'], 3); - if ($width !== 0.0 && $height !== 0.0) { - $dimensions = implode('/', array($depth, $width, $height)); + if (0.0 !== $width && 0.0 !== $height) { + $dimensions = implode('/', [$depth, $width, $height]); } else { $dimensions = null; } @@ -211,7 +209,7 @@ class RetailcrmCatalog $offers = Product::getProductAttributesIds($product['id_product']); if (!empty($offers)) { - $offersCount+= count($offers); + $offersCount += count($offers); $productForCombination = new Product($product['id_product']); foreach ($offers as $offer) { @@ -238,10 +236,10 @@ class RetailcrmCatalog $pictures[] = $picture; } - if ($this->version == "1.3") { + if ('1.3' == $this->version) { $quantity = $product['quantity']; } else { - $quantity = (int)StockAvailable::getQuantityAvailableByProduct($product['id_product'], $offer['id_product_attribute']); + $quantity = (int) StockAvailable::getQuantityAvailableByProduct($product['id_product'], $offer['id_product_attribute']); } $offerCombination = new Combination($offer['id_product_attribute']); @@ -251,9 +249,9 @@ class RetailcrmCatalog : round($offerCombination->price, 2); $offerPrice = round($offerCombinationPrice, 2) + $price; - $offerPrice = $offerPrice > 0 ? $offerPrice : $price; + $offerPrice = 0 < $offerPrice ? $offerPrice : $price; - if ($offerCombination->wholesale_price > 0) { + if (0 < $offerCombination->wholesale_price) { $offerPurchasePrice = round($offerCombination->wholesale_price, 2); } else { $offerPurchasePrice = $purchasePrice; @@ -274,7 +272,7 @@ class RetailcrmCatalog 'categoryId' => $categoriesLeft, 'picture' => $pictures, 'url' => $url, - 'quantity' => $quantity > 0 ? $quantity : 0, + 'quantity' => 0 < $quantity ? $quantity : 0, 'purchasePrice' => $offerPurchasePrice, 'price' => round($offerPrice, 2), 'vendor' => $vendor, @@ -300,20 +298,20 @@ class RetailcrmCatalog $item, [ 'product' => $product, - 'offer' => $offer + 'offer' => $offer, ] ); } } else { - $offersCount++; + ++$offersCount; $covers = Image::getImages($id_lang, $product['id_product'], null); $pictures = $this->getPictures($covers, $product); - if ($this->version == "1.3") { + if ('1.3' == $this->version) { $quantity = $product['quantity']; } else { - $quantity = (int)StockAvailable::getQuantityAvailableByProduct($product['id_product']); + $quantity = (int) StockAvailable::getQuantityAvailableByProduct($product['id_product']); } $item = [ @@ -325,7 +323,7 @@ class RetailcrmCatalog 'categoryId' => $categoriesLeft, 'picture' => $pictures, 'url' => $url, - 'quantity' => $quantity > 0 ? $quantity : 0, + 'quantity' => 0 < $quantity ? $quantity : 0, 'purchasePrice' => round($purchasePrice, 2), 'price' => $price, 'vendor' => $vendor, @@ -339,14 +337,15 @@ class RetailcrmCatalog 'RetailcrmFilterProcessOffer', $item, [ - 'product' => $product + 'product' => $product, ] ); } } $start += $limit; - } while ($start < $count && count($products) > 0); + } while ($start < $count && 0 < count($products)); + } RetailcrmCatalogHelper::setIcmlFileInfo($productsCount, $offersCount); } @@ -357,27 +356,26 @@ class RetailcrmCatalog foreach ($covers as $cover) { $picture = $this->protocol . $this->link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $cover['id_image'], 'large_default'); - if ($offers === false && $cover['cover']) { + if (false === $offers && $cover['cover']) { array_unshift($pictures, $picture); } else { $pictures[] = $picture; } - } + return $pictures; } private static function getProductsCount( $id_lang, Context $context = null - ) - { + ) { if (!$context) { $context = Context::getContext(); } $front = true; - if (!in_array($context->controller->controller_type, array('front', 'modulefront'))) { + if (!in_array($context->controller->controller_type, ['front', 'modulefront'])) { $front = false; } @@ -385,10 +383,10 @@ class RetailcrmCatalog FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON (p.`id_product` = pl.`id_product` ' . Shop::addSqlRestrictionOnLang('pl') . ') - WHERE pl.`id_lang` = ' . (int)$id_lang . + WHERE pl.`id_lang` = ' . (int) $id_lang . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : ''); - return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); + return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } /** @@ -452,5 +450,4 @@ class RetailcrmCatalog return $parentId; } - } diff --git a/retailcrm/lib/RetailcrmCatalogHelper.php b/retailcrm/lib/RetailcrmCatalogHelper.php index 050ef10..a3625c8 100644 --- a/retailcrm/lib/RetailcrmCatalogHelper.php +++ b/retailcrm/lib/RetailcrmCatalogHelper.php @@ -44,14 +44,14 @@ class RetailcrmCatalogHelper { $date = null; $filePath = self::getIcmlFilePath(); - if (!file_exists($filePath) || ($fileHandler = fopen($filePath, 'rb')) === false) { + if (!file_exists($filePath) || ($fileHandler = fopen($filePath, 'r')) === false) { return false; } while ($line = fgets($fileHandler)) { - if (strpos($line, 'yml_catalog date=') !== false) { + if (false !== strpos($line, 'yml_catalog date=')) { preg_match_all('/date="([\d\- :]+)"/', $line, $matches); - if (count($matches) == 2) { + if (2 == count($matches)) { $date = $matches[1][0]; } break; @@ -60,7 +60,7 @@ class RetailcrmCatalogHelper fclose($fileHandler); - return DateTime::createFromFormat('Y-m-d H:i:s', $date); + return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $date); } public static function getIcmlFileLink() @@ -89,37 +89,37 @@ class RetailcrmCatalogHelper public static function getIcmlFileInfo() { - $icmlInfo = json_decode((string)Configuration::get(self::ICML_INFO_NAME), true); + $icmlInfo = json_decode((string) Configuration::get(self::ICML_INFO_NAME), true); - if ($icmlInfo === null || json_last_error() !== JSON_ERROR_NONE) { - $icmlInfo = array(); + if (null === $icmlInfo || JSON_ERROR_NONE !== json_last_error()) { + $icmlInfo = []; } $lastGenerated = self::getIcmlFileDate(); - if ($lastGenerated === false) { + if (false === $lastGenerated) { return $icmlInfo; } $icmlInfo['lastGenerated'] = $lastGenerated; - $now = new DateTime(); + $now = new DateTimeImmutable(); /** @var DateInterval $diff */ $diff = $lastGenerated->diff($now); - $icmlInfo['lastGeneratedDiff'] = array( + $icmlInfo['lastGeneratedDiff'] = [ 'days' => $diff->days, 'hours' => $diff->h, - 'minutes' => $diff->i - ); + 'minutes' => $diff->i, + ]; $icmlInfo['isOutdated'] = ( - $icmlInfo['lastGeneratedDiff']['days'] > 0 - || $icmlInfo['lastGeneratedDiff']['hours'] > 4 + 0 < $icmlInfo['lastGeneratedDiff']['days'] + || 4 < $icmlInfo['lastGeneratedDiff']['hours'] ); $api = RetailcrmTools::getApiClient(); - if ($api !== null) { + if (null !== $api) { $reference = new RetailcrmReferences($api); $site = $reference->getSite(); @@ -134,7 +134,7 @@ class RetailcrmCatalogHelper public static function getIcmlFileInfoMultistore() { - return RetailcrmContextSwitcher::runInContext(array(self::class, 'getIcmlFileInfo')); + return RetailcrmContextSwitcher::runInContext([self::class, 'getIcmlFileInfo']); } /** @@ -143,10 +143,10 @@ class RetailcrmCatalogHelper */ public static function setIcmlFileInfo($productsCount, $offersCount) { - $icmlInfo = array( + $icmlInfo = [ 'productsCount' => $productsCount, - 'offersCount' => $offersCount - ); - Configuration::updateValue(self::ICML_INFO_NAME, (string)json_encode($icmlInfo)); + 'offersCount' => $offersCount, + ]; + Configuration::updateValue(self::ICML_INFO_NAME, (string) json_encode($icmlInfo)); } -} \ No newline at end of file +} diff --git a/retailcrm/lib/RetailcrmCli.php b/retailcrm/lib/RetailcrmCli.php index 0a6385b..4263e00 100644 --- a/retailcrm/lib/RetailcrmCli.php +++ b/retailcrm/lib/RetailcrmCli.php @@ -35,14 +35,13 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(@date_default_timezone_get()); } -require_once(dirname(__FILE__) . '/../../../config/config.inc.php'); -require_once(dirname(__FILE__) . '/../../../init.php'); -require_once(dirname(__FILE__) . '/../bootstrap.php'); +require_once __DIR__ . '/../../../config/config.inc.php'; +require_once __DIR__ . '/../../../init.php'; +require_once __DIR__ . '/../bootstrap.php'; if (!defined('_PS_VERSION_')) { exit; @@ -53,7 +52,8 @@ if (!defined('_PS_VERSION_')) { * * @author DIGITAL RETAIL TECHNOLOGIES SL * @license GPL - * @link https://retailcrm.ru + * + * @see https://retailcrm.ru */ class RetailcrmCli { @@ -98,16 +98,16 @@ class RetailcrmCli RetailcrmLogger::output('WARNING: cannot handle signals properly, force stop can cause problems!'); } - $shortopts = "j:s:"; - $longopts = array( - "job:", - "shop:", - "set-web-jobs:", - "query-web-jobs", - "run-jobs", - "reset-job-manager", - "reset-all" - ); + $shortopts = 'j:s:'; + $longopts = [ + 'job:', + 'shop:', + 'set-web-jobs:', + 'query-web-jobs', + 'run-jobs', + 'reset-job-manager', + 'reset-all', + ]; $options = getopt($shortopts, $longopts); $jobName = isset($options['j']) ? $options['j'] : (isset($options['job']) ? $options['job'] : null); @@ -148,7 +148,7 @@ class RetailcrmCli */ private function setCleanupOnShutdown() { - RetailcrmJobManager::setCustomShutdownHandler(array($this, 'cleanupOnShutdown')); + RetailcrmJobManager::setCustomShutdownHandler([$this, 'cleanupOnShutdown']); } /** @@ -184,7 +184,7 @@ class RetailcrmCli * Prints error details * * @param \Exception $exception - * @param string $header + * @param string $header */ private function printStack($exception, $header = 'Error while executing a job: ') { @@ -216,19 +216,19 @@ class RetailcrmCli RetailcrmLogger::output(sprintf('> php %s --query-web-jobs - Check web jobs status', $this->cliPath)); RetailcrmLogger::output(); RetailcrmLogger::output( - "NOTICE: If you have MultiShop feature enabled, you can additionally " . - "specify shop id when manually running job: " + 'NOTICE: If you have MultiShop feature enabled, you can additionally ' . + 'specify shop id when manually running job: ' ); - RetailcrmLogger::output("At default jobs are running for all active shops alternately."); + RetailcrmLogger::output('At default jobs are running for all active shops alternately.'); RetailcrmLogger::output(); RetailcrmLogger::output(sprintf('> php %s -j -s - Runs provided job for specified shop', $this->cliPath)); RetailcrmLogger::output(sprintf('> php %s --job --shop - Runs provided job for specified shop', $this->cliPath)); RetailcrmLogger::output(); RetailcrmLogger::output( - "WARNING: Commands below are dangerous and should be used only when " . + 'WARNING: Commands below are dangerous and should be used only when ' . "job manager or cli doesn't work properly." ); - RetailcrmLogger::output("Use them at your own risk."); + RetailcrmLogger::output('Use them at your own risk.'); RetailcrmLogger::output(); RetailcrmLogger::output(sprintf( '> php %s --reset-job-manager - Will reset job manager internal timers & current job name', @@ -245,12 +245,13 @@ class RetailcrmCli * Sets new web jobs state * * @param bool $state - * @param $shopId + * @param $shopId */ private function setWebJobs($state, $shopId = null) { - if ($shopId === null) { + if (null === $shopId) { RetailcrmLogger::output('You must specify shop id'); + return; } @@ -269,8 +270,9 @@ class RetailcrmCli */ private function queryWebJobs($shopId = null) { - if ($shopId === null) { + if (null === $shopId) { RetailcrmLogger::output('You must specify shop id'); + return; } @@ -352,7 +354,7 @@ class RetailcrmCli */ public static function clearCurrentJob($job) { - if (is_null($job) || self::getCurrentJob() == $job) { + if (null === $job || self::getCurrentJob() == $job) { return Configuration::deleteByName(self::CURRENT_TASK_CLI); } @@ -384,7 +386,7 @@ class RetailcrmCli */ private function getAllowedJobs() { - return array( + return [ 'RetailcrmAbandonedCartsEvent', 'RetailcrmIcmlEvent', 'RetailcrmIcmlUpdateUrlEvent', @@ -392,7 +394,7 @@ class RetailcrmCli 'RetailcrmInventoriesEvent', 'RetailcrmExportEvent', 'RetailcrmUpdateSinceIdEvent', - 'RetailcrmClearLogsEvent' - ); + 'RetailcrmClearLogsEvent', + ]; } } diff --git a/retailcrm/lib/RetailcrmConsultantRcctExtractor.php b/retailcrm/lib/RetailcrmConsultantRcctExtractor.php index 1ae7500..b2e2161 100644 --- a/retailcrm/lib/RetailcrmConsultantRcctExtractor.php +++ b/retailcrm/lib/RetailcrmConsultantRcctExtractor.php @@ -52,6 +52,7 @@ class RetailcrmConsultantRcctExtractor extends RetailcrmAbstractDataBuilder { $this->consultantScript = $consultantScript; $this->data = ''; + return $this; } diff --git a/retailcrm/lib/RetailcrmContextSwitcher.php b/retailcrm/lib/RetailcrmContextSwitcher.php index 4607c54..a5e3a4e 100644 --- a/retailcrm/lib/RetailcrmContextSwitcher.php +++ b/retailcrm/lib/RetailcrmContextSwitcher.php @@ -52,16 +52,17 @@ class RetailcrmContextSwitcher * * @param callable $callback * @param array $arguments Arguments that will be passed to callback function + * * @return array */ - public static function runInContext($callback, $arguments = array()) + public static function runInContext($callback, $arguments = []) { - $result = array(); + $result = []; self::storeContext(); foreach (self::getShops() as $shop) { - self::setShopContext(intval($shop['id_shop'])); - $result[intval($shop['id_shop'])] = call_user_func_array($callback, $arguments); + self::setShopContext((int) ($shop['id_shop'])); + $result[(int) ($shop['id_shop'])] = call_user_func_array($callback, $arguments); } self::restoreContext(); @@ -98,7 +99,6 @@ class RetailcrmContextSwitcher } /** - * * Change shop in the context * * @param $id_shop @@ -120,10 +120,10 @@ class RetailcrmContextSwitcher { $idShop = Shop::getContextShopID(); - if (Shop::isFeatureActive() && $idShop === null) { + if (Shop::isFeatureActive() && null === $idShop) { return Shop::getShops(true, Shop::getContextShopGroupID(true)); } else { - return array(Shop::getShop($idShop)); + return [Shop::getShop($idShop)]; } } -} \ No newline at end of file +} diff --git a/retailcrm/lib/RetailcrmCorporateCustomerBuilder.php b/retailcrm/lib/RetailcrmCorporateCustomerBuilder.php index 729fb08..62f92af 100644 --- a/retailcrm/lib/RetailcrmCorporateCustomerBuilder.php +++ b/retailcrm/lib/RetailcrmCorporateCustomerBuilder.php @@ -38,32 +38,32 @@ class RetailcrmCorporateCustomerBuilder extends RetailcrmAbstractBuilder implements RetailcrmBuilderInterface { /** - * @var Customer|CustomerCore $corporateCustomer Corporate customer + * @var Customer|CustomerCore Corporate customer */ private $corporateCustomer; /** - * @var RetailcrmBuilderInterface $customerBuilder Customer builder + * @var RetailcrmBuilderInterface Customer builder */ private $customerBuilder; /** - * @var array $dataCrm customerHistory + * @var array customerHistory */ protected $dataCrm; /** - * @var string $companyName + * @var string */ private $companyName; /** - * @var string $companyInn + * @var string */ protected $companyInn; /** - * @var Address|AddressCore $corporateAddress + * @var Address|AddressCore */ private $corporateAddress; @@ -77,51 +77,61 @@ class RetailcrmCorporateCustomerBuilder extends RetailcrmAbstractBuilder impleme /** * @param RetailcrmBuilderInterface $customerBuilder + * * @return RetailcrmCorporateCustomerBuilder */ public function setCustomerBuilder($customerBuilder) { $this->customerBuilder = $customerBuilder; + return $this; } /** * @param Customer $corporateCustomer Corporate customer + * * @return RetailcrmCorporateCustomerBuilder */ public function setCustomer($corporateCustomer) { $this->corporateCustomer = $corporateCustomer; + return $this; } /** * @param string $companyName + * * @return RetailcrmCorporateCustomerBuilder */ public function setCompanyName($companyName) { $this->companyName = $companyName; + return $this; } /** * @param string $companyInn + * * @return RetailcrmCorporateCustomerBuilder */ public function setCompanyInn($companyInn) { $this->companyInn = $companyInn; + return $this; } /** - * @param Address|AddressCore $corporateAddress + * @param Address|AddressCore $corporateAddress + * * @return RetailcrmCorporateCustomerBuilder */ public function setCorporateAddress($corporateAddress) { $this->corporateAddress = $corporateAddress; + return $this; } @@ -129,6 +139,7 @@ class RetailcrmCorporateCustomerBuilder extends RetailcrmAbstractBuilder impleme * Set data in address, name and inn company corporate customer * * @param array $dataCrm + * * @return RetailcrmCorporateCustomerBuilder */ public function extractCompanyDataFromOrder($dataCrm) @@ -145,6 +156,7 @@ class RetailcrmCorporateCustomerBuilder extends RetailcrmAbstractBuilder impleme public function setDataCrm($dataCrm) { $this->dataCrm = $dataCrm; + return $this; } @@ -188,15 +200,14 @@ class RetailcrmCorporateCustomerBuilder extends RetailcrmAbstractBuilder impleme $this->buildCustomer(); if (!empty($this->corporateAddress)) { - - if (empty($this->corporateAddress->alias) || $this->corporateAddress->alias == 'default') { + if (empty($this->corporateAddress->alias) || 'default' == $this->corporateAddress->alias) { $this->corporateAddress->alias = '--'; } $this->corporateAddress->vat_number = !empty($this->companyInn) ? $this->companyInn : ''; $this->corporateAddress->company = !empty($this->companyName) ? $this->companyName : ''; - if (!empty($this->companyName) && (empty($this->corporateCustomer->firstname) || $this->corporateCustomer->firstname == '--')) { + if (!empty($this->companyName) && (empty($this->corporateCustomer->firstname) || '--' == $this->corporateCustomer->firstname)) { $this->corporateCustomer->firstname = $this->companyName; } } @@ -204,18 +215,17 @@ class RetailcrmCorporateCustomerBuilder extends RetailcrmAbstractBuilder impleme $this->corporateCustomer = RetailcrmTools::filter( 'RetailcrmFilterSaveCorporateCustomer', $this->corporateCustomer, - array( + [ 'dataCrm' => $this->dataCrm, - )); + ]); $this->corporateAddress = RetailcrmTools::filter( 'RetailcrmFilterSaveCorporateCustomerAddress', $this->corporateAddress, - array( + [ 'dataCrm' => $this->dataCrm, - )); + ]); return $this; } } - diff --git a/retailcrm/lib/RetailcrmCustomerAddressBuilder.php b/retailcrm/lib/RetailcrmCustomerAddressBuilder.php index 2455013..eace106 100644 --- a/retailcrm/lib/RetailcrmCustomerAddressBuilder.php +++ b/retailcrm/lib/RetailcrmCustomerAddressBuilder.php @@ -44,32 +44,32 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement private $customerAddress; /** - * @var array $dataCrm + * @var array */ private $dataCrm; /** - * @var int $idCustomer + * @var int */ private $idCustomer; /** - * @var string $firstName + * @var string */ private $firstName; /** - * @var string $lastName + * @var string */ private $lastName; /** - * @var string $phone + * @var string */ private $phone; /** - * @var string $alias + * @var string */ private $alias; @@ -83,6 +83,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement /** * @param Address|AddressCore $customerAddress + * * @return RetailcrmCustomerAddressBuilder */ public function setCustomerAddress($customerAddress) @@ -101,6 +102,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement /** * @param int $idCustomer + * * @return RetailcrmCustomerAddressBuilder */ public function setIdCustomer($idCustomer) @@ -112,6 +114,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement /** * @param string $alias + * * @return RetailcrmCustomerAddressBuilder */ public function setAlias($alias) @@ -123,6 +126,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement /** * @param string $firstName + * * @return RetailcrmCustomerAddressBuilder */ public function setFirstName($firstName) @@ -134,6 +138,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement /** * @param string $lastName + * * @return RetailcrmCustomerAddressBuilder */ public function setLastName($lastName) @@ -145,6 +150,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement /** * @param string $phone + * * @return RetailcrmCustomerAddressBuilder */ public function setPhone($phone) @@ -160,7 +166,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement return $this->customerAddress; } - return array(); + return []; } public function reset() @@ -211,9 +217,9 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement $this->customerAddress = RetailcrmTools::filter( 'RetailcrmFilterSaveCustomerAddress', $this->customerAddress, - array( - 'dataCrm' => $this->dataCrm - ) + [ + 'dataCrm' => $this->dataCrm, + ] ); return $this; @@ -225,7 +231,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement throw new InvalidArgumentException("Property $field not exist in the object"); } - if ($value !== null) { + if (null !== $value) { $this->customerAddress->$field = $value; } else { $this->customerAddress->$field = $default; @@ -243,7 +249,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement $addressLine = explode(RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER, $text, 2); $this->setAddressField('address1', $addressLine[0], '--'); - if (count($addressLine) == 1) { + if (1 == count($addressLine)) { $this->setAddressField('address2', ''); } else { $this->setAddressField('address2', $addressLine[1], ''); diff --git a/retailcrm/lib/RetailcrmCustomerBuilder.php b/retailcrm/lib/RetailcrmCustomerBuilder.php index db8d8f0..83ff5b1 100644 --- a/retailcrm/lib/RetailcrmCustomerBuilder.php +++ b/retailcrm/lib/RetailcrmCustomerBuilder.php @@ -37,16 +37,16 @@ */ class RetailcrmCustomerBuilder extends RetailcrmAbstractBuilder implements RetailcrmBuilderInterface { - /** @var Customer|CustomerCore $customer Customer */ + /** @var Customer|CustomerCore Customer */ private $customer; - /** @var Address|AddressCore|null $customerAddress Address */ + /** @var Address|AddressCore|null Address */ private $customerAddress; - /** @var array $dataCrm customerHistory */ + /** @var array customerHistory */ protected $dataCrm; - /** @var RetailcrmBuilderInterface $addressBuilder Address builder */ + /** @var RetailcrmBuilderInterface Address builder */ private $addressBuilder; public function __construct() @@ -55,28 +55,33 @@ class RetailcrmCustomerBuilder extends RetailcrmAbstractBuilder implements Retai } /** - * @param Customer|CustomerCore $customer + * @param Customer|CustomerCore $customer + * * @return RetailcrmCustomerBuilder */ public function setCustomer($customer) { $this->customer = $customer; + return $this; } /** * @param RetailcrmBuilderInterface $addressBuilder + * * @return RetailcrmCustomerBuilder */ public function setAddressBuilder($addressBuilder) { $this->addressBuilder = $addressBuilder; + return $this; } public function setDataCrm($dataCrm) { $this->dataCrm = $dataCrm; + return $this; } @@ -111,7 +116,8 @@ class RetailcrmCustomerBuilder extends RetailcrmAbstractBuilder implements Retai ->setLastName($this->arrayValue('lastName')) ->setPhone(isset($this->dataCrm['phones'][0]['number']) && !empty($this->dataCrm['phones'][0]['number']) ? $this->dataCrm['phones'][0]['number'] : '') - ->build(); + ->build() + ; $this->customerAddress = $this->addressBuilder->getData(); } else { @@ -128,7 +134,7 @@ class RetailcrmCustomerBuilder extends RetailcrmAbstractBuilder implements Retai $this->customer->firstname = $this->arrayValue('firstName'); $this->customer->lastname = $this->arrayValue('lastName'); - if (isset($this->dataCrm['subscribed']) && $this->dataCrm['subscribed'] == false) { + if (isset($this->dataCrm['subscribed']) && false == $this->dataCrm['subscribed']) { $this->customer->newsletter = false; } @@ -139,7 +145,7 @@ class RetailcrmCustomerBuilder extends RetailcrmAbstractBuilder implements Retai $this->customer->birthday = $this->arrayValue('birthday', ''); if (isset($this->dataCrm['sex'])) { - $this->customer->id_gender = $this->dataCrm['sex'] == 'male' ? 1 : 2; + $this->customer->id_gender = 'male' == $this->dataCrm['sex'] ? 1 : 2; } $this->buildAddress(); @@ -150,18 +156,17 @@ class RetailcrmCustomerBuilder extends RetailcrmAbstractBuilder implements Retai $this->customer->email = RetailcrmTools::createPlaceholderEmail($this->arrayValue('firstName', microtime())); } - if (empty($this->customer->passwd )) { + if (empty($this->customer->passwd)) { $this->customer->passwd = Tools::substr(str_shuffle(Tools::strtolower(sha1(rand() . time()))), 0, 5); } $this->customer = RetailcrmTools::filter( 'RetailcrmFilterSaveCustomer', $this->customer, - array( + [ 'dataCrm' => $this->dataCrm, - )); + ]); return $this; } } - diff --git a/retailcrm/lib/RetailcrmCustomerBuilderResult.php b/retailcrm/lib/RetailcrmCustomerBuilderResult.php index c7972d2..c14d82d 100644 --- a/retailcrm/lib/RetailcrmCustomerBuilderResult.php +++ b/retailcrm/lib/RetailcrmCustomerBuilderResult.php @@ -37,10 +37,10 @@ */ class RetailcrmCustomerBuilderResult { - /** @var Customer|CustomerCore $customer */ + /** @var Customer|CustomerCore */ private $customer; - /**@var Address|AddressCore|null $customerAddress */ + /** @var Address|AddressCore|null */ private $customerAddress; /** @@ -71,4 +71,3 @@ class RetailcrmCustomerBuilderResult return $this->customerAddress; } } - diff --git a/retailcrm/lib/RetailcrmCustomerSwitcher.php b/retailcrm/lib/RetailcrmCustomerSwitcher.php index 3764b90..3d312b5 100644 --- a/retailcrm/lib/RetailcrmCustomerSwitcher.php +++ b/retailcrm/lib/RetailcrmCustomerSwitcher.php @@ -38,16 +38,16 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface { /** - * @var \RetailcrmCustomerSwitcherState $data + * @var \RetailcrmCustomerSwitcherState */ private $data; /** - * @var \RetailcrmCustomerSwitcherResult|null $result + * @var \RetailcrmCustomerSwitcherResult|null */ private $result; - /** @var bool $isContact */ + /** @var bool */ private $isContact; /** @@ -75,10 +75,10 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface if (!empty($newCustomer)) { RetailcrmLogger::writeDebugArray( __METHOD__, - array( + [ 'Changing to individual customer for order', - $this->data->getOrder()->id - ) + $this->data->getOrder()->id, + ] ); $this->isContact = false; $this->processChangeToRegular($this->data->getOrder(), $newCustomer); @@ -90,10 +90,10 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface if (!empty($newContact)) { RetailcrmLogger::writeDebugArray( __METHOD__, - array( + [ 'Changing to contact person customer for order', - $this->data->getOrder()->id - ) + $this->data->getOrder()->id, + ] ); $this->isContact = true; $this->processChangeToRegular($this->data->getOrder(), $newContact); @@ -124,7 +124,7 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface * Change order customer to regular one * * @param \Order $order - * @param array $newCustomer + * @param array $newCustomer */ protected function processChangeToRegular($order, $newCustomer) { @@ -141,12 +141,12 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface RetailcrmLogger::writeDebugArray( __METHOD__, - array( + [ 'Switching in order', $order->id, 'to', - $newCustomer - ) + $newCustomer, + ] ); if (isset($newCustomer['externalId'])) { @@ -175,10 +175,10 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface $customer = $result->getCustomer(); $address = $this->getCustomerAddress($customer, $result->getCustomerAddress()); - RetailcrmLogger::writeDebugArray(__METHOD__, array('Result:', array( + RetailcrmLogger::writeDebugArray(__METHOD__, ['Result:', [ 'customer' => RetailcrmTools::dumpEntity($customer), - 'address' => RetailcrmTools::dumpEntity($address) - ))); + 'address' => RetailcrmTools::dumpEntity($address), + ]]); } $this->result = new RetailcrmCustomerSwitcherResult($customer, $address, $order); @@ -223,7 +223,8 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface ->setPhone($billingPhone) ->setAlias('--') ->build() - ->getData(); + ->getData() + ; $address->company = $this->data->getNewCompanyName(); RetailcrmTools::assignAddressIdsByFields($customer, $address); } @@ -277,6 +278,7 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface { $this->data = new RetailcrmCustomerSwitcherState(); $this->result = null; + return $this; } @@ -310,6 +312,7 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface } $this->data = $data; + return $this; } @@ -335,20 +338,20 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface private function debugLogState() { if (RetailcrmTools::isDebug()) { - RetailcrmLogger::writeDebugArray(__METHOD__, array('state', array( + RetailcrmLogger::writeDebugArray(__METHOD__, ['state', [ 'newCustomer' => $this->data->getNewCustomer(), 'newContact' => $this->data->getNewContact(), 'newCompanyName' => $this->data->getNewCompanyName(), 'companyAddress' => $this->data->getCompanyAddress(), 'order' => RetailcrmTools::dumpEntity($this->data->getOrder()), - ))); + ]]); } } /** * Returns placeholder address if customer hasn't one; returns address without any changes otherwise. * - * @param \Customer|\CustomerCore $customer + * @param \Customer|\CustomerCore $customer * @param Address|\AddressCore|null $address * * @return \Address|\AddressCore|array|mixed @@ -370,7 +373,7 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface * Process address fields for existing customer. * * @param Customer|\CustomerCore $customer - * @param Address|\AddressCore $address + * @param Address|\AddressCore $address */ private function processCustomerAddress($customer, $address) { @@ -378,7 +381,7 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface $newCompany = $this->data->getNewCompanyName(); RetailcrmLogger::writeDebug(__METHOD__, 'Processing address for a contact person'); - if ($address->alias == '' || $address->alias == 'default') { + if ('' == $address->alias || 'default' == $address->alias) { $address->alias = '--'; } @@ -411,20 +414,22 @@ class RetailcrmCustomerSwitcher implements RetailcrmBuilderInterface * Builds placeholder address for customer if he doesn't have address. * * @param \Customer $customer - * @param string $alias + * @param string $alias * * @return \Address|\AddressCore|array|mixed */ private function createPlaceholderAddress($customer, $alias = 'default') { $addressBuilder = new RetailcrmCustomerAddressBuilder(); + return $addressBuilder ->setIdCustomer($customer->id) ->setFirstName($customer->firstname) ->setLastName($customer->lastname) ->setAlias($alias) ->build() - ->getData(); + ->getData() + ; } /** diff --git a/retailcrm/lib/RetailcrmExport.php b/retailcrm/lib/RetailcrmExport.php index 12dc626..b2abef5 100644 --- a/retailcrm/lib/RetailcrmExport.php +++ b/retailcrm/lib/RetailcrmExport.php @@ -49,12 +49,12 @@ class RetailcrmExport static $api; /** - * @var integer + * @var int */ static $ordersOffset; /** - * @var integer + * @var int */ static $customersOffset; @@ -75,12 +75,12 @@ class RetailcrmExport */ public static function getOrdersCount() { - $sql = 'SELECT count(o.id_order) - FROM `' . _DB_PREFIX_ . 'orders` o + $sql = 'SELECT count(o.id_order) + FROM `' . _DB_PREFIX_ . 'orders` o WHERE 1 ' . Shop::addSqlRestriction(false, 'o'); - return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); + return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } /** @@ -90,36 +90,39 @@ class RetailcrmExport * @param int|null $count Sets the count of orders to get from database * * @return Generator + * * @throws PrestaShopDatabaseException */ public static function getOrdersIds($start = 0, $count = null) { - if (is_null($count)) { + if (null === $count) { $to = static::getOrdersCount(); $count = $to - $start; } else { $to = $start + $count; } - if ($count > 0) { + if (0 < $count) { $predefinedSql = 'SELECT o.`id_order` - FROM `' . _DB_PREFIX_ . 'orders` o + FROM `' . _DB_PREFIX_ . 'orders` o WHERE 1 ' . Shop::addSqlRestriction(false, 'o') . ' ORDER BY o.`id_order` ASC'; while ($start < $to) { $offset = ($start + static::$ordersOffset > $to) ? $to - $start : static::$ordersOffset; - if ($offset <= 0) + if (0 >= $offset) { break; + } $sql = $predefinedSql . ' - LIMIT ' . (int)$start . ', ' . (int)$offset; + LIMIT ' . (int) $start . ', ' . (int) $offset; $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); - if (empty($orders)) + if (empty($orders)) { break; + } foreach ($orders as $order) { yield $order; @@ -140,7 +143,7 @@ class RetailcrmExport return; } - $orders = array(); + $orders = []; $orderRecords = static::getOrdersIds($from, $count); $orderBuilder = new RetailcrmOrderBuilder(); $orderBuilder->defaultLangFromConfiguration()->setApi(static::$api); @@ -180,9 +183,9 @@ class RetailcrmExport time_nanosleep(0, 250000000); - if (count($orders) == 50) { + if (50 == count($orders)) { static::$api->ordersUpload($orders); - $orders = array(); + $orders = []; } } @@ -193,6 +196,7 @@ class RetailcrmExport /** * Get total count of customers for context shop + * * @param bool $withOrders If set to true, then return total count of customers. * If set to false, then return count of customers without orders * @@ -200,7 +204,7 @@ class RetailcrmExport */ public static function getCustomersCount($withOrders = true) { - $sql = 'SELECT count(c.id_customer) + $sql = 'SELECT count(c.id_customer) FROM `' . _DB_PREFIX_ . 'customer` c WHERE 1 ' . Shop::addSqlRestriction(false, 'c'); @@ -208,15 +212,15 @@ class RetailcrmExport if (!$withOrders) { $sql .= ' AND c.id_customer not in ( - select o.id_customer - from `' . _DB_PREFIX_ . 'orders` o + select o.id_customer + from `' . _DB_PREFIX_ . 'orders` o WHERE 1 ' . Shop::addSqlRestriction(false, 'o') . ' group by o.id_customer )'; } - return (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); + return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); } /** @@ -229,18 +233,19 @@ class RetailcrmExport * @param bool $returnAddressId If set to true, then also return address id in `id_address` * * @return Generator + * * @throws PrestaShopDatabaseException */ public static function getCustomersIds($start = 0, $count = null, $withOrders = true, $returnAddressId = true) { - if (is_null($count)) { + if (null === $count) { $to = static::getCustomersCount($withOrders); $count = $to - $start; } else { $to = $start + $count; } - if ($count > 0) { + if (0 < $count) { $predefinedSql = 'SELECT c.`id_customer` ' . ($returnAddressId ? ', a.`id_address`' : '') . ' FROM `' . _DB_PREFIX_ . 'customer` c @@ -274,27 +279,28 @@ class RetailcrmExport ' . Shop::addSqlRestriction(false, 'c') . ($withOrders ? '' : ' AND c.`id_customer` not in ( - select o.`id_customer` - from `' . _DB_PREFIX_ . 'orders` o + select o.`id_customer` + from `' . _DB_PREFIX_ . 'orders` o WHERE 1 ' . Shop::addSqlRestriction(false, 'o') . ' group by o.`id_customer` )') . ' ORDER BY c.`id_customer` ASC'; - while ($start < $to) { $offset = ($start + static::$customersOffset > $to) ? $to - $start : static::$customersOffset; - if ($offset <= 0) + if (0 >= $offset) { break; + } $sql = $predefinedSql . ' - LIMIT ' . (int)$start . ', ' . (int)$offset; + LIMIT ' . (int) $start . ', ' . (int) $offset; $customers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); - if (empty($customers)) + if (empty($customers)) { break; + } foreach ($customers as $customer) { yield $customer; @@ -315,7 +321,7 @@ class RetailcrmExport return; } - $customers = array(); + $customers = []; $customersRecords = RetailcrmExport::getCustomersIds($from, $count, false); foreach ($customersRecords as $record) { @@ -332,9 +338,10 @@ class RetailcrmExport $address = $addressBuilder ->setAddress($cmsAddress) ->build() - ->getDataArray(); + ->getDataArray() + ; } else { - $address = array(); + $address = []; } try { @@ -345,9 +352,9 @@ class RetailcrmExport RetailcrmLogger::output($exception->getMessage()); } - if (count($customers) == 50) { + if (50 == count($customers)) { static::$api->customersUpload($customers); - $customers = array(); + $customers = []; time_nanosleep(0, 250000000); } @@ -360,9 +367,11 @@ class RetailcrmExport } /** - * @param int $id + * @param int $id * @param false $receiveOrderNumber + * * @return bool + * * @throws PrestaShopObjectNotFoundExceptionCore * @throws PrestaShopDatabaseException * @throws PrestaShopException @@ -392,7 +401,8 @@ class RetailcrmExport ->setApi(static::$api) ->setCmsOrder($object) ->setCmsCustomer($customer) - ->buildOrderWithPreparedCustomer(); + ->buildOrderWithPreparedCustomer() + ; if (empty($crmOrder)) { return false; @@ -410,9 +420,9 @@ class RetailcrmExport $response = static::$api->ordersEdit($crmOrder); if (empty($existingOrder['payments']) && !empty($crmOrder['payments'])) { - $payment = array_merge(reset($crmOrder['payments']), array( - 'order' => array('externalId' => $crmOrder['externalId']) - )); + $payment = array_merge(reset($crmOrder['payments']), [ + 'order' => ['externalId' => $crmOrder['externalId']], + ]); static::$api->ordersPaymentCreate($payment); } } @@ -427,9 +437,9 @@ class RetailcrmExport */ private static function validateState() { - if (!static::$api || - !static::$ordersOffset || - !static::$customersOffset + if (!static::$api + || !static::$ordersOffset + || !static::$customersOffset ) { return false; } diff --git a/retailcrm/lib/RetailcrmFilterInterface.php b/retailcrm/lib/RetailcrmFilterInterface.php index 0ca1a8d..a6fcaa0 100644 --- a/retailcrm/lib/RetailcrmFilterInterface.php +++ b/retailcrm/lib/RetailcrmFilterInterface.php @@ -41,7 +41,8 @@ interface RetailcrmFilterInterface /** * @param object|array|string $object * @param array $parameters + * * @return object|array|string */ public static function filter($object, array $parameters); -} \ No newline at end of file +} diff --git a/retailcrm/lib/RetailcrmHistory.php b/retailcrm/lib/RetailcrmHistory.php index dcf7391..05a372f 100644 --- a/retailcrm/lib/RetailcrmHistory.php +++ b/retailcrm/lib/RetailcrmHistory.php @@ -51,25 +51,26 @@ class RetailcrmHistory { $lastSync = Configuration::get('RETAILCRM_LAST_CUSTOMERS_SYNC'); - $customerFix = array(); + $customerFix = []; - $filter = $lastSync === false - ? array('startDate' => date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))) - : array('sinceId' => $lastSync); + $filter = false === $lastSync + ? ['startDate' => date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))] + : ['sinceId' => $lastSync]; $request = new RetailcrmApiPaginatedRequest(); - $historyChanges = array(); + $historyChanges = []; $history = $request ->setApi(self::$api) ->setMethod('customersHistory') - ->setParams(array($filter, '{{page}}')) + ->setParams([$filter, '{{page}}']) ->setDataKey('history') ->setLimit(100) ->setPageLimit(50) ->execute() - ->getData(); + ->getData() + ; - if (count($history) > 0) { + if (0 < count($history)) { $historyChanges = static::filterHistory($history, 'customer'); $end = end($history); Configuration::updateValue('RETAILCRM_LAST_CUSTOMERS_SYNC', $end['id']); @@ -77,7 +78,7 @@ class RetailcrmHistory if (count($historyChanges)) { $customersHistory = RetailcrmHistoryHelper::assemblyCustomer($historyChanges); - RetailcrmLogger::writeDebugArray(__METHOD__, array('Assembled history:', $customersHistory)); + RetailcrmLogger::writeDebugArray(__METHOD__, ['Assembled history:', $customersHistory]); foreach ($customersHistory as $customerHistory) { $customerHistory = RetailcrmTools::filter( @@ -111,43 +112,46 @@ class RetailcrmHistory $addressBuilder = new RetailcrmCustomerAddressBuilder(); $addressBuilder - ->setCustomerAddress($customerAddress); + ->setCustomerAddress($customerAddress) + ; $customerBuilder ->setCustomer($foundCustomer) ->setAddressBuilder($addressBuilder) ->setDataCrm($customerData) - ->build(); + ->build() + ; $customer = $customerBuilder->getData()->getCustomer(); $address = $customerBuilder->getData()->getCustomerAddress(); - if (self::loadInCMS($customer, 'update') === false) { + if (false === self::loadInCMS($customer, 'update')) { continue; } if (!empty($address)) { RetailcrmTools::assignAddressIdsByFields($customer, $address); - if (self::loadInCMS($address, 'update') === false) { + if (false === self::loadInCMS($address, 'update')) { continue; } } } else { $customerBuilder ->setDataCrm($customerHistory) - ->build(); + ->build() + ; $customer = $customerBuilder->getData()->getCustomer(); - if (self::loadInCMS($customer, 'add') === false) { + if (false === self::loadInCMS($customer, 'add')) { continue; } - $customerFix[] = array( + $customerFix[] = [ 'id' => $customerHistory['id'], - 'externalId' => $customer->id - ); + 'externalId' => $customer->id, + ]; $customer->update(); @@ -156,7 +160,7 @@ class RetailcrmHistory $address->id_customer = $customer->id; - if (self::loadInCMS($address, 'add') === false) { + if (false === self::loadInCMS($address, 'add')) { continue; } } @@ -177,6 +181,7 @@ class RetailcrmHistory * Get orders history * * @return mixed + * * @throws \PrestaShopException * @throws \PrestaShopDatabaseException */ @@ -185,19 +190,19 @@ class RetailcrmHistory $lastSync = Configuration::get('RETAILCRM_LAST_ORDERS_SYNC'); $lastDate = Configuration::get('RETAILCRM_LAST_SYNC'); - if ($lastSync === false && $lastDate === false) { - $filter = array( + if (false === $lastSync && false === $lastDate) { + $filter = [ 'startDate' => date( 'Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))) - ) - ); - } elseif ($lastSync === false && $lastDate !== false) { - $filter = array('startDate' => $lastDate); - } elseif ($lastSync !== false) { - $filter = array('sinceId' => $lastSync); + ), + ]; + } elseif (false === $lastSync && false !== $lastDate) { + $filter = ['startDate' => $lastDate]; + } elseif (false !== $lastSync) { + $filter = ['sinceId' => $lastSync]; } else { - $filter = array(); + $filter = []; } $orderFix = []; @@ -210,26 +215,27 @@ class RetailcrmHistory $history = $request ->setApi(self::$api) ->setMethod('ordersHistory') - ->setParams(array($filter, '{{page}}')) + ->setParams([$filter, '{{page}}']) ->setDataKey('history') ->setLimit(100) ->setPageLimit(50) ->execute() - ->getData(); + ->getData() + ; - if (count($history) > 0) { + if (0 < count($history)) { $historyChanges = static::filterHistory($history, 'order'); $end = end($history); Configuration::updateValue('RETAILCRM_LAST_ORDERS_SYNC', $end['id']); } if (count($historyChanges)) { - $default_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT'); + $default_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); $references = new RetailcrmReferences(self::$api); - $receiveOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING)); - $sendOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_SENDING)); + $receiveOrderNumber = (bool) (Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING)); + $sendOrderNumber = (bool) (Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_SENDING)); $statuses = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_STATUS'), true))); - $cartStatus = (string)(Configuration::get('RETAILCRM_API_SYNCHRONIZED_CART_STATUS')); + $cartStatus = (string) (Configuration::get('RETAILCRM_API_SYNCHRONIZED_CART_STATUS')); $deliveries = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true))); $payments = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true))); $deliveryDefault = json_decode(Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT'), true); @@ -241,7 +247,7 @@ class RetailcrmHistory } $orders = RetailcrmHistoryHelper::assemblyOrder($historyChanges); - RetailcrmLogger::writeDebugArray(__METHOD__, array('Assembled history:', $orders)); + RetailcrmLogger::writeDebugArray(__METHOD__, ['Assembled history:', $orders]); foreach ($orders as $order_history) { $order_history = RetailcrmTools::filter( @@ -249,7 +255,7 @@ class RetailcrmHistory $order_history ); - if (isset($order_history['deleted']) && $order_history['deleted'] == true) { + if (isset($order_history['deleted']) && true == $order_history['deleted']) { continue; } $infoOrder = null; @@ -271,7 +277,7 @@ class RetailcrmHistory // status $state = $order['status']; - if (array_key_exists($state, $statuses) && $statuses[$state] != '') { + if (array_key_exists($state, $statuses) && '' != $statuses[$state]) { $orderStatus = $statuses[$state]; } @@ -280,12 +286,12 @@ class RetailcrmHistory $paymentId = null; $paymentType = null; if (isset($order['payments'])) { - if (count($order['payments']) === 1) { + if (1 === count($order['payments'])) { $paymentCRM = end($order['payments']); $paymentTypeCRM = $paymentCRM['type']; - } elseif (count($order['payments']) > 1) { + } elseif (1 < count($order['payments'])) { foreach ($order['payments'] as $paymentCRM) { - if (isset($paymentCRM['status']) && $paymentCRM['status'] !== 'paid') { + if (isset($paymentCRM['status']) && 'paid' !== $paymentCRM['status']) { $paymentTypeCRM = $paymentCRM['type']; break; } @@ -332,7 +338,7 @@ class RetailcrmHistory // delivery $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : false; - if ($delivery && array_key_exists($delivery, $deliveries) && $deliveries[$delivery] != '') { + if ($delivery && array_key_exists($delivery, $deliveries) && '' != $deliveries[$delivery]) { $deliveryType = $deliveries[$delivery]; } @@ -355,7 +361,7 @@ class RetailcrmHistory $customer = null; $customerId = null; - if ($order['customer']['type'] === 'customer_corporate' + if ('customer_corporate' === $order['customer']['type'] && RetailcrmTools::isCorporateEnabled() && !empty($order['contact']) && array_key_exists('externalId', $order['contact']) @@ -366,7 +372,7 @@ class RetailcrmHistory if (empty($customerId) && !empty($order['contact']['email'])) { $customer = Customer::getCustomersByEmail($order['contact']['email']); - $customer = is_array($customer) ? reset($customer) : array(); + $customer = is_array($customer) ? reset($customer) : []; if (array_key_exists('id_customer', $customer)) { $customerId = $customer['id_customer']; @@ -381,14 +387,15 @@ class RetailcrmHistory $corporateCustomerBuilder = new RetailcrmCorporateCustomerBuilder(); $dataOrder = array_merge( $order['contact'], - array('address' => $order['company']['address']) + ['address' => $order['company']['address']] ); $corporateCustomerBuilder ->setCustomer(new Customer($customerId)) ->setDataCrm($dataOrder) ->extractCompanyDataFromOrder($order) - ->build(); + ->build() + ; $customer = $corporateCustomerBuilder->getData()->getCustomer(); $addressInvoice = $corporateCustomerBuilder->getData()->getCustomerAddress(); @@ -400,7 +407,8 @@ class RetailcrmHistory $customerBuilder ->setDataCrm($order['customer']) - ->build(); + ->build() + ; $customer = $customerBuilder->getData()->getCustomer(); $addressInvoice = $customerBuilder->getData()->getCustomerAddress(); @@ -410,7 +418,7 @@ class RetailcrmHistory $customer->id = self::getCustomerIdByEmail($customer->email); } - if (self::loadInCMS($customer, 'save') === false) { + if (false === self::loadInCMS($customer, 'save')) { continue; } @@ -427,7 +435,7 @@ class RetailcrmHistory $order['company']['address']['id'], array_merge( $order['company']['address'], - array('externalId' => $addressInvoice->id) + ['externalId' => $addressInvoice->id] ), 'id', 'id' @@ -449,7 +457,8 @@ class RetailcrmHistory ->setLastName(isset($order['lastName']) ? $order['lastName'] : null) ->setPhone(isset($order['phone']) ? $order['phone'] : null) ->build() - ->getData(); + ->getData() + ; if (RetailcrmTools::validateEntity($addressDelivery)) { RetailcrmTools::assignAddressIdsByFields($customer, $addressDelivery); @@ -466,15 +475,15 @@ class RetailcrmHistory $cart->id_currency = $default_currency; $cart->id_lang = self::$default_lang; $cart->id_shop = Context::getContext()->shop->id; - $cart->id_shop_group = intval(Context::getContext()->shop->id_shop_group); + $cart->id_shop_group = (int) (Context::getContext()->shop->id_shop_group); $cart->id_customer = $customer->id; - $cart->id_address_delivery = isset($addressDelivery->id) ? (int)$addressDelivery->id : 0; - $cart->id_address_invoice = isset($addressInvoice->id) ? (int)$addressInvoice->id : 0; - $cart->id_carrier = (int)$deliveryType; + $cart->id_address_delivery = isset($addressDelivery->id) ? (int) $addressDelivery->id : 0; + $cart->id_address_invoice = isset($addressInvoice->id) ? (int) $addressInvoice->id : 0; + $cart->id_carrier = (int) $deliveryType; self::loadInCMS($cart, 'add'); - $products = array(); + $products = []; if (!empty($order['items'])) { foreach ($order['items'] as $item) { if (RetailcrmOrderBuilder::isGiftItem($item)) { @@ -482,11 +491,11 @@ class RetailcrmHistory } $productId = explode('#', $item['offer']['externalId']); - $product = array(); - $product['id_product'] = (int)$productId[0]; + $product = []; + $product['id_product'] = (int) $productId[0]; $product['id_product_attribute'] = !empty($productId[1]) ? $productId[1] : 0; $product['quantity'] = $item['quantity']; - $product['id_address_delivery'] = isset($addressDelivery->id) ? (int)$addressDelivery->id : 0; + $product['id_address_delivery'] = isset($addressDelivery->id) ? (int) $addressDelivery->id : 0; $products[] = $product; } } @@ -500,18 +509,18 @@ class RetailcrmHistory */ $newOrder = new Order(); $newOrder->id_shop = Context::getContext()->shop->id; - $newOrder->id_shop_group = intval(Context::getContext()->shop->id_shop_group); - $newOrder->id_address_delivery = isset($addressDelivery->id) ? (int)$addressDelivery->id : 0; - $newOrder->id_address_invoice = isset($addressInvoice->id) ? (int)$addressInvoice->id : 0; - $newOrder->id_cart = (int)$cart->id; + $newOrder->id_shop_group = (int) (Context::getContext()->shop->id_shop_group); + $newOrder->id_address_delivery = isset($addressDelivery->id) ? (int) $addressDelivery->id : 0; + $newOrder->id_address_invoice = isset($addressInvoice->id) ? (int) $addressInvoice->id : 0; + $newOrder->id_cart = (int) $cart->id; $newOrder->id_currency = $default_currency; $newOrder->id_lang = self::$default_lang; - $newOrder->id_customer = (int)$customer->id; + $newOrder->id_customer = (int) $customer->id; $orderNumber = $receiveOrderNumber ? $order['number'] : $newOrder->generateReference(); $newOrder->reference = $orderNumber; if (isset($deliveryType)) { - $newOrder->id_carrier = (int)$deliveryType; + $newOrder->id_carrier = (int) $deliveryType; } if (isset($paymentType)) { @@ -523,6 +532,7 @@ class RetailcrmHistory $totalPaid = $order['totalSumm']; $orderTotalProducts = array_reduce($order['items'], function ($sum, $it) { $sum += $it['initialPrice'] * $it['quantity']; + return $sum; }); $deliveryCost = $order['delivery']['cost']; @@ -537,8 +547,8 @@ class RetailcrmHistory $newOrder->total_paid_tax_excl = $totalPaid; $newOrder->total_paid_real = $totalPaid; - $newOrder->total_products = (int)$orderTotalProducts; - $newOrder->total_products_wt = (int)$orderTotalProducts; + $newOrder->total_products = (int) $orderTotalProducts; + $newOrder->total_products_wt = (int) $orderTotalProducts; $newOrder->total_shipping = $deliveryCost; $newOrder->total_shipping_tax_incl = $deliveryCost; @@ -603,7 +613,7 @@ class RetailcrmHistory foreach ($order['payments'] as $payment) { if (!isset($payment['externalId']) && isset($payment['status']) - && $payment['status'] === 'paid' + && 'paid' === $payment['status'] ) { $paymentTypeCRM = isset($payment['type']) ? $payment['type'] : null; $paymentType = null; @@ -668,10 +678,10 @@ class RetailcrmHistory * Create order details */ - $newItemsIds = array(); + $newItemsIds = []; if (!empty($order['items'])) { foreach ($order['items'] as $item) { - $product = new Product((int)$item['offer']['externalId'], false, self::$default_lang); + $product = new Product((int) $item['offer']['externalId'], false, self::$default_lang); $product_id = $item['offer']['externalId']; $product_attribute_id = 0; @@ -679,13 +689,13 @@ class RetailcrmHistory continue; } - if (strpos($item['offer']['externalId'], '#') !== false) { + if (false !== strpos($item['offer']['externalId'], '#')) { $externalIds = explode('#', $item['offer']['externalId']); $product_id = $externalIds[0]; $product_attribute_id = $externalIds[1]; } - if ($product_attribute_id != 0) { + if (0 != $product_attribute_id) { $productName = htmlspecialchars( strip_tags(Product::getProductName($product_id, $product_attribute_id)) ); @@ -702,14 +712,14 @@ class RetailcrmHistory $orderDetail->id_order_invoice = $newOrder->invoice_number; $orderDetail->id_shop = Context::getContext()->shop->id; - $orderDetail->product_id = (int)$product_id; - $orderDetail->product_attribute_id = (int)$product_attribute_id; - $orderDetail->product_reference = implode('', array('\'', $product->reference, '\'')); + $orderDetail->product_id = (int) $product_id; + $orderDetail->product_attribute_id = (int) $product_attribute_id; + $orderDetail->product_reference = implode('', ['\'', $product->reference, '\'']); $orderDetail->product_price = $productPrice; $orderDetail->original_product_price = $productPrice; - $orderDetail->product_quantity = (int)$item['quantity']; - $orderDetail->product_quantity_in_stock = (int)$item['quantity']; + $orderDetail->product_quantity = (int) $item['quantity']; + $orderDetail->product_quantity_in_stock = (int) $item['quantity']; $orderDetail->total_price_tax_incl = $productPrice * $orderDetail->product_quantity; $orderDetail->unit_price_tax_incl = $productPrice; @@ -717,7 +727,6 @@ class RetailcrmHistory $orderDetail->id_warehouse = !empty($newOrder->id_warehouse) ? $newOrder->id_warehouse : 0; if (!$product->checkQty($orderDetail->product_quantity)) { - self::$api->ordersFixExternalIds([[ 'id' => $order['id'], 'externalId' => $newOrder->id, @@ -746,26 +755,26 @@ class RetailcrmHistory } // collect order ids for single fix request - $orderFix[] = array('id' => $order['id'], 'externalId' => $newOrder->id); + $orderFix[] = ['id' => $order['id'], 'externalId' => $newOrder->id]; // update order items ids in crm $newItemsIdsByOrderId[$newOrder->id] = $newItemsIds; // collect orders id and reference if option sendOrderNumber enabled if ($sendOrderNumber) { - $updateOrderIds[] = array( + $updateOrderIds[] = [ 'externalId' => $newOrder->id, 'number' => $newOrder->reference, - ); + ]; } } else { $order = $order_history; - if (stripos($order['externalId'], 'pscart_') !== false) { + if (false !== stripos($order['externalId'], 'pscart_')) { continue; } - $orderToUpdate = new Order((int)$order['externalId']); + $orderToUpdate = new Order((int) $order['externalId']); if (!Validate::isLoadedObject($orderToUpdate)) { continue; } @@ -773,9 +782,9 @@ class RetailcrmHistory $order = RetailcrmTools::filter( 'RetailcrmFilterOrdersHistoryUpdate', $order, - array( - 'orderToUpdate' => $orderToUpdate - ) + [ + 'orderToUpdate' => $orderToUpdate, + ] ); self::handleCustomerDataChange($orderToUpdate, $order); @@ -839,13 +848,14 @@ class RetailcrmHistory ->setPhone($orderPhone) ->setAlias($orderAddress->alias) ->build() - ->getData(); + ->getData() + ; if (RetailcrmTools::validateEntity($address, $orderToUpdate)) { $address->id = null; RetailcrmTools::assignAddressIdsByFields(new Customer($orderToUpdate->id_customer), $address); - if ($address->id === null) { + if (null === $address->id) { // Modifying an address in order creates another address // instead of changing the original one. This issue has been fixed in PS 1.7.7 if (version_compare(_PS_VERSION_, '1.7.7', '<')) { @@ -878,12 +888,12 @@ class RetailcrmHistory if ( ( - $dtype !== null && - isset($deliveries[$dtype]) - && $deliveries[$dtype] !== null + null !== $dtype + && isset($deliveries[$dtype]) + && null !== $deliveries[$dtype] && $deliveries[$dtype] !== $orderToUpdate->id_carrier ) - || $dcost !== null + || null !== $dcost ) { if (property_exists($orderToUpdate, 'id_order_carrier')) { $idOrderCarrier = $orderToUpdate->id_order_carrier; @@ -895,11 +905,11 @@ class RetailcrmHistory $orderCarrier = new OrderCarrier($idOrderCarrier); - if ($dtype != null) { + if (null != $dtype) { $orderCarrier->id_carrier = $deliveries[$dtype]; } - if ($dcost != null) { + if (null != $dcost) { $orderCarrier->shipping_cost_tax_incl = $dcost; $orderCarrier->shipping_cost_tax_excl = $dcost; } @@ -910,14 +920,14 @@ class RetailcrmHistory } } - /** + /* * check payment type */ if (!empty($order['payments'])) { foreach ($order['payments'] as $payment) { if (!isset($payment['externalId']) && isset($payment['status']) - && $payment['status'] === 'paid' + && 'paid' === $payment['status'] ) { $paymentTypeCRM = isset($payment['type']) ? $payment['type'] : null; $paymentType = null; @@ -981,7 +991,7 @@ class RetailcrmHistory */ $id_order_detail = null; foreach ($order['items'] as $key => $item) { - if (isset($item['delete']) && $item['delete'] == true) { + if (isset($item['delete']) && true == $item['delete']) { if (RetailcrmOrderBuilder::isGiftItem($item)) { $orderToUpdate->gift = false; } @@ -1025,11 +1035,11 @@ class RetailcrmHistory $product_attribute_id = $parsedExtId['product_attribute_id']; $isExistingItem = isset($item['create']) ? false : true; - if ($isExistingItem && - $product_id == $orderItem['product_id'] && - $product_attribute_id == $orderItem['product_attribute_id'] + if ($isExistingItem + && $product_id == $orderItem['product_id'] + && $product_attribute_id == $orderItem['product_attribute_id'] ) { - $product = new Product((int)$product_id, false, self::$default_lang); + $product = new Product((int) $product_id, false, self::$default_lang); $orderDetailId = !empty($parsedExtId['id_order_detail']) ? $parsedExtId['id_order_detail'] : $orderItem['id_order_detail']; @@ -1050,7 +1060,7 @@ class RetailcrmHistory $orderDetail->product_quantity = $item['quantity']; $orderDetail->product_quantity_in_stock = $item['quantity']; - if ($deltaQuantity < 0 && !$product->checkQty(-1 * $deltaQuantity)) { + if (0 > $deltaQuantity && !$product->checkQty(-1 * $deltaQuantity)) { $newStatus = self::setOutOfStockStatus( $infoOrder, $orderToUpdate, @@ -1084,7 +1094,7 @@ class RetailcrmHistory * Check new items */ $isNewItemsExist = false; - $newItemsIds = array(); + $newItemsIds = []; foreach ($order['items'] as $key => $newItem) { if (RetailcrmOrderBuilder::isGiftItem($newItem)) { continue; @@ -1099,9 +1109,9 @@ class RetailcrmHistory $product_id = $parsedExtId['product_id']; $product_attribute_id = $parsedExtId['product_attribute_id']; - $product = new Product((int)$product_id, false, self::$default_lang); + $product = new Product((int) $product_id, false, self::$default_lang); - if ($product_attribute_id != 0) { + if (0 != $product_attribute_id) { $productName = htmlspecialchars( strip_tags(Product::getProductName($product_id, $product_attribute_id)) ); @@ -1121,14 +1131,14 @@ class RetailcrmHistory $orderDetail->id_order_invoice = $orderToUpdate->invoice_number; $orderDetail->id_shop = Context::getContext()->shop->id; - $orderDetail->product_id = (int)$product_id; - $orderDetail->product_attribute_id = (int)$product_attribute_id; - $orderDetail->product_reference = implode('', array('\'', $product->reference, '\'')); + $orderDetail->product_id = (int) $product_id; + $orderDetail->product_attribute_id = (int) $product_attribute_id; + $orderDetail->product_reference = implode('', ['\'', $product->reference, '\'']); $orderDetail->product_price = $productPrice; $orderDetail->original_product_price = $productPrice; - $orderDetail->product_quantity = (int)$newItem['quantity']; - $orderDetail->product_quantity_in_stock = (int)$newItem['quantity']; + $orderDetail->product_quantity = (int) $newItem['quantity']; + $orderDetail->product_quantity_in_stock = (int) $newItem['quantity']; $orderDetail->total_price_tax_incl = $productPrice * $orderDetail->product_quantity; $orderDetail->unit_price_tax_incl = $productPrice; @@ -1177,6 +1187,7 @@ class RetailcrmHistory $totalPaid = $infoOrder['totalSumm']; $orderTotalProducts = array_reduce($infoOrder['items'], function ($sum, $it) { $sum += $it['initialPrice'] * $it['quantity']; + return $sum; }); $deliveryCost = $infoOrder['delivery']['cost']; @@ -1203,7 +1214,7 @@ class RetailcrmHistory self::loadInCMS($orderToUpdate, 'update'); } - /** + /* * check status */ if (!empty($order['status']) && !array_key_exists($orderToUpdate->id, $updateOrderStatuses)) { @@ -1242,10 +1253,10 @@ class RetailcrmHistory // collect orders id and reference if option sendOrderNumber enabled if ($sendOrderNumber) { - $updateOrderIds[] = array( + $updateOrderIds[] = [ 'externalId' => $orderToUpdate->id, 'number' => $orderToUpdate->reference, - ); + ]; } } } @@ -1292,10 +1303,10 @@ class RetailcrmHistory && $crmOrderResponse->isSuccessful() && $crmOrderResponse->offsetExists('order') ) { - return (array)$crmOrderResponse['order']; + return (array) $crmOrderResponse['order']; } - return array(); + return []; } /** @@ -1309,12 +1320,12 @@ class RetailcrmHistory { RetailcrmLogger::writeDebugArray( __METHOD__, - array( + [ 'Using this individual person data in order to set it into order,', $data->getOrder()->id, ': ', - $crmCustomer - ) + $crmCustomer, + ] ); if ($isContact) { @@ -1343,13 +1354,13 @@ class RetailcrmHistory if (isset($crmOrder['fullPaidAt']) && !empty($crmOrder['fullPaidAt'])) { $stype = $statusArray['out_of_stock_paid']; - if ($stype == '') { + if ('' == $stype) { return false; } } else { $stype = $statusArray['out_of_stock_not_paid']; - if ($stype == '') { + if ('' == $stype) { return false; } } @@ -1390,12 +1401,12 @@ class RetailcrmHistory * @param \Order $order * @param array $historyOrder * - * @return bool True if customer change happened; false otherwise. + * @return bool true if customer change happened; false otherwise */ private static function handleCustomerDataChange($order, $historyOrder) { $handled = false; - $crmOrder = array(); + $crmOrder = []; $newCustomerId = null; $switcher = new RetailcrmCustomerSwitcher(); $data = new RetailcrmCustomerSwitcherState(); @@ -1429,7 +1440,7 @@ class RetailcrmHistory if ($isChangedToRegular) { self::prepareChangeToIndividual( - RetailcrmTools::arrayValue($crmOrder, 'customer', array()), + RetailcrmTools::arrayValue($crmOrder, 'customer', []), $data ); } @@ -1453,12 +1464,12 @@ class RetailcrmHistory if (RetailcrmTools::isCrmOrderCorporate($crmOrder)) { self::prepareChangeToIndividual( - RetailcrmTools::arrayValue($crmOrder, 'contact', array()), + RetailcrmTools::arrayValue($crmOrder, 'contact', []), $data, true ); - $data->setNewCustomer(array()); + $data->setNewCustomer([]); } } @@ -1478,7 +1489,8 @@ class RetailcrmHistory try { $result = $switcher->setData($data) ->build() - ->getResult(); + ->getResult() + ; $result->save(); $handled = true; } catch (\Exception $exception) { @@ -1517,10 +1529,10 @@ class RetailcrmHistory { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'order_detail - WHERE id_order = ' . pSQL((int)$order_id) . ' - AND product_id = ' . pSQL((int)$product_id) . ' - AND product_attribute_id = ' . pSQL((int)$product_attribute_id) . ' - AND id_order_detail = ' . pSQL((int)$id_order_detail) + WHERE id_order = ' . pSQL((int) $order_id) . ' + AND product_id = ' . pSQL((int) $product_id) . ' + AND product_attribute_id = ' . pSQL((int) $product_attribute_id) . ' + AND id_order_detail = ' . pSQL((int) $id_order_detail) ); } @@ -1537,7 +1549,7 @@ class RetailcrmHistory * @param \ObjectModel|\ObjectModelCore $object * @param string $action * - * @return boolean + * @return bool */ private static function loadInCMS($object, $action) { @@ -1569,7 +1581,7 @@ class RetailcrmHistory 'loadInCMS', sprintf( ' > %s %s', - (string)$action, + (string) $action, $e->getMessage() ) ); @@ -1596,16 +1608,16 @@ class RetailcrmHistory */ private static function filterHistory($historyEntries, $recordType) { - $history = array(); - $organizedHistory = array(); - $notOurChanges = array(); + $history = []; + $organizedHistory = []; + $notOurChanges = []; foreach ($historyEntries as $entry) { if (!isset($entry[$recordType]['externalId'])) { - if ($entry['source'] == 'api' + if ('api' == $entry['source'] && isset($change['apiKey']['current']) - && $entry['apiKey']['current'] == true - && $entry['field'] != 'externalId' + && true == $entry['apiKey']['current'] + && 'externalId' != $entry['field'] ) { continue; } else { @@ -1619,19 +1631,19 @@ class RetailcrmHistory $field = $entry['field']; if (!isset($organizedHistory[$externalId])) { - $organizedHistory[$externalId] = array(); + $organizedHistory[$externalId] = []; } if (!isset($notOurChanges[$externalId])) { - $notOurChanges[$externalId] = array(); + $notOurChanges[$externalId] = []; } if ( - $entry['source'] == 'api' + 'api' == $entry['source'] && isset($entry['apiKey']['current']) - && $entry['apiKey']['current'] == true + && true == $entry['apiKey']['current'] ) { - if (isset($notOurChanges[$externalId][$field]) || $field == 'externalId' || $field == 'status') { + if (isset($notOurChanges[$externalId][$field]) || 'externalId' == $field || 'status' == $field) { $organizedHistory[$externalId][] = $entry; } else { continue; @@ -1663,7 +1675,7 @@ class RetailcrmHistory if (!empty($customerEmail)) { $item = Customer::getCustomersByEmail($customerEmail); - if (is_array($item) && count($item) > 0) { + if (is_array($item) && 0 < count($item)) { $item = reset($item); return (int) $item['id_customer']; @@ -1686,7 +1698,7 @@ class RetailcrmHistory { if (isset($item['externalIds'])) { foreach ($item['externalIds'] as $externalId) { - if ($externalId['code'] == 'prestashop') { + if ('prestashop' == $externalId['code']) { return static::parseItemExternalIdString($externalId['value']); } } @@ -1707,23 +1719,23 @@ class RetailcrmHistory private static function parseItemExternalIdString($externalIdString) { $parsed = explode('_', $externalIdString); - $data = array( + $data = [ 'product_id' => 0, 'product_attribute_id' => 0, - 'id_order_detail' => 0 - ); + 'id_order_detail' => 0, + ]; - if (count($parsed) > 0) { + if (0 < count($parsed)) { $productIdParsed = explode('#', $parsed[0]); - if (count($productIdParsed) == 2) { + if (2 == count($productIdParsed)) { $data['product_id'] = $productIdParsed[0]; $data['product_attribute_id'] = $productIdParsed[1]; - } elseif (count($productIdParsed) == 1) { + } elseif (1 == count($productIdParsed)) { $data['product_id'] = $parsed[0]; } - if (count($parsed) == 2) { + if (2 == count($parsed)) { $data['id_order_detail'] = $parsed[1]; } } @@ -1755,10 +1767,10 @@ class RetailcrmHistory */ private static function removeEdgeQuotes($str) { - if (strlen($str) >= 2) { + if (2 <= strlen($str)) { $newStr = $str; - if ($newStr[0] == '\'' && $newStr[strlen($newStr) - 1] == '\'') { + if ('\'' == $newStr[0] && '\'' == $newStr[strlen($newStr) - 1]) { $newStr = substr($newStr, 1, strlen($newStr) - 2); } @@ -1780,33 +1792,33 @@ class RetailcrmHistory { $object->product_name = static::removeEdgeQuotes($name); - if ($object->validateField('product_name', $object->product_name) !== true) { - $object->product_name = implode('', array('\'', $name, '\'')); + if (true !== $object->validateField('product_name', $object->product_name)) { + $object->product_name = implode('', ['\'', $name, '\'']); } } private static function updateOrderItems($orderId, $newItemsIds) { - $upOrderItems = array( + $upOrderItems = [ 'externalId' => $orderId, - ); + ]; $orderdb = new Order($orderId); foreach ($orderdb->getProducts() as $item) { - if (isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) { + if (isset($item['product_attribute_id']) && 0 < $item['product_attribute_id']) { $productId = $item['product_id'] . '#' . $item['product_attribute_id']; } else { $productId = $item['product_id']; } - $crmItem = array( - 'externalIds' => array( - array( + $crmItem = [ + 'externalIds' => [ + [ 'code' => 'prestashop', - 'value' => $productId . "_" . $item['id_order_detail'], - ) - ), - ); + 'value' => $productId . '_' . $item['id_order_detail'], + ], + ], + ]; if (array_key_exists($item['id_order_detail'], $newItemsIds)) { $crmItem['id'] = $newItemsIds[$item['id_order_detail']]; @@ -1825,14 +1837,15 @@ class RetailcrmHistory * Updates sinceId for orders or customers to the latest value * * @param string $entity Can be either 'orders' or 'customers' + * * @return bool */ public static function updateSinceId($entity) { - if ($entity === 'orders') { + if ('orders' === $entity) { $key = 'RETAILCRM_LAST_ORDERS_SYNC'; $method = 'ordersHistory'; - } elseif ($entity === 'customers') { + } elseif ('customers' === $entity) { $key = 'RETAILCRM_LAST_CUSTOMERS_SYNC'; $method = 'customersHistory'; } else { @@ -1843,24 +1856,24 @@ class RetailcrmHistory RetailcrmLogger::writeDebug(__METHOD__, "Current $entity sinceId: $currentSinceID"); $historyResponse = call_user_func_array( - array(self::$api, $method), - array( - array('sinceId' => $currentSinceID), + [self::$api, $method], + [ + ['sinceId' => $currentSinceID], null, - 20 - ) + 20, + ] ); if ($historyResponse instanceof RetailcrmApiResponse && $historyResponse->offsetExists('pagination')) { $lastPage = $historyResponse['pagination']['totalPageCount']; - if ($lastPage > 1) { + if (1 < $lastPage) { $historyResponse = call_user_func_array( - array(self::$api, $method), - array( - array('sinceId' => $currentSinceID), + [self::$api, $method], + [ + ['sinceId' => $currentSinceID], $lastPage, - 20 - ) + 20, + ] ); } @@ -1871,7 +1884,7 @@ class RetailcrmHistory $history = $historyResponse['history']; $lastSinceId = end($history)['id']; - if ($currentSinceID !== strval($lastSinceId)) { + if ($currentSinceID !== (string) $lastSinceId) { RetailcrmLogger::writeDebug(__METHOD__, "Updating to: $lastSinceId"); Configuration::updateValue($key, $lastSinceId); } diff --git a/retailcrm/lib/RetailcrmHistoryHelper.php b/retailcrm/lib/RetailcrmHistoryHelper.php index 4272b85..19fe36b 100644 --- a/retailcrm/lib/RetailcrmHistoryHelper.php +++ b/retailcrm/lib/RetailcrmHistoryHelper.php @@ -35,23 +35,24 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ -class RetailcrmHistoryHelper { +class RetailcrmHistoryHelper +{ public static function assemblyOrder($orderHistory) { - if (file_exists( __DIR__ . '/../objects.xml')) { + if (file_exists(__DIR__ . '/../objects.xml')) { $objects = simplexml_load_file(__DIR__ . '/../objects.xml'); - foreach($objects->fields->field as $object) { - $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; + foreach ($objects->fields->field as $object) { + $fields[(string) $object['group']][(string) $object['id']] = (string) $object; } } - $orders = array(); + $orders = []; foreach ($orderHistory as $change) { $change['order'] = self::removeEmpty($change['order']); if (isset($change['order']['items']) && $change['order']['items']) { - $items = array(); + $items = []; - foreach($change['order']['items'] as $item) { + foreach ($change['order']['items'] as $item) { $items[$item['id']] = $item; } @@ -75,10 +76,10 @@ class RetailcrmHistoryHelper { } else { $orders[$change['order']['id']]['payments'][$change['payment']['id']] = $change['payment']; } - if ($change['oldValue'] == null && $change['field'] == 'payments') { + if (null == $change['oldValue'] && 'payments' == $change['field']) { $orders[$change['order']['id']]['payments'][$change['payment']['id']]['create'] = true; } - if ($change['newValue'] == null && $change['field'] == 'payments') { + if (null == $change['newValue'] && 'payments' == $change['field']) { $orders[$change['order']['id']]['payments'][$change['payment']['id']]['delete'] = true; } if (!$orders[$change['order']['id']]['payments'][$change['payment']['id']] && $fields['payment'][$change['field']]) { @@ -93,10 +94,10 @@ class RetailcrmHistoryHelper { $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; } - if (empty($change['oldValue']) && $change['field'] == 'order_product') { + if (empty($change['oldValue']) && 'order_product' == $change['field']) { $orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = true; } - if (empty($change['newValue']) && $change['field'] == 'order_product') { + if (empty($change['newValue']) && 'order_product' == $change['field']) { $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true; } if (!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create']) @@ -106,7 +107,7 @@ class RetailcrmHistoryHelper { } } else { if (isset($fields['delivery'][$change['field']]) - && $fields['delivery'][$change['field']] == 'service' + && 'service' == $fields['delivery'][$change['field']] ) { $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); } elseif (isset($fields['delivery'][$change['field']]) @@ -125,7 +126,7 @@ class RetailcrmHistoryHelper { && $fields['customerContragent'][$change['field']] ) { $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); - } elseif (strripos($change['field'], 'custom_') !== false) { + } elseif (false !== strripos($change['field'], 'custom_')) { $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); } elseif (isset($fields['order'][$change['field']]) && $fields['order'][$change['field']] @@ -141,7 +142,7 @@ class RetailcrmHistoryHelper { $orders[$change['order']['id']]['create'] = 1; } - if(isset($change['deleted'])) { + if (isset($change['deleted'])) { $orders[$change['order']['id']]['deleted'] = 1; } } @@ -152,19 +153,19 @@ class RetailcrmHistoryHelper { public static function assemblyCustomer($customerHistory) { - $fields = array(); + $fields = []; if (file_exists(_PS_ROOT_DIR_ . '/modules/retailcrm/objects.xml')) { $objects = simplexml_load_file(_PS_ROOT_DIR_ . '/modules/retailcrm/objects.xml'); - foreach($objects->fields->field as $object) { - if ($object["group"] == 'customer') { - $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; + foreach ($objects->fields->field as $object) { + if ('customer' == $object['group']) { + $fields[(string) $object['group']][(string) $object['id']] = (string) $object; } } } - $customers = array(); + $customers = []; foreach ($customerHistory as $change) { $change['customer'] = self::removeEmpty($change['customer']); @@ -176,7 +177,7 @@ class RetailcrmHistoryHelper { continue; } - if ($change['field'] == 'id') { + if ('id' == $change['field']) { $customers[$change['customer']['id']] = $change['customer']; } @@ -194,12 +195,12 @@ class RetailcrmHistoryHelper { // email_marketing_unsubscribed_at old value will be null and new value will be datetime in // `Y-m-d H:i:s` format if customer was marked as unsubscribed in retailCRM - if (isset($change['customer']['id']) && - $change['field'] == 'email_marketing_unsubscribed_at' + if (isset($change['customer']['id']) + && 'email_marketing_unsubscribed_at' == $change['field'] ) { - if ($change['oldValue'] == null && is_string(self::newValue($change['newValue']))) { + if (null == $change['oldValue'] && is_string(self::newValue($change['newValue']))) { $customers[$change['customer']['id']]['subscribed'] = false; - } elseif (is_string($change['oldValue']) && self::newValue($change['newValue']) == null) { + } elseif (is_string($change['oldValue']) && null == self::newValue($change['newValue'])) { $customers[$change['customer']['id']]['subscribed'] = true; } } @@ -215,19 +216,19 @@ class RetailcrmHistoryHelper { public static function assemblyCorporateCustomer($customerHistory) { - $fields = array(); + $fields = []; if (file_exists(_PS_ROOT_DIR_ . '/modules/retailcrm/objects.xml')) { $objects = simplexml_load_file(_PS_ROOT_DIR_ . '/modules/retailcrm/objects.xml'); - foreach($objects->fields->field as $object) { - if (in_array($object["group"], array('customerCorporate', 'customerAddress'))) { - $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; + foreach ($objects->fields->field as $object) { + if (in_array($object['group'], ['customerCorporate', 'customerAddress'])) { + $fields[(string) $object['group']][(string) $object['id']] = (string) $object; } } } - $customersCorporate = array(); + $customersCorporate = []; foreach ($customerHistory as $change) { $change['customer'] = self::removeEmpty($change['customer']); @@ -261,13 +262,13 @@ class RetailcrmHistoryHelper { && $fields['customerAddress'][$change['field']] ) { if (empty($customersCorporate[$change['customer']['id']]['address'])) { - $customersCorporate[$change['customer']['id']]['address'] = array(); + $customersCorporate[$change['customer']['id']]['address'] = []; } $customersCorporate[$change['customer']['id']]['address'][$fields['customerAddress'][$change['field']]] = self::newValue($change['newValue']); } - if ($change['field'] == 'address') { + if ('address' == $change['field']) { $customersCorporate[$change['customer']['id']]['address'] = array_merge($change['address'], self::newValue($change['newValue'])); } } @@ -293,10 +294,10 @@ class RetailcrmHistoryHelper { public static function removeEmpty($inputArray) { - $outputArray = array(); + $outputArray = []; if (!empty($inputArray)) { foreach ($inputArray as $key => $element) { - if(!empty($element) || $element === 0 || $element === '0'){ + if (!empty($element) || 0 === $element || '0' === $element) { if (is_array($element)) { $element = self::removeEmpty($element); } @@ -312,7 +313,7 @@ class RetailcrmHistoryHelper { * @param array $address Crm Order address changes * * @return bool true if changed address field, which is used to generate - * address1 and address2 fields in CMS. false otherwise + * address1 and address2 fields in CMS. false otherwise */ public static function isAddressLineChanged($address) { diff --git a/retailcrm/lib/RetailcrmIcml.php b/retailcrm/lib/RetailcrmIcml.php index a198e5e..b5ff660 100644 --- a/retailcrm/lib/RetailcrmIcml.php +++ b/retailcrm/lib/RetailcrmIcml.php @@ -50,7 +50,7 @@ class RetailcrmIcml $this->shop = $shop; $this->file = $file; - $this->properties = array( + $this->properties = [ 'name', 'productName', 'price', @@ -62,14 +62,14 @@ class RetailcrmIcml 'productActivity', 'dimensions', 'vatRate', - ); + ]; - $this->params = array( + $this->params = [ 'article' => 'Артикул', 'color' => 'Цвет', 'weight' => 'Вес', - 'tax' => 'Наценка' - ); + 'tax' => 'Наценка', + ]; } public function generate($categories, $offers) @@ -121,7 +121,7 @@ class RetailcrmIcml $e->appendChild($this->dd->createElement('picture', $category['picture'])); } - if ($category['parentId'] > 0) { + if (0 < $category['parentId']) { $e->setAttribute('parentId', $category['parentId']); } } @@ -152,11 +152,13 @@ class RetailcrmIcml $offerKeys = array_keys($offer); foreach ($offerKeys as $key) { - if ($offer[$key] == null) continue; + if (null == $offer[$key]) { + continue; + } if (in_array($key, $this->properties)) { - if(is_array($offer[$key])) { - foreach($offer[$key] as $property) { + if (is_array($offer[$key])) { + foreach ($offer[$key] as $property) { $e->appendChild( $this->dd->createElement($key) )->appendChild( diff --git a/retailcrm/lib/RetailcrmInventories.php b/retailcrm/lib/RetailcrmInventories.php index 0ee50cc..caaa2f7 100644 --- a/retailcrm/lib/RetailcrmInventories.php +++ b/retailcrm/lib/RetailcrmInventories.php @@ -52,9 +52,9 @@ class RetailcrmInventories $page = 1; do { - $result = self::$api->storeInventories(array(), $page, 250); + $result = self::$api->storeInventories([], $page, 250); - if ($result === false) { + if (false === $result) { return $result; } @@ -63,11 +63,11 @@ class RetailcrmInventories } $totalPageCount = $result['pagination']['totalPageCount']; - $page++; + ++$page; } while ($page <= $totalPageCount); } - private static function setQuantityOffer($offer) + private static function setQuantityOffer($offer) { if (isset($offer['externalId'])) { $invOffer = explode('#', $offer['externalId']); diff --git a/retailcrm/lib/RetailcrmJobManager.php b/retailcrm/lib/RetailcrmJobManager.php index f2257c5..502e19f 100644 --- a/retailcrm/lib/RetailcrmJobManager.php +++ b/retailcrm/lib/RetailcrmJobManager.php @@ -35,14 +35,13 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(@date_default_timezone_get()); } -require_once(dirname(__FILE__) . '/../../../config/config.inc.php'); -require_once(dirname(__FILE__) . '/../../../init.php'); -require_once(dirname(__FILE__) . '/../bootstrap.php'); +require_once __DIR__ . '/../../../config/config.inc.php'; +require_once __DIR__ . '/../../../init.php'; +require_once __DIR__ . '/../bootstrap.php'; if (!defined('_PS_VERSION_')) { exit; @@ -53,7 +52,8 @@ if (!defined('_PS_VERSION_')) { * * @author DIGITAL RETAIL TECHNOLOGIES SL * @license GPL - * @link https://retailcrm.ru + * + * @see https://retailcrm.ru */ class RetailcrmJobManager { @@ -82,14 +82,14 @@ class RetailcrmJobManager * DateInterval must be positive. Pass `null` instead of DateInterval to remove * any delay - in other words, jobs without interval will be executed every time. * - * @param array $jobs Jobs list + * @param array $jobs Jobs list * * @throws \Exception */ public static function startJobs( - $jobs = array() + $jobs = [] ) { - RetailcrmLogger::writeDebug(__METHOD__,'starting JobManager'); + RetailcrmLogger::writeDebug(__METHOD__, 'starting JobManager'); static::execJobs($jobs); } @@ -100,11 +100,11 @@ class RetailcrmJobManager * * @throws \Exception */ - public static function execJobs($jobs = array()) + public static function execJobs($jobs = []) { - $current = date_create('now'); - $lastRuns = array(); - $lastRunsDetails = array(); + $current = date_create_immutable('now'); + $lastRuns = []; + $lastRunsDetails = []; try { $lastRuns = static::getLastRuns(); @@ -140,13 +140,13 @@ class RetailcrmJobManager } uasort($jobs, function ($diff1, $diff2) { - $date1 = new \DateTime(); - $date2 = new \DateTime(); + $date1 = new \DateTimeImmutable(); + $date2 = new \DateTimeImmutable(); - if (!is_null($diff1)) { + if (null !== $diff1) { $date1->add($diff1); } - if (!is_null($diff2)) { + if (null !== $diff2) { $date2->add($diff2); } @@ -159,21 +159,21 @@ class RetailcrmJobManager foreach ($jobs as $job => $diff) { try { - if (isset($lastRuns[$job]) && $lastRuns[$job] instanceof DateTime) { + if (isset($lastRuns[$job]) && $lastRuns[$job] instanceof DateTimeImmutable) { $shouldRunAt = clone $lastRuns[$job]; if ($diff instanceof DateInterval) { $shouldRunAt->add($diff); } } else { - $shouldRunAt = \DateTime::createFromFormat('Y-m-d H:i:s', '1970-01-01 00:00:00'); + $shouldRunAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '1970-01-01 00:00:00'); } RetailcrmLogger::writeDebug(__METHOD__, sprintf( 'Checking %s, interval %s, shouldRunAt: %s: %s', $job, - is_null($diff) ? 'NULL' : $diff->format('%R%Y-%m-%d %H:%i:%s:%F'), - isset($shouldRunAt) && $shouldRunAt instanceof \DateTime + null === $diff ? 'NULL' : $diff->format('%R%Y-%m-%d %H:%i:%s:%F'), + isset($shouldRunAt) && $shouldRunAt instanceof \DateTimeImmutable ? $shouldRunAt->format(DATE_RFC3339) : 'undefined', (isset($shouldRunAt) && $shouldRunAt <= $current) ? 'true' : 'false' @@ -186,7 +186,7 @@ class RetailcrmJobManager __METHOD__, sprintf('Executed job %s, result: %s', $job, $result ? 'true' : 'false') ); - $lastRuns[$job] = new \DateTime('now'); + $lastRuns[$job] = new \DateTimeImmutable('now'); break; } @@ -199,7 +199,7 @@ class RetailcrmJobManager $lastRunsDetails[$job] = [ 'success' => false, - 'lastRun' => new \DateTime('now'), + 'lastRun' => new \DateTimeImmutable('now'), 'error' => [ 'message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString(), @@ -220,7 +220,7 @@ class RetailcrmJobManager if (isset($result) && $result) { $lastRunsDetails[$job] = [ 'success' => true, - 'lastRun' => new \DateTime('now'), + 'lastRun' => new \DateTimeImmutable('now'), 'error' => null, ]; @@ -243,12 +243,13 @@ class RetailcrmJobManager static::unlock(); } - /** * Run job in the force mode so it will run even if there's another job running * * @param $jobName + * * @return bool + * * @throws Exception */ public static function execManualJob($jobName) @@ -259,7 +260,7 @@ class RetailcrmJobManager if ($result) { static::updateLastRunDetail($jobName, [ 'success' => true, - 'lastRun' => new \DateTime('now'), + 'lastRun' => new \DateTimeImmutable('now'), 'error' => null, ]); } @@ -275,7 +276,7 @@ class RetailcrmJobManager RetailcrmLogger::printException($exception, '', false); self::updateLastRunDetail($jobName, [ 'success' => false, - 'lastRun' => new \DateTime('now'), + 'lastRun' => new \DateTimeImmutable('now'), 'error' => [ 'message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString(), @@ -286,32 +287,32 @@ class RetailcrmJobManager } } - /** * Extracts jobs last runs from db * * @return array + * * @throws \Exception */ private static function getLastRuns() { - $lastRuns = json_decode((string)Configuration::getGlobalValue(self::LAST_RUN_NAME), true); + $lastRuns = json_decode((string) Configuration::getGlobalValue(self::LAST_RUN_NAME), true); - if (json_last_error() != JSON_ERROR_NONE) { - $lastRuns = array(); + if (JSON_ERROR_NONE != json_last_error()) { + $lastRuns = []; } else { foreach ($lastRuns as $job => $ran) { - $lastRan = DateTime::createFromFormat(DATE_RFC3339, $ran); + $lastRan = DateTimeImmutable::createFromFormat(DATE_RFC3339, $ran); - if ($lastRan instanceof DateTime) { + if ($lastRan instanceof DateTimeImmutable) { $lastRuns[$job] = $lastRan; } else { - $lastRuns[$job] = new DateTime(); + $lastRuns[$job] = new DateTimeImmutable(); } } } - return (array)$lastRuns; + return (array) $lastRuns; } /** @@ -321,16 +322,16 @@ class RetailcrmJobManager * * @throws \Exception */ - private static function setLastRuns($lastRuns = array()) + private static function setLastRuns($lastRuns = []) { - $now = new DateTime(); + $now = new DateTimeImmutable(); if (!is_array($lastRuns)) { - $lastRuns = array(); + $lastRuns = []; } foreach ($lastRuns as $job => $ran) { - if ($ran instanceof DateTime) { + if ($ran instanceof DateTimeImmutable) { $lastRuns[$job] = $ran->format(DATE_RFC3339); } else { $lastRuns[$job] = $now->format(DATE_RFC3339); @@ -342,12 +343,13 @@ class RetailcrmJobManager ); } - Configuration::updateGlobalValue(self::LAST_RUN_NAME, (string)json_encode($lastRuns)); + Configuration::updateGlobalValue(self::LAST_RUN_NAME, (string) json_encode($lastRuns)); } /** * @param string $jobName * @param Datetime|null $data + * * @throws Exception */ public static function updateLastRun($jobName, $data) @@ -361,19 +363,20 @@ class RetailcrmJobManager * Extracts jobs last runs from db * * @return array + * * @throws \Exception */ public static function getLastRunDetails() { - $lastRuns = json_decode((string)Configuration::getGlobalValue(self::LAST_RUN_DETAIL_NAME), true); + $lastRuns = json_decode((string) Configuration::getGlobalValue(self::LAST_RUN_DETAIL_NAME), true); - if (json_last_error() != JSON_ERROR_NONE) { - $lastRuns = array(); + if (JSON_ERROR_NONE != json_last_error()) { + $lastRuns = []; } else { foreach ($lastRuns as $job => $details) { - $lastRan = DateTime::createFromFormat(DATE_RFC3339, $details['lastRun']); + $lastRan = DateTimeImmutable::createFromFormat(DATE_RFC3339, $details['lastRun']); - if ($lastRan instanceof DateTime) { + if ($lastRan instanceof DateTimeImmutable) { $lastRuns[$job]['lastRun'] = $lastRan; } else { $lastRuns[$job]['lastRun'] = null; @@ -381,7 +384,7 @@ class RetailcrmJobManager } } - return (array)$lastRuns; + return (array) $lastRuns; } /** @@ -391,26 +394,27 @@ class RetailcrmJobManager * * @throws \Exception */ - private static function setLastRunDetails($lastRuns = array()) + private static function setLastRunDetails($lastRuns = []) { if (!is_array($lastRuns)) { - $lastRuns = array(); + $lastRuns = []; } foreach ($lastRuns as $job => $details) { - if (isset($details['lastRun']) && $details['lastRun'] instanceof DateTime) { + if (isset($details['lastRun']) && $details['lastRun'] instanceof DateTimeImmutable) { $lastRuns[$job]['lastRun'] = $details['lastRun']->format(DATE_RFC3339); } else { $lastRuns[$job]['lastRun'] = null; } } - Configuration::updateGlobalValue(self::LAST_RUN_DETAIL_NAME, (string)json_encode($lastRuns)); + Configuration::updateGlobalValue(self::LAST_RUN_DETAIL_NAME, (string) json_encode($lastRuns)); } /** * @param string $jobName * @param array $data + * * @throws Exception */ public static function updateLastRunDetail($jobName, $data) @@ -424,12 +428,13 @@ class RetailcrmJobManager * Runs job * * @param string $job - * @param bool $once - * @param bool $cliMode - * @param bool $force - * @param int $shopId + * @param bool $once + * @param bool $cliMode + * @param bool $force + * @param int $shopId * * @return bool + * * @throws \RetailcrmJobManagerException */ public static function runJob($job, $cliMode = false, $force = false, $shopId = null) @@ -441,7 +446,7 @@ class RetailcrmJobManager } catch (\RetailcrmJobManagerException $exception) { throw $exception; } catch (\Exception $exception) { - throw new RetailcrmJobManagerException($exception->getMessage(), $job, array(), 0, $exception); + throw new RetailcrmJobManagerException($exception->getMessage(), $job, [], 0, $exception); } } @@ -458,7 +463,7 @@ class RetailcrmJobManager $jobs[$name] = serialize($interval); } - return (string)base64_encode(json_encode($jobs)); + return (string) base64_encode(json_encode($jobs)); } /** @@ -472,7 +477,7 @@ class RetailcrmJobManager */ public static function setCurrentJob($job) { - return (bool)Configuration::updateGlobalValue(self::CURRENT_TASK, $job); + return (bool) Configuration::updateGlobalValue(self::CURRENT_TASK, $job); } /** @@ -482,7 +487,7 @@ class RetailcrmJobManager */ public static function getCurrentJob() { - return (string)Configuration::getGlobalValue(self::CURRENT_TASK); + return (string) Configuration::getGlobalValue(self::CURRENT_TASK); } /** @@ -494,7 +499,7 @@ class RetailcrmJobManager */ public static function clearCurrentJob($job) { - if (is_null($job) || self::getCurrentJob() == $job) { + if (null === $job || self::getCurrentJob() == $job) { return Configuration::deleteByName(self::CURRENT_TASK); } @@ -505,6 +510,7 @@ class RetailcrmJobManager * Resets JobManager internal state. Doesn't work if JobManager is active. * * @return bool + * * @throws \Exception */ public static function reset() @@ -536,7 +542,7 @@ class RetailcrmJobManager { $error = error_get_last(); - if(null !== $error && $error['type'] === E_ERROR) { + if (null !== $error && E_ERROR === $error['type']) { self::defaultShutdownHandler($error); } } @@ -547,7 +553,7 @@ class RetailcrmJobManager private static function registerShutdownHandler() { if (!self::$shutdownHandlerRegistered) { - register_shutdown_function(array('RetailcrmJobManager', 'shutdownHandlerWrapper')); + register_shutdown_function(['RetailcrmJobManager', 'shutdownHandlerWrapper']); self::$shutdownHandlerRegistered = true; } } @@ -560,16 +566,16 @@ class RetailcrmJobManager private static function defaultShutdownHandler($error) { if (is_callable(self::$customShutdownHandler)) { - call_user_func_array(self::$customShutdownHandler, array($error)); + call_user_func_array(self::$customShutdownHandler, [$error]); } else { if (null !== $error) { $job = self::getCurrentJob(); - if(!empty($job)) { + if (!empty($job)) { $lastRunsDetails = self::getLastRunDetails(); $lastRunsDetails[$job] = [ 'success' => false, - 'lastRun' => new \DateTime('now'), + 'lastRun' => new \DateTimeImmutable('now'), 'error' => [ 'message' => (isset($error['message']) ? $error['message'] : print_r($error, true)), 'trace' => print_r($error, true), @@ -607,17 +613,17 @@ class RetailcrmJobManager * @param string $msg * @param string $trace * @param string $currentJob - * @param array $jobs + * @param array $jobs */ - private static function handleError($file, $msg, $trace, $currentJob = '', $jobs = array()) + private static function handleError($file, $msg, $trace, $currentJob = '', $jobs = []) { - $data = array(); + $data = []; if (!empty($currentJob)) { $data[] = 'current job: ' . $currentJob; } - if (count($jobs) > 0) { + if (0 < count($jobs)) { $data[] = 'jobs list: ' . self::serializeJobs($jobs); } @@ -635,12 +641,13 @@ class RetailcrmJobManager * * @param string $jobName * @param string $phpScript - * @param bool $once - * @param bool $cliMode - * @param bool $force - * @param int $shopId + * @param bool $once + * @param bool $cliMode + * @param bool $force + * @param int $shopId * * @return bool + * * @throws \RetailcrmJobManagerException */ private static function execHere($jobName, $cliMode = false, $force = false, $shopId = null) @@ -650,8 +657,8 @@ class RetailcrmJobManager if (!$cliMode && !$force) { ignore_user_abort(true); - if (version_compare(phpversion(), '7.0.16', '>=') && - function_exists('fastcgi_finish_request') + if (version_compare(phpversion(), '7.0.16', '>=') + && function_exists('fastcgi_finish_request') ) { if (!headers_sent()) { header('Expires: Thu, 19 Nov 1981 08:52:00 GMT'); @@ -719,7 +726,7 @@ class RetailcrmJobManager $lastRuns = array_values(static::getLastRuns()); if (empty($lastRuns)) { - return \DateTime::createFromFormat('Y-m-d H:i:s', '1970-01-01 00:00:00'); + return \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '1970-01-01 00:00:00'); } usort( @@ -727,7 +734,7 @@ class RetailcrmJobManager function ($first, $second) { if ($first < $second) { return 1; - } else if ($first > $second) { + } elseif ($first > $second) { return -1; } else { return 0; @@ -742,11 +749,12 @@ class RetailcrmJobManager * Returns true if lock is present and it's not expired * * @return bool + * * @throws \Exception */ private static function isLocked() { - $inProcess = (bool)Configuration::getGlobalValue(self::IN_PROGRESS_NAME); + $inProcess = (bool) Configuration::getGlobalValue(self::IN_PROGRESS_NAME); $lastRan = static::getLastRun(); $lastRanSeconds = $lastRan->format('U'); @@ -764,6 +772,7 @@ class RetailcrmJobManager * Installs lock * * @return bool + * * @throws \Exception */ private static function lock() diff --git a/retailcrm/lib/RetailcrmJsonResponse.php b/retailcrm/lib/RetailcrmJsonResponse.php index 0758435..8699b8b 100644 --- a/retailcrm/lib/RetailcrmJsonResponse.php +++ b/retailcrm/lib/RetailcrmJsonResponse.php @@ -41,9 +41,11 @@ if (!defined('_PS_VERSION_')) { /** * Class RetailcrmLogger + * * @author DIGITAL RETAIL TECHNOLOGIES SL * @license GPL - * @link https://retailcrm.ru + * + * @see https://retailcrm.ru */ class RetailcrmJsonResponse { @@ -54,6 +56,7 @@ class RetailcrmJsonResponse $result = json_encode($response); echo $result; + return $result; } @@ -63,7 +66,7 @@ class RetailcrmJsonResponse return self::jsonResponse([ 'success' => false, - 'errorMsg' => $msg + 'errorMsg' => $msg, ]); } @@ -73,11 +76,12 @@ class RetailcrmJsonResponse 'success' => true, ]; - if (!is_null($data)) { + if (null !== $data) { if (is_array($key)) { foreach ($key as $i => $value) { - if (isset($data[$i])) + if (isset($data[$i])) { $response[$value] = $data[$i]; + } } } elseif (is_string($key)) { $response[$key] = $data; @@ -88,4 +92,4 @@ class RetailcrmJsonResponse return self::jsonResponse($response); } -} \ No newline at end of file +} diff --git a/retailcrm/lib/RetailcrmLogger.php b/retailcrm/lib/RetailcrmLogger.php index c389bb6..6aa01dd 100755 --- a/retailcrm/lib/RetailcrmLogger.php +++ b/retailcrm/lib/RetailcrmLogger.php @@ -41,9 +41,11 @@ if (!defined('_PS_VERSION_')) { /** * Class RetailcrmLogger + * * @author DIGITAL RETAIL TECHNOLOGIES SL * @license GPL - * @link https://retailcrm.ru + * + * @see https://retailcrm.ru */ class RetailcrmLogger { @@ -117,7 +119,7 @@ class RetailcrmLogger */ public static function output($message = '', $end = PHP_EOL) { - if (php_sapi_name() == 'cli') { + if ('cli' == php_sapi_name()) { echo $message . $end; } } @@ -158,7 +160,7 @@ class RetailcrmLogger /** * Debug log record with multiple entries * - * @param string $caller + * @param string $caller * @param array|string $messages */ public static function writeDebugArray($caller, $messages) @@ -170,6 +172,7 @@ class RetailcrmLogger $messages, function ($carry, $item) { $carry .= ' ' . print_r($item, true); + return $carry; } ), @@ -214,7 +217,7 @@ class RetailcrmLogger */ private static function getLogFilePrefix() { - if (php_sapi_name() == 'cli') { + if ('cli' == php_sapi_name()) { if (isset($_SERVER['TERM'])) { return 'cli'; } else { @@ -250,13 +253,13 @@ class RetailcrmLogger $logFiles = self::getLogFiles(); foreach ($logFiles as $logFile) { - $fileNames[] = [ - 'name' => basename($logFile), - 'path' => $logFile, - 'size' => number_format(filesize($logFile), 0, '.', ' ') . ' bytes', - 'modified' => date('Y-m-d H:i:s', filemtime($logFile)), - ]; - } + $fileNames[] = [ + 'name' => basename($logFile), + 'path' => $logFile, + 'size' => number_format(filesize($logFile), 0, '.', ' ') . ' bytes', + 'modified' => date('Y-m-d H:i:s', filemtime($logFile)), + ]; + } return $fileNames; } @@ -276,7 +279,7 @@ class RetailcrmLogger $handle = opendir($logDir); while (($file = readdir($handle)) !== false) { - if (self::checkFileName($file) !== false) { + if (false !== self::checkFileName($file)) { yield "$logDir/$file"; } } @@ -288,6 +291,7 @@ class RetailcrmLogger * Checks if given logs filename relates to the module * * @param string $file + * * @return false|string */ public static function checkFileName($file) @@ -322,4 +326,4 @@ class RetailcrmLogger return $reduced; } -} \ No newline at end of file +} diff --git a/retailcrm/lib/RetailcrmOrderBuilder.php b/retailcrm/lib/RetailcrmOrderBuilder.php index 3aa1f77..d2b29ba 100644 --- a/retailcrm/lib/RetailcrmOrderBuilder.php +++ b/retailcrm/lib/RetailcrmOrderBuilder.php @@ -39,27 +39,27 @@ class RetailcrmOrderBuilder { /** - * @var \RetailcrmApiClientV5 $api + * @var \RetailcrmApiClientV5 */ protected $api; /** - * @var int $default_lang + * @var int */ protected $default_lang; /** - * @var Order|OrderCore|null $cmsOrder + * @var Order|OrderCore|null */ protected $cmsOrder; /** - * @var Cart|CartCore|null $cmsCart + * @var Cart|CartCore|null */ protected $cmsCart; /** - * @var Customer|CustomerCore|null $cmsCustomer + * @var Customer|CustomerCore|null */ protected $cmsCustomer; @@ -74,17 +74,17 @@ class RetailcrmOrderBuilder protected $deliveryAddress; /** - * @var array|null $createdCustomer + * @var array|null */ protected $createdCustomer; /** - * @var array|null $corporateCompanyExtractCache + * @var array|null */ protected $corporateCompanyExtractCache; /** - * @var string $apiSite + * @var string */ protected $apiSite; @@ -93,7 +93,8 @@ class RetailcrmOrderBuilder */ public function defaultLangFromConfiguration() { - $this->default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + $this->default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); + return $this; } @@ -105,6 +106,7 @@ class RetailcrmOrderBuilder public function setDefaultLang($default_lang) { $this->default_lang = $default_lang; + return $this; } @@ -116,6 +118,7 @@ class RetailcrmOrderBuilder public function setApi($api) { $this->api = $api; + return $this; } @@ -129,15 +132,15 @@ class RetailcrmOrderBuilder $this->cmsOrder = $cmsOrder; if ($cmsOrder instanceof Order) { - if (is_null($this->cmsCustomer)) { + if (null === $this->cmsCustomer) { $this->cmsCustomer = $cmsOrder->getCustomer(); } - if (is_null($this->invoiceAddress)) { + if (null === $this->invoiceAddress) { $this->invoiceAddress = new Address($cmsOrder->id_address_invoice); } - if (is_null($this->deliveryAddress)) { + if (null === $this->deliveryAddress) { $this->deliveryAddress = new Address($cmsOrder->id_address_delivery); } } @@ -155,15 +158,15 @@ class RetailcrmOrderBuilder $this->cmsCart = $cmsCart; if ($cmsCart instanceof Cart) { - if (is_null($this->cmsCustomer) && !empty($cmsCart->id_customer)) { + if (null === $this->cmsCustomer && !empty($cmsCart->id_customer)) { $this->cmsCustomer = new Customer($cmsCart->id_customer); } - if (is_null($this->invoiceAddress) && !empty($cmsCart->id_address_invoice)) { + if (null === $this->invoiceAddress && !empty($cmsCart->id_address_invoice)) { $this->invoiceAddress = new Address($cmsCart->id_address_invoice); } - if (is_null($this->deliveryAddress) && !empty($cmsCart->id_address_delivery)) { + if (null === $this->deliveryAddress && !empty($cmsCart->id_address_delivery)) { $this->deliveryAddress = new Address($cmsCart->id_address_delivery); } } @@ -179,6 +182,7 @@ class RetailcrmOrderBuilder public function setCmsCustomer($cmsCustomer) { $this->cmsCustomer = $cmsCustomer; + return $this; } @@ -259,7 +263,7 @@ class RetailcrmOrderBuilder $createResponse = $this->api->customersCreate($crmCustomer); if (!$createResponse || !$createResponse->isSuccessful()) { - $this->createdCustomer = array(); + $this->createdCustomer = []; return false; } @@ -314,7 +318,8 @@ class RetailcrmOrderBuilder return $addressBuilder ->setAddress($this->invoiceAddress) ->build() - ->getDataArray(); + ->getDataArray() + ; } /** @@ -327,7 +332,7 @@ class RetailcrmOrderBuilder private function buildCorporateAddress($isMain = true) { if (empty($this->invoiceAddress) || empty($this->invoiceAddress->id)) { - return array(); + return []; } $addressBuilder = new RetailcrmAddressBuilder(); @@ -338,7 +343,8 @@ class RetailcrmOrderBuilder ->setIsMain($isMain) ->setWithExternalId(true) ->build() - ->getDataArray(); + ->getDataArray() + ; } /** @@ -365,15 +371,15 @@ class RetailcrmOrderBuilder } } - $company = array( + $company = [ 'isMain' => true, - 'name' => $companyName - ); + 'name' => $companyName, + ]; if (!empty($addressId)) { - $company['address'] = array( - 'id' => $addressId - ); + $company['address'] = [ + 'id' => $addressId, + ]; } if (!empty($vat)) { @@ -420,7 +426,7 @@ class RetailcrmOrderBuilder if ($corporateWasFound) { $contactList = $this->api->customersCorporateContacts( $crmCorporate['id'], - array('contactIds' => array($customer['id'])), + ['contactIds' => [$customer['id']]], null, null, 'id', @@ -431,14 +437,14 @@ class RetailcrmOrderBuilder return $crmCorporate; } - if (count($contactList['contacts']) == 0) { - $contactData = array( + if (0 == count($contactList['contacts'])) { + $contactData = [ 'isMain' => false, - 'customer' => array( + 'customer' => [ 'id' => $customer['id'], - 'site' => $this->getApiSite() - ) - ); + 'site' => $this->getApiSite(), + ], + ]; $crmCorporateCompany = $this->extractCorporateCompanyCached( $crmCorporate['id'], @@ -446,9 +452,9 @@ class RetailcrmOrderBuilder ); if (!empty($crmCorporateCompany) && isset($crmCorporateCompany['id'])) { - $contactData['companies'] = array(array( - 'company' => array('id' => $crmCorporateCompany['id']) - )); + $contactData['companies'] = [[ + 'company' => ['id' => $crmCorporateCompany['id']], + ]]; } $this->api->customersCorporateContactsCreate( @@ -528,17 +534,18 @@ class RetailcrmOrderBuilder $addresses = $request ->setApi($this->api) ->setMethod('customersCorporateAddresses') - ->setParams(array( + ->setParams([ $corporateId, - array(), + [], '{{page}}', '{{limit}}', 'id', - $this->getApiSite() - )) + $this->getApiSite(), + ]) ->setDataKey('addresses') ->execute() - ->getData(); + ->getData() + ; foreach ($addresses as $addressInCrm) { if (!empty($addressInCrm['externalId']) && $addressInCrm['externalId'] == $this->invoiceAddress->id) { @@ -574,7 +581,7 @@ class RetailcrmOrderBuilder if (empty($this->cmsCustomer->id) || $this->cmsCustomer->is_guest) { if (!empty($this->cmsCustomer->email)) { - $customers = $this->api->customersList(array('email' => $this->cmsCustomer->email)); + $customers = $this->api->customersList(['email' => $this->cmsCustomer->email]); if ($customers && $customers->isSuccessful() @@ -594,7 +601,7 @@ class RetailcrmOrderBuilder } } - return array(); + return []; } /** @@ -607,22 +614,22 @@ class RetailcrmOrderBuilder */ private function findCorporateCustomerByContactAndCompany($contactId, $companyName) { - $crmCorporate = $this->api->customersCorporateList(array( - 'contactIds' => array($contactId), - 'companyName' => $companyName - )); + $crmCorporate = $this->api->customersCorporateList([ + 'contactIds' => [$contactId], + 'companyName' => $companyName, + ]); if ($crmCorporate instanceof RetailcrmApiResponse && $crmCorporate->isSuccessful() && $crmCorporate->offsetExists('customersCorporate') - && count($crmCorporate['customersCorporate']) > 0 + && 0 < count($crmCorporate['customersCorporate']) ) { $crmCorporate = $crmCorporate['customersCorporate']; return reset($crmCorporate); } - return array(); + return []; } /** @@ -634,29 +641,29 @@ class RetailcrmOrderBuilder */ private function findCorporateCustomerByCompany($companyName) { - $crmCorporate = $this->api->customersCorporateList(array( - 'companyName' => $companyName - )); + $crmCorporate = $this->api->customersCorporateList([ + 'companyName' => $companyName, + ]); if ($crmCorporate instanceof RetailcrmApiResponse && $crmCorporate->isSuccessful() && $crmCorporate->offsetExists('customersCorporate') - && count($crmCorporate['customersCorporate']) > 0 + && 0 < count($crmCorporate['customersCorporate']) ) { $crmCorporate = $crmCorporate['customersCorporate']; return reset($crmCorporate); } - return array(); + return []; } /** * Get corporate companies, extract company data by provided identifiers * * @param int|string $corporateCrmId - * @param string $companyName - * @param string $by + * @param string $companyName + * @param string $by * * @return array */ @@ -664,7 +671,7 @@ class RetailcrmOrderBuilder { $companiesResponse = $this->api->customersCorporateCompanies( $corporateCrmId, - array(), + [], null, null, $by @@ -673,7 +680,7 @@ class RetailcrmOrderBuilder if ($companiesResponse instanceof RetailcrmApiResponse && $companiesResponse->isSuccessful() && $companiesResponse->offsetExists('companies') - && count($companiesResponse['companies']) > 0 + && 0 < count($companiesResponse['companies']) ) { $company = array_reduce( $companiesResponse['companies'], @@ -687,19 +694,19 @@ class RetailcrmOrderBuilder ); if (is_array($company)) { - return $company; + return $company; } } - return array(); + return []; } /** * extractCorporateCompany with cache * * @param int|string $corporateCrmId - * @param string $companyName - * @param string $by + * @param string $companyName + * @param string $by * * @return array */ @@ -708,7 +715,7 @@ class RetailcrmOrderBuilder $cachedItemId = sprintf('%s:%s', (string) $corporateCrmId, $companyName); if (!is_array($this->corporateCompanyExtractCache)) { - $this->corporateCompanyExtractCache = array(); + $this->corporateCompanyExtractCache = []; } if (!isset($this->corporateCompanyExtractCache[$cachedItemId])) { @@ -729,8 +736,8 @@ class RetailcrmOrderBuilder */ private function validateCmsCustomer() { - if (is_null($this->cmsCustomer)) { - throw new \InvalidArgumentException("RetailcrmOrderBuilder::cmsCustomer must be set"); + if (null === $this->cmsCustomer) { + throw new \InvalidArgumentException('RetailcrmOrderBuilder::cmsCustomer must be set'); } } @@ -744,7 +751,7 @@ class RetailcrmOrderBuilder $this->validateCmsCustomer(); if (empty($this->cmsCustomer->id)) { - throw new \InvalidArgumentException("RetailcrmOrderBuilder::cmsCustomer must be stored in DB"); + throw new \InvalidArgumentException('RetailcrmOrderBuilder::cmsCustomer must be stored in DB'); } } @@ -755,11 +762,11 @@ class RetailcrmOrderBuilder $contactPersonExternalId = ''; if (empty($customer)) { - return array(); + return []; } if (empty($this->cmsCustomer->id)) { - $contacts = $this->api->customersList(array('email' => $this->cmsCustomer->email)); + $contacts = $this->api->customersList(['email' => $this->cmsCustomer->email]); if ($contacts && $contacts->isSuccessful() @@ -776,7 +783,7 @@ class RetailcrmOrderBuilder } else { $contacts = $this->api->customersCorporateContacts( $customer['id'], - array('contactExternalIds' => array($this->cmsCustomer->id)), + ['contactExternalIds' => [$this->cmsCustomer->id]], null, null, 'id', @@ -786,7 +793,7 @@ class RetailcrmOrderBuilder if ($contacts && $contacts->isSuccessful() && $contacts->offsetExists('contacts') - && count($contacts['contacts']) == 1 + && 1 == count($contacts['contacts']) ) { $contactPersonExternalId = $this->cmsCustomer->id; } @@ -809,19 +816,20 @@ class RetailcrmOrderBuilder /** * Build array with order data for retailCRM from PrestaShop order data * - * @param Order|\OrderCore $order PrestaShop Order - * @param Customer|\CustomerCore|null $customer PrestaShop Customer - * @param Cart|\CartCore|null $orderCart Cart for provided order. Optional - * @param bool $isStatusExport Use status for export - * @param bool $preferCustomerAddress Use customer address even if delivery address is - * provided - * @param bool $dataFromCart Prefer data from cart - * @param string $contactPersonId Contact person id to append - * @param string $contactPersonExternalId Contact person externalId to append. - * @param string $customerId Customer id - * @param string $site Site code (for customer only) + * @param Order|\OrderCore $order PrestaShop Order + * @param Customer|\CustomerCore|null $customer PrestaShop Customer + * @param Cart|\CartCore|null $orderCart Cart for provided order. Optional + * @param bool $isStatusExport Use status for export + * @param bool $preferCustomerAddress Use customer address even if delivery address is + * provided + * @param bool $dataFromCart Prefer data from cart + * @param string $contactPersonId Contact person id to append + * @param string $contactPersonExternalId contact person externalId to append + * @param string $customerId Customer id + * @param string $site Site code (for customer only) + * + * @return array retailCRM order data * - * @return array retailCRM order data * @todo Refactor into OrderBuilder (current order builder should be divided into several independent builders). */ public static function buildCrmOrder( @@ -840,16 +848,16 @@ class RetailcrmOrderBuilder $delivery = json_decode(Configuration::get(RetailCRM::DELIVERY), true); $payment = json_decode(Configuration::get(RetailCRM::PAYMENT), true); $status = json_decode(Configuration::get(RetailCRM::STATUS), true); - $sendOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_SENDING)); + $sendOrderNumber = (bool) (Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_SENDING)); $orderNumber = $sendOrderNumber ? $order->reference : null; - if (Module::getInstanceByName('advancedcheckout') === false) { + if (false === Module::getInstanceByName('advancedcheckout')) { $paymentType = $order->module; } else { $paymentType = $order->payment; } - if ($order->current_state == 0) { + if (0 == $order->current_state) { $order_status = $statusExport; if (!$isStatusExport) { @@ -865,15 +873,15 @@ class RetailcrmOrderBuilder $cart = $orderCart; - if (is_null($cart)) { + if (null === $cart) { $cart = new Cart($order->getCartIdStatic($order->id)); } - if (is_null($customer)) { + if (null === $customer) { $customer = new Customer($order->id_customer); } - $crmOrder = array_filter(array( + $crmOrder = array_filter([ 'externalId' => $order->id, 'number' => $orderNumber, 'createdAt' => RetailcrmTools::verifyDate($order->date_add, 'Y-m-d H:i:s') @@ -882,13 +890,13 @@ class RetailcrmOrderBuilder 'firstName' => $customer->firstname, 'lastName' => $customer->lastname, 'email' => $customer->email, - )); + ]); $addressCollection = $cart->getAddressCollection(); $addressDelivery = new Address($order->id_address_delivery); $addressInvoice = new Address($order->id_address_invoice); - if (is_null($addressDelivery->id) || $preferCustomerAddress === true) { + if (null === $addressDelivery->id || true === $preferCustomerAddress) { $addressDelivery = array_filter( $addressCollection, function ($v) use ($customer) { @@ -896,7 +904,7 @@ class RetailcrmOrderBuilder } ); - if (is_array($addressDelivery) && count($addressDelivery) == 1) { + if (is_array($addressDelivery) && 1 == count($addressDelivery)) { $addressDelivery = reset($addressDelivery); } } @@ -905,7 +913,8 @@ class RetailcrmOrderBuilder $addressBuilder ->setMode(RetailcrmAddressBuilder::MODE_ORDER_DELIVERY) ->setAddress($addressDelivery) - ->build(); + ->build() + ; $crmOrder = array_merge($crmOrder, $addressBuilder->getDataArray()); if ($addressInvoice instanceof Address && !empty($addressInvoice->company)) { @@ -917,18 +926,18 @@ class RetailcrmOrderBuilder } if (isset($payment[$paymentType]) && !empty($payment[$paymentType])) { - $order_payment = array( + $order_payment = [ 'externalId' => $order->id . '#' . $order->reference, - 'type' => $payment[$paymentType] - ); + 'type' => $payment[$paymentType], + ]; - if (round($order->total_paid_real, 2) > 0) { + if (0 < round($order->total_paid_real, 2)) { $order_payment['amount'] = round($order->total_paid_real, 2); $order_payment['status'] = 'paid'; } $crmOrder['payments'][] = $order_payment; } else { - $crmOrder['payments'] = array(); + $crmOrder['payments'] = []; } $idCarrier = $dataFromCart ? $cart->id_carrier : $order->id_carrier; @@ -940,7 +949,7 @@ class RetailcrmOrderBuilder } else { $totalShipping = $dataFromCart ? $cart->getCarrierCost($idCarrier) : $order->total_shipping; - if (!empty($totalShipping) && $totalShipping != 0) { + if (!empty($totalShipping) && 0 != $totalShipping) { $totalShippingWithoutTax = $dataFromCart ? $totalShipping - $cart->getCarrierCost($idCarrier, false) : $order->total_shipping_tax_excl; @@ -954,20 +963,20 @@ class RetailcrmOrderBuilder $crmOrder['delivery']['code'] = $delivery[$idCarrier]; } - if(isset($totalShipping) && $order->total_discounts > $order->total_products_wt ) { - $totalShipping -= $order->total_discounts - $order->total_products_wt; + if (isset($totalShipping) && $order->total_discounts > $order->total_products_wt) { + $totalShipping -= $order->total_discounts - $order->total_products_wt; $crmOrder['discountManualAmount'] = round($order->total_products_wt, 2); } else { $crmOrder['discountManualAmount'] = round($order->total_discounts, 2); } - if (isset($totalShipping) && round($totalShipping, 2) > 0) { + if (isset($totalShipping) && 0 < round($totalShipping, 2)) { $crmOrder['delivery']['cost'] = round($totalShipping, 2); } else { $crmOrder['delivery']['cost'] = 0.00; } - if (isset($totalShippingWithoutTax) && round($totalShippingWithoutTax, 2) > 0) { + if (isset($totalShippingWithoutTax) && 0 < round($totalShippingWithoutTax, 2)) { $crmOrder['delivery']['netCost'] = round($totalShippingWithoutTax, 2); } else { $crmOrder['delivery']['netCost'] = 0.00; @@ -975,14 +984,14 @@ class RetailcrmOrderBuilder $comment = $order->getFirstMessage(); - if ($comment !== false) { + if (false !== $comment) { $crmOrder['customerComment'] = $comment; } if ($dataFromCart) { $productStore = $cart; $converter = function ($product) { - $map = array( + $map = [ 'product_attribute_id' => 'id_product_attribute', 'product_quantity' => 'cart_quantity', 'product_id' => 'id_product', @@ -990,8 +999,8 @@ class RetailcrmOrderBuilder 'product_name' => 'name', 'product_price' => 'price', 'purchase_supplier_price' => 'price', - 'product_price_wt' => 'price_wt' - ); + 'product_price_wt' => 'price_wt', + ]; foreach ($map as $target => $value) { if (isset($product[$value])) { @@ -1011,19 +1020,19 @@ class RetailcrmOrderBuilder foreach ($productStore->getProducts() as $productData) { $product = $converter($productData); - if (isset($product['product_attribute_id']) && $product['product_attribute_id'] > 0) { + if (isset($product['product_attribute_id']) && 0 < $product['product_attribute_id']) { $productId = $product['product_id'] . '#' . $product['product_attribute_id']; } else { $productId = $product['product_id']; } if (isset($product['attributes']) && $product['attributes']) { - $arProp = array(); + $arProp = []; $count = 0; - $arAttr = explode(",", $product['attributes']); + $arAttr = explode(',', $product['attributes']); foreach ($arAttr as $valAttr) { - $arItem = explode(":", $valAttr); + $arItem = explode(':', $valAttr); if ($arItem[0] && $arItem[1]) { // Product property code should start with a letter, digit or underscore @@ -1038,26 +1047,26 @@ class RetailcrmOrderBuilder $arProp[$count]['value'] = trim($arItem[1]); } - $count++; + ++$count; } } - $item = array( - "externalIds" => array( - array( + $item = [ + 'externalIds' => [ + [ 'code' => 'prestashop', - 'value' => $productId . "_" . $product['id_order_detail'], - ), - ), - 'offer' => array('externalId' => $productId), + 'value' => $productId . '_' . $product['id_order_detail'], + ], + ], + 'offer' => ['externalId' => $productId], 'productName' => $product['product_name'], 'quantity' => $product['product_quantity'], 'initialPrice' => round($product['product_price'], 2), /*'initialPrice' => !empty($item['rate']) ? $item['price'] + ($item['price'] * $item['rate'] / 100) : $item['price'],*/ - 'purchasePrice' => round($product['purchase_supplier_price'], 2) - ); + 'purchasePrice' => round($product['purchase_supplier_price'], 2), + ]; if (true == Configuration::get('PS_TAX') && isset($product['product_price_wt'])) { $item['initialPrice'] = round($product['product_price_wt'], 2); @@ -1070,7 +1079,7 @@ class RetailcrmOrderBuilder $crmOrder['items'][] = $item; } - if ($order->gift && $order->total_wrapping > 0) { + if ($order->gift && 0 < $order->total_wrapping) { self::setOrderGiftItem($order, $crmOrder); } @@ -1101,29 +1110,30 @@ class RetailcrmOrderBuilder return RetailcrmTools::filter( 'RetailcrmFilterProcessOrder', RetailcrmTools::clearArray($crmOrder), - array( + [ 'order' => $order, 'customer' => $customer, - 'cart' => $cart - )); + 'cart' => $cart, + ]); } /** * Build array with order data for retailCRM from PrestaShop cart data * * @param \RetailcrmProxy|\RetailcrmApiClientV5 $api - * @param Cart $cart Cart with data - * @param string $externalId External ID for order - * @param string $paymentType Payment type (buildCrmOrder requires it) - * @param string $status Status for order + * @param Cart $cart Cart with data + * @param string $externalId External ID for order + * @param string $paymentType Payment type (buildCrmOrder requires it) + * @param string $status Status for order * * @return array + * * @throws \Exception */ public static function buildCrmOrderFromCart($api, $cart = null, $externalId = '', $paymentType = '', $status = '') { if (empty($cart) || empty($paymentType) || empty($status)) { - return array(); + return []; } try { @@ -1134,7 +1144,7 @@ class RetailcrmOrderBuilder $order->id_address_invoice = $cart->id_address_invoice; $order->id_currency = $cart->id_currency; $order->id_carrier = $cart->id_carrier; - $order->total_discounts = $cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS);; + $order->total_discounts = $cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS); $order->module = $paymentType; $order->payment = $paymentType; @@ -1150,7 +1160,8 @@ class RetailcrmOrderBuilder ->setCmsOrder($order) ->setCmsCart($cart) ->setCmsCustomer(new Customer($cart->id_customer)) - ->buildOrderWithPreparedCustomer(true); + ->buildOrderWithPreparedCustomer(true) + ; $orderData['externalId'] = $externalId; $orderData['status'] = $status; @@ -1163,7 +1174,7 @@ class RetailcrmOrderBuilder $exception->getMessage() ); - return array(); + return []; } } @@ -1175,10 +1186,10 @@ class RetailcrmOrderBuilder * * @return array */ - public static function buildCrmCustomer(Customer $object, $address = array()) + public static function buildCrmCustomer(Customer $object, $address = []) { $customer = array_filter(array_merge( - array( + [ 'externalId' => !empty($object->id) ? $object->id : null, 'firstName' => $object->firstname, 'lastName' => $object->lastname, @@ -1188,20 +1199,20 @@ class RetailcrmOrderBuilder ? $object->date_add : date('Y-m-d H:i:s'), 'birthday' => RetailcrmTools::verifyDate($object->birthday, 'Y-m-d') ? $object->birthday : '', - 'sex' => $object->id_gender == "1" ? "male" : ($object->id_gender == "2" ? "female" : "") - ), + 'sex' => '1' == $object->id_gender ? 'male' : ('2' == $object->id_gender ? 'female' : ''), + ], $address ), function ($value) { - return !($value === '' || $value === null || (is_array($value) ? count($value) == 0 : false)); + return !('' === $value || null === $value || (is_array($value) ? 0 == count($value) : false)); }); return RetailcrmTools::filter( 'RetailcrmFilterProcessCustomer', $customer, - array( + [ 'customer' => $object, - 'address' => $address - )); + 'address' => $address, + ]); } public static function buildCrmCustomerCorporate( @@ -1212,18 +1223,18 @@ class RetailcrmOrderBuilder $appendCompany = false, $site = '' ) { - $customerAddresses = array(); - $addresses = $object->getAddresses((int)Configuration::get('PS_LANG_DEFAULT')); - $customer = array( - 'addresses' => array(), - 'companies' => array() - ); - $company = array( + $customerAddresses = []; + $addresses = $object->getAddresses((int) Configuration::get('PS_LANG_DEFAULT')); + $customer = [ + 'addresses' => [], + 'companies' => [], + ]; + $company = [ 'isMain' => true, 'externalId' => null, 'active' => true, - 'name' => '' - ); + 'name' => '', + ]; // TODO: $company['contragent']['INN'] may not work, should check that later... foreach ($addresses as $address) { @@ -1235,11 +1246,12 @@ class RetailcrmOrderBuilder ->setAddress($address) ->setWithExternalId(true) ->build() - ->getDataArray(); + ->getDataArray() + ; $customer['nickName'] = empty($nickName) ? $address->company : $nickName; $company['name'] = $address->company; $company['contragent']['INN'] = $address->vat_number; - $company['externalId'] = 'company_'.$address->id; + $company['externalId'] = 'company_' . $address->id; } if (is_array($address) && !empty($address['company'])) { @@ -1248,34 +1260,34 @@ class RetailcrmOrderBuilder ->setAddressId($address['id_address']) ->setWithExternalId(true) ->build() - ->getDataArray(); + ->getDataArray() + ; $customer['nickName'] = empty($nickName) ? $address->company : $nickName; $company['name'] = $address['company']; $company['contragent']['INN'] = $address['vat_number']; - $company['externalId'] = 'company_'.$address['id_address']; + $company['externalId'] = 'company_' . $address['id_address']; } } - if ($appendCompany && !is_null($company['externalId'])) { + if ($appendCompany && null !== $company['externalId']) { $customer['companies'][] = $company; } if (!empty($contactExternalId) && !empty($site)) { - $customer['customerContacts'] = array(array( + $customer['customerContacts'] = [[ 'isMain' => true, - 'customer' => array( + 'customer' => [ 'externalId' => $contactExternalId, - 'site' => $site - ) - )); + 'site' => $site, + ], + ]]; if (!empty($customer['companies']) - && isset($customer['companies'][0]) - && isset($customer['companies'][0]['externalId']) + && isset($customer['companies'][0], $customer['companies'][0]['externalId']) ) { - $customer['customerContacts'][0]['companies'] = array(array( - 'company' => array('externalId' => $customer['companies'][0]['externalId']) - )); + $customer['customerContacts'][0]['companies'] = [[ + 'company' => ['externalId' => $customer['companies'][0]['externalId']], + ]]; } } @@ -1286,9 +1298,9 @@ class RetailcrmOrderBuilder return RetailcrmTools::filter( 'RetailcrmFilterProcessCustomerCorporate', RetailcrmTools::clearArray($customer), - array( - 'customer' => $object - )); + [ + 'customer' => $object, + ]); } /** @@ -1300,17 +1312,16 @@ class RetailcrmOrderBuilder */ public static function isGiftItem($item) { - if (isset($item['offer']) - && isset($item['offer']['externalId']) - && $item['offer']['externalId'] == RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID + if (isset($item['offer'], $item['offer']['externalId']) + && RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID == $item['offer']['externalId'] ) { return true; } if (isset($item['externalIds'])) { foreach ($item['externalIds'] as $externalId) { - if ($externalId['code'] == 'prestashop' - && $externalId['value'] == RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID + if ('prestashop' == $externalId['code'] + && RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID == $externalId['value'] ) { return true; } @@ -1329,17 +1340,17 @@ class RetailcrmOrderBuilder */ public static function getGiftItem($giftItemPrice) { - return array( - 'externalIds' => array(array( + return [ + 'externalIds' => [[ 'code' => 'prestashop', - 'value' => RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID - )), - 'offer' => array('externalId' => RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID), + 'value' => RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID, + ]], + 'offer' => ['externalId' => RetailcrmReferences::GIFT_WRAPPING_ITEM_EXTERNAL_ID], 'productName' => 'Gift Wrapping Cost', 'quantity' => 1, 'initialPrice' => $giftItemPrice, - 'purchasePrice' => $giftItemPrice - ); + 'purchasePrice' => $giftItemPrice, + ]; } /** diff --git a/retailcrm/lib/RetailcrmPrestashopLoader.php b/retailcrm/lib/RetailcrmPrestashopLoader.php index c4e6ae0..882a236 100644 --- a/retailcrm/lib/RetailcrmPrestashopLoader.php +++ b/retailcrm/lib/RetailcrmPrestashopLoader.php @@ -37,6 +37,6 @@ */ $_SERVER['HTTPS'] = 1; -require_once(dirname(__FILE__) . '/../../../config/config.inc.php'); -require_once(dirname(__FILE__) . '/../../../init.php'); -require_once(dirname(__FILE__) . '/../bootstrap.php'); +require_once __DIR__ . '/../../../config/config.inc.php'; +require_once __DIR__ . '/../../../init.php'; +require_once __DIR__ . '/../bootstrap.php'; diff --git a/retailcrm/lib/RetailcrmReferences.php b/retailcrm/lib/RetailcrmReferences.php index a54120f..52fe77c 100644 --- a/retailcrm/lib/RetailcrmReferences.php +++ b/retailcrm/lib/RetailcrmReferences.php @@ -41,11 +41,11 @@ class RetailcrmReferences public $default_lang; public $carriers; - public $payment_modules = array(); + public $payment_modules = []; public $apiStatuses; /** - * @var bool|RetailcrmApiClientV5|RetailcrmProxy $api + * @var bool|RetailcrmApiClientV5|RetailcrmProxy */ private $api; @@ -65,23 +65,23 @@ class RetailcrmReferences public function getDeliveryTypes() { - $deliveryTypes = array(); + $deliveryTypes = []; $apiDeliveryTypes = $this->getApiDeliveryTypes(); if (!empty($this->carriers)) { foreach ($this->carriers as $carrier) { - $deliveryTypes[] = array( + $deliveryTypes[] = [ 'type' => 'select', 'label' => $carrier['name'], 'name' => 'RETAILCRM_API_DELIVERY[' . $carrier['id_carrier'] . ']', 'subname' => $carrier['id_carrier'], 'required' => false, - 'options' => array( + 'options' => [ 'query' => $apiDeliveryTypes, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } } @@ -90,26 +90,26 @@ class RetailcrmReferences public function getStatuses() { - $statusTypes = array(); + $statusTypes = []; $states = OrderState::getOrderStates($this->default_lang, true); $this->apiStatuses = $this->apiStatuses ?: $this->getApiStatuses(); if (!empty($states)) { foreach ($states as $state) { - if ($state['name'] != ' ') { + if (' ' != $state['name']) { $key = $state['id_order_state']; - $statusTypes[] = array( + $statusTypes[] = [ 'type' => 'select', 'label' => $state['name'], 'name' => "RETAILCRM_API_STATUS[$key]", 'subname' => $key, 'required' => false, - 'options' => array( + 'options' => [ 'query' => $this->apiStatuses, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } } } @@ -119,22 +119,22 @@ class RetailcrmReferences public function getOutOfStockStatuses($arParams) { - $statusTypes = array(); + $statusTypes = []; $this->apiStatuses = $this->apiStatuses ?: $this->getApiStatuses(); foreach ($arParams as $key => $state) { - $statusTypes[] = array( + $statusTypes[] = [ 'type' => 'select', 'label' => $state, 'name' => "RETAILCRM_API_OUT_OF_STOCK_STATUS[$key]", 'subname' => $key, 'required' => false, - 'options' => array( + 'options' => [ 'query' => $this->apiStatuses, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } return $statusTypes; @@ -143,23 +143,23 @@ class RetailcrmReferences public function getPaymentTypes() { $payments = $this->getSystemPaymentModules(); - $paymentTypes = array(); + $paymentTypes = []; $apiPaymentTypes = $this->getApiPaymentTypes(); if (!empty($payments)) { foreach ($payments as $payment) { - $paymentTypes[] = array( + $paymentTypes[] = [ 'type' => 'select', 'label' => $payment['name'], 'name' => 'RETAILCRM_API_PAYMENT[' . $payment['code'] . ']', 'subname' => $payment['code'], 'required' => false, - 'options' => array( + 'options' => [ 'query' => $apiPaymentTypes, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } } @@ -168,63 +168,61 @@ class RetailcrmReferences public function getPaymentAndDeliveryForDefault($arParams) { - $paymentTypes = array(); - $deliveryTypes = array(); + $paymentTypes = []; + $deliveryTypes = []; - $paymentDeliveryTypes = array(); + $paymentDeliveryTypes = []; if (!empty($this->carriers)) { - - $deliveryTypes[] = array( + $deliveryTypes[] = [ 'id_option' => '', 'name' => '', - ); + ]; foreach ($this->carriers as $valCarrier) { - $deliveryTypes[] = array( + $deliveryTypes[] = [ 'id_option' => $valCarrier['id_carrier'], 'name' => $valCarrier['name'], - ); + ]; } - $paymentDeliveryTypes[] = array( + $paymentDeliveryTypes[] = [ 'type' => 'select', 'label' => $arParams[0], 'name' => 'RETAILCRM_API_DELIVERY_DEFAULT', 'required' => false, - 'options' => array( - 'query' => $deliveryTypes, + 'options' => [ + 'query' => $deliveryTypes, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } $paymentModules = $this->getSystemPaymentModules(); if (!empty($paymentModules)) { - - $paymentTypes[] = array( + $paymentTypes[] = [ 'id_option' => '', 'name' => '', - ); + ]; foreach ($paymentModules as $valPayment) { - $paymentTypes[$valPayment['id']] = array( + $paymentTypes[$valPayment['id']] = [ 'id_option' => $valPayment['code'], 'name' => $valPayment['name'], - ); + ]; } - $paymentDeliveryTypes[] = array( + $paymentDeliveryTypes[] = [ 'type' => 'select', 'label' => $arParams[1], 'name' => 'RETAILCRM_API_PAYMENT_DEFAULT', 'required' => false, - 'options' => array( + 'options' => [ 'query' => $paymentTypes, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } return $paymentDeliveryTypes; @@ -239,46 +237,52 @@ class RetailcrmReferences */ $modules = RetailCRM::getCachedCmsModulesList(); $allPaymentModules = PaymentModule::getInstalledPaymentModules(); - $paymentModulesIds = array(); + $paymentModulesIds = []; foreach ($allPaymentModules as $module) { - $paymentModulesIds[] = $module['id_module']; + $paymentModulesIds[] = $module['id_module']; } foreach ($modules as $module) { - if ((!empty($module->parent_class) && $module->parent_class == 'PaymentModule') + if ((!empty($module->parent_class) && 'PaymentModule' == $module->parent_class) || in_array($module->id, $paymentModulesIds) ) { if ($module->id) { $module_id = (int) $module->id; - if (!get_class($module) == 'SimpleXMLElement') - $module->country = array(); + if ('SimpleXMLElement' == !get_class($module)) { + $module->country = []; + } $countries = DB::getInstance()->executeS('SELECT id_country FROM ' . _DB_PREFIX_ . 'module_country WHERE id_module = ' . pSQL($module_id) . ' AND `id_shop`=' . pSQL($shop_id)); - foreach ($countries as $country) + foreach ($countries as $country) { $module->country[] = $country['id_country']; - if (!get_class($module) == 'SimpleXMLElement') - $module->currency = array(); + } + if ('SimpleXMLElement' == !get_class($module)) { + $module->currency = []; + } $currencies = DB::getInstance()->executeS('SELECT id_currency FROM ' . _DB_PREFIX_ . 'module_currency WHERE id_module = ' . pSQL($module_id) . ' AND `id_shop`=' . pSQL($shop_id)); - foreach ($currencies as $currency) + foreach ($currencies as $currency) { $module->currency[] = $currency['id_currency']; - if (!get_class($module) == 'SimpleXMLElement') - $module->group = array(); + } + if ('SimpleXMLElement' == !get_class($module)) { + $module->group = []; + } $groups = DB::getInstance()->executeS('SELECT id_group FROM ' . _DB_PREFIX_ . 'module_group WHERE id_module = ' . pSQL($module_id) . ' AND `id_shop`=' . pSQL($shop_id)); - foreach ($groups as $group) + foreach ($groups as $group) { $module->group[] = $group['id_group']; + } } else { $module->country = null; $module->currency = null; $module->group = null; } - if ($module->active != 0 || $active === false) { - $this->payment_modules[] = array( + if (0 != $module->active || false === $active) { + $this->payment_modules[] = [ 'id' => $module->id, 'code' => $module->name, - 'name' => $module->displayName - ); + 'name' => $module->displayName, + ]; } } } @@ -293,23 +297,23 @@ class RetailcrmReferences public function getApiDeliveryTypes() { - $crmDeliveryTypes = array(); + $crmDeliveryTypes = []; $request = $this->api->deliveryTypesList(); if ($request) { - $crmDeliveryTypes[] = array( + $crmDeliveryTypes[] = [ 'id_option' => '', 'name' => '', - ); + ]; foreach ($request->deliveryTypes as $dType) { if (!$dType['active']) { continue; } - $crmDeliveryTypes[] = array( + $crmDeliveryTypes[] = [ 'id_option' => $dType['code'], 'name' => $dType['name'], - ); + ]; } } @@ -318,31 +322,31 @@ class RetailcrmReferences public function getApiStatuses() { - $crmStatusTypes = array(); + $crmStatusTypes = []; $request = $this->api->statusesList(); if ($request) { - $crmStatusTypes[] = array( + $crmStatusTypes[] = [ 'id_option' => '', 'name' => '', 'ordering' => '', - ); + ]; foreach ($request->statuses as $sType) { if (!$sType['active']) { continue; } - $crmStatusTypes[] = array( + $crmStatusTypes[] = [ 'id_option' => $sType['code'], 'name' => $sType['name'], 'ordering' => $sType['ordering'], - ); + ]; } usort($crmStatusTypes, function ($a, $b) { if ($a['ordering'] == $b['ordering']) { return 0; } else { - return ($a['ordering'] < $b['ordering'] ? -1 : 1); + return $a['ordering'] < $b['ordering'] ? -1 : 1; } }); } @@ -352,23 +356,23 @@ class RetailcrmReferences public function getApiPaymentTypes() { - $crmPaymentTypes = array(); + $crmPaymentTypes = []; $request = $this->api->paymentTypesList(); if ($request) { - $crmPaymentTypes[] = array( + $crmPaymentTypes[] = [ 'id_option' => '', 'name' => '', - ); + ]; foreach ($request->paymentTypes as $pType) { if (!$pType['active']) { continue; } - $crmPaymentTypes[] = array( + $crmPaymentTypes[] = [ 'id_option' => $pType['code'], - 'name' => $pType['name'] - ); + 'name' => $pType['name'], + ]; } } @@ -381,8 +385,8 @@ class RetailcrmReferences $response = $this->api->credentials(); if (!($response instanceof RetailcrmApiResponse) || !$response->isSuccessful() - || $response['siteAccess'] !== 'access_selective' - || count($response['sitesAvailable']) !== 1 + || 'access_selective' !== $response['siteAccess'] + || 1 !== count($response['sitesAvailable']) || !in_array('/api/reference/sites', $response['credentials']) || !in_array('/api/reference/sites/{code}/edit', $response['credentials']) ) { @@ -401,7 +405,6 @@ class RetailcrmReferences if ($response instanceof RetailcrmApiResponse && $response->isSuccessful() && $response->offsetExists('sites') && $response['sites']) { - return current($response['sites']); } } catch (Exception $e) { @@ -423,16 +426,16 @@ class RetailcrmReferences $retailcrmStores = $this->getApiStores(); foreach ($storesShop as $key => $storeShop) { - $stores[] = array( + $stores[] = [ 'type' => 'select', - 'name' => 'RETAILCRM_STORES['. $key .']', + 'name' => 'RETAILCRM_STORES[' . $key . ']', 'label' => $storeShop, - 'options' => array( + 'options' => [ 'query' => $retailcrmStores, 'id' => 'id_option', - 'name' => 'name' - ) - ); + 'name' => 'name', + ], + ]; } return $stores; @@ -440,7 +443,7 @@ class RetailcrmReferences protected function getShopStores() { - $stores = array(); + $stores = []; $warehouses = Warehouse::getWarehouses(); foreach ($warehouses as $warehouse) { @@ -454,20 +457,20 @@ class RetailcrmReferences protected function getApiStores() { - $crmStores = array(); + $crmStores = []; $response = $this->api->storesList(); if ($response) { - $crmStores[] = array( + $crmStores[] = [ 'id_option' => '', - 'name' => '' - ); + 'name' => '', + ]; foreach ($response->stores as $store) { - $crmStores[] = array( + $crmStores[] = [ 'id_option' => $store['code'], - 'name' => $store['name'] - ); + 'name' => $store['name'], + ]; } } diff --git a/retailcrm/lib/RetailcrmTools.php b/retailcrm/lib/RetailcrmTools.php index 324c26a..3529a51 100644 --- a/retailcrm/lib/RetailcrmTools.php +++ b/retailcrm/lib/RetailcrmTools.php @@ -64,7 +64,7 @@ class RetailcrmTools */ public static function isCorporateEnabled() { - return (bool)Configuration::get(RetailCRM::ENABLE_CORPORATE_CLIENTS); + return (bool) Configuration::get(RetailCRM::ENABLE_CORPORATE_CLIENTS); } /** @@ -76,7 +76,7 @@ class RetailcrmTools */ public static function isCustomerCorporate($customer) { - $addresses = $customer->getAddresses((int)Configuration::get('PS_LANG_DEFAULT')); + $addresses = $customer->getAddresses((int) Configuration::get('PS_LANG_DEFAULT')); foreach ($addresses as $address) { if (($address instanceof Address && !empty($address->company)) @@ -116,7 +116,7 @@ class RetailcrmTools */ public static function isCrmOrderCorporate($order) { - return isset($order['customer']['type']) && $order['customer']['type'] == 'customer_corporate'; + return isset($order['customer']['type']) && 'customer_corporate' == $order['customer']['type']; } /** @@ -130,7 +130,7 @@ class RetailcrmTools { if (!empty($customer->id)) { foreach ($customer->getAddresses(self::defaultLang()) as $addressArray) { - if ($addressArray['alias'] == 'default') { + if ('default' == $addressArray['alias']) { return (int) $addressArray['id_address']; } } @@ -147,9 +147,9 @@ class RetailcrmTools * * @return bool */ - public static function verifyDate($date, $format = "Y-m-d") + public static function verifyDate($date, $format = 'Y-m-d') { - return $date !== "0000-00-00" && (bool)date_create_from_format($format, $date); + return '0000-00-00' !== $date && (bool) date_create_immutable_from_format($format, $date); } /** @@ -163,7 +163,7 @@ class RetailcrmTools { $ids = explode(',', $ids); - $ranges = array(); + $ranges = []; foreach ($ids as $idx => $uid) { if (strpos($uid, '-')) { @@ -182,18 +182,20 @@ class RetailcrmTools /** * @param ObjectModel $object * @param ObjectModel|null $relatedObject + * * @return bool + * * @throws PrestaShopException */ public static function validateEntity($object, $relatedObject = null) { $validate = $object->validateFields(false, true); - if ($validate === true) { + if (true === $validate) { return true; } $msg = ''; - if ($relatedObject !== null) { + if (null !== $relatedObject) { $msg = sprintf('for %s with id %s', get_class($relatedObject), $relatedObject->id @@ -224,10 +226,11 @@ class RetailcrmTools if (!is_object($object)) { ob_start(); var_dump($object); - return (string)ob_get_clean(); + + return (string) ob_get_clean(); } - $data = array(); + $data = []; $type = get_class($object); if (property_exists($type, 'definition')) { @@ -243,7 +246,6 @@ class RetailcrmTools $data[$field] = $object->$field; } } - } } @@ -253,27 +255,28 @@ class RetailcrmTools /** * Converts CMS address to CRM address * - * @param $address + * @param $address * @param array $customer * @param array $order + * * @deprecated Replaced with RetailcrmAddressBuilder * * @return array */ - public static function addressParse($address, &$customer = array(), &$order = array()) + public static function addressParse($address, &$customer = [], &$order = []) { if (!isset($customer)) { - $customer = array(); + $customer = []; } if (!isset($order)) { - $order = array(); + $order = []; } if ($address instanceof Address) { $postcode = $address->postcode; $city = $address->city; - $addres_line = sprintf("%s %s", $address->address1, $address->address2); + $addres_line = sprintf('%s %s', $address->address1, $address->address2); $countryIso = Country::getIsoById($address->id_country); $vat = $address->vat_number; } @@ -302,31 +305,31 @@ class RetailcrmTools $order = array_merge($order, $phones['order']); $customer = array_merge($customer, $phones['customer']); - return array( + return [ 'order' => RetailcrmTools::clearArray($order), 'customer' => RetailcrmTools::clearArray($customer), - 'vat' => isset($vat) && !empty($vat) ? $vat : '' - ); + 'vat' => isset($vat) && !empty($vat) ? $vat : '', + ]; } - public static function getPhone($address, &$customer = array(), &$order = array()) + public static function getPhone($address, &$customer = [], &$order = []) { if (!isset($customer)) { - $customer = array(); + $customer = []; } if (!isset($order)) { - $order = array(); + $order = []; } if (!empty($address->phone_mobile)) { $order['phone'] = $address->phone_mobile; - $customer['phones'][] = array('number'=> $address->phone_mobile); + $customer['phones'][] = ['number' => $address->phone_mobile]; } if (!empty($address->phone)) { $order['additionalPhone'] = $address->phone; - $customer['phones'][] = array('number'=> $address->phone); + $customer['phones'][] = ['number' => $address->phone]; } if (!isset($order['phone']) && !empty($order['additionalPhone'])) { @@ -334,7 +337,7 @@ class RetailcrmTools unset($order['additionalPhone']); } - $phonesArray = array('customer' => $customer, 'order' => $order); + $phonesArray = ['customer' => $customer, 'order' => $order]; return $phonesArray; } @@ -368,8 +371,8 @@ class RetailcrmTools public static function explodeFIO($string) { - $result = array(); - $parse = (!$string) ? false : explode(" ", $string, 3); + $result = []; + $parse = (!$string) ? false : explode(' ', $string, 3); switch (count($parse)) { case 1: @@ -410,6 +413,7 @@ class RetailcrmTools * @param callable|null $filterFunc * * @return array + * * @todo Don't filter out false & all methods MUST NOT use false as blank value. */ public static function clearArray(array $arr, $filterFunc = null) @@ -418,16 +422,16 @@ class RetailcrmTools return $arr; } - $result = array(); + $result = []; foreach ($arr as $index => $node) { $result[$index] = (is_array($node)) ? self::clearArray($node) : $node; - if ($result[$index] === '' - || $result[$index] === null - || (is_array($result[$index]) && count($result[$index]) < 1) + if ('' === $result[$index] + || null === $result[$index] + || (is_array($result[$index]) && 1 > count($result[$index])) ) { unset($result[$index]); } @@ -438,7 +442,7 @@ class RetailcrmTools } return array_filter($result, function ($value) { - return !is_null($value); + return null !== $value; }); } @@ -499,8 +503,8 @@ class RetailcrmTools */ public static function mergeCustomerAddress($customer, $address) { - $customerPhones = isset($customer['phones']) ? $customer['phones'] : array(); - $addressPhones = isset($address['phones']) ? $address['phones'] : array(); + $customerPhones = isset($customer['phones']) ? $customer['phones'] : []; + $addressPhones = isset($address['phones']) ? $address['phones'] : []; $squashedCustomerPhones = array_filter(array_map(function ($val) { return isset($val['number']) ? $val['number'] : null; }, $customerPhones)); @@ -515,19 +519,21 @@ class RetailcrmTools } } - return array_merge($customer, $address, array('phones' => $customerPhones)); + return array_merge($customer, $address, ['phones' => $customerPhones]); } /** * Compare 'address' and 'phones' fields from crm customer info arrays + * * @param $customer1 * @param $customer2 + * * @return bool true if addresses are equal, false otherwise */ public static function isEqualCustomerAddress($customer1, $customer2) { - $customer1Phones = isset($customer1['phones']) ? $customer1['phones'] : array(); - $customer2Phones = isset($customer2['phones']) ? $customer2['phones'] : array(); + $customer1Phones = isset($customer1['phones']) ? $customer1['phones'] : []; + $customer2Phones = isset($customer2['phones']) ? $customer2['phones'] : []; $squashedCustomer1Phones = array_filter(array_map(function ($val) { return isset($val['number']) ? $val['number'] : null; @@ -542,8 +548,8 @@ class RetailcrmTools return false; } - $customer1Address = isset($customer1['address']) ? $customer1['address'] : array(); - $customer2Address = isset($customer2['address']) ? $customer2['address'] : array(); + $customer1Address = isset($customer1['address']) ? $customer1['address'] : []; + $customer2Address = isset($customer2['address']) ? $customer2['address'] : []; if (isset($customer1Address['id'])) { unset($customer1Address['id']); @@ -573,7 +579,7 @@ class RetailcrmTools if (function_exists('http_response_code')) { $code = http_response_code($code); } else { - if ($code !== NULL) { + if (null !== $code) { switch ($code) { case 100: $text = 'Continue'; break; case 101: $text = 'Switching Protocols'; break; @@ -638,7 +644,7 @@ class RetailcrmTools */ public static function isCustomerChangedToRegular($assembledOrder) { - return isset($assembledOrder['contragentType']) && $assembledOrder['contragentType'] == 'individual'; + return isset($assembledOrder['contragentType']) && 'individual' == $assembledOrder['contragentType']; } /** @@ -651,7 +657,7 @@ class RetailcrmTools */ public static function isCustomerChangedToLegal($assembledOrder) { - return isset($assembledOrder['contragentType']) && $assembledOrder['contragentType'] == 'legal-entity'; + return isset($assembledOrder['contragentType']) && 'legal-entity' == $assembledOrder['contragentType']; } /** @@ -682,13 +688,13 @@ class RetailcrmTools * (it will be set to id from provided customer, even if it doesn't have ID yet). * * @param Customer|CustomerCore $customer - * @param Address|\AddressCore $address + * @param Address|\AddressCore $address */ public static function assignAddressIdsByFields($customer, $address) { RetailcrmLogger::writeDebugArray( __METHOD__, - array('Called with customer', $customer->id, 'and address', self::dumpEntity($address)) + ['Called with customer', $customer->id, 'and address', self::dumpEntity($address)] ); foreach ($customer->getAddresses(self::defaultLang()) as $customerInnerAddress) { @@ -711,13 +717,13 @@ class RetailcrmTools */ public static function startJobManager() { - $intervals = array( + $intervals = [ 'RetailcrmClearLogsEvent' => new \DateInterval('P1D'), 'RetailcrmIcmlEvent' => new \DateInterval('PT4H'), 'RetailcrmInventoriesEvent' => new \DateInterval('PT15M'), 'RetailcrmSyncEvent' => new \DateInterval('PT7M'), - 'RetailcrmAbandonedCartsEvent' => new \DateInterval('PT1M') - ); + 'RetailcrmAbandonedCartsEvent' => new \DateInterval('PT1M'), + ]; RetailcrmJobManager::startJobs(self::filter( 'RetailcrmFilterJobManagerIntervals', @@ -735,7 +741,7 @@ class RetailcrmTools */ protected static function isAddressesEqualByFields($first, $second) { - $checkMapping = array( + $checkMapping = [ 'alias', 'id_country', 'lastname', @@ -748,21 +754,21 @@ class RetailcrmTools 'other', 'phone', 'company', - 'vat_number' - ); + 'vat_number', + ]; foreach ($checkMapping as $field) { if ($first->$field != $second->$field) { - RetailcrmLogger::writeDebug(__METHOD__, json_encode(array( - 'first' => array( + RetailcrmLogger::writeDebug(__METHOD__, json_encode([ + 'first' => [ 'id' => $first->id, - $field => $first->$field - ), - 'second' => array( + $field => $first->$field, + ], + 'second' => [ 'id' => $second->id, - $field => $second->$field - ), - ))); + $field => $second->$field, + ], + ])); return false; } @@ -780,7 +786,7 @@ class RetailcrmTools * * @return false|mixed */ - public static function filter($filter, $object, $parameters = array()) + public static function filter($filter, $object, $parameters = []) { if (!class_exists($filter)) { return $object; @@ -798,8 +804,8 @@ class RetailcrmTools try { RetailcrmLogger::writeDebug($filter . '::before', print_r(self::dumpEntity($object), true)); $result = call_user_func_array( - array($filter, 'filter'), - array($object, $parameters) + [$filter, 'filter'], + [$object, $parameters] ); RetailcrmLogger::writeDebug($filter . '::after', print_r(self::dumpEntity($result), true)); @@ -814,6 +820,7 @@ class RetailcrmTools /** * @param $name + * * @return array|false|mixed */ public static function getConfigurationByName($name) @@ -836,12 +843,13 @@ class RetailcrmTools try { return current(Db::getInstance()->executeS($sql)); } catch (PrestaShopDatabaseException $e) { - return array(); + return []; } } /** * @param $name + * * @return DateTime|false */ public static function getConfigurationCreatedAtByName($name) @@ -852,6 +860,6 @@ class RetailcrmTools return false; } - return DateTime::createFromFormat('Y-m-d H:i:s', $config['date_add']); + return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $config['date_add']); } } diff --git a/retailcrm/lib/api/RetailcrmApiClientV5.php b/retailcrm/lib/api/RetailcrmApiClientV5.php index eb67088..da6c0dd 100644 --- a/retailcrm/lib/api/RetailcrmApiClientV5.php +++ b/retailcrm/lib/api/RetailcrmApiClientV5.php @@ -55,9 +55,9 @@ class RetailcrmApiClientV5 /** * Client creating * - * @param string $url api url + * @param string $url api url * @param string $apiKey api key - * @param string $site site code + * @param string $site site code * * @throws \InvalidArgumentException * @@ -73,9 +73,9 @@ class RetailcrmApiClientV5 $url = $url . 'api/' . self::VERSION; - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->client = new RetailcrmHttpClient($url, ['apiKey' => $apiKey]); $this->apiKey = $apiKey; - $this->unversionedClient = new RetailcrmHttpClient($unversionedUrl, array('apiKey' => $apiKey)); + $this->unversionedClient = new RetailcrmHttpClient($unversionedUrl, ['apiKey' => $apiKey]); $this->siteCode = $site; } @@ -91,6 +91,7 @@ class RetailcrmApiClientV5 /** * @return RetailcrmApiResponse + * * @throws CurlException * @throws InvalidArgumentException * @throws InvalidJsonException @@ -104,8 +105,8 @@ class RetailcrmApiClientV5 * Returns users list * * @param array $filter - * @param null $page - * @param null $limit + * @param null $page + * @param null $limit * * @throws \RetailCrm\Exception\InvalidJsonException * @throws \RetailCrm\Exception\CurlException @@ -113,9 +114,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function usersList(array $filter = array(), $page = null, $limit = null) + public function usersList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -137,7 +138,7 @@ class RetailcrmApiClientV5 /** * Returns user data * - * @param integer $id user ID + * @param int $id user ID * * @throws \RetailCrm\Exception\InvalidJsonException * @throws \RetailCrm\Exception\CurlException @@ -153,14 +154,14 @@ class RetailcrmApiClientV5 /** * Change user status * - * @param integer $id user ID - * @param string $status user status + * @param int $id user ID + * @param string $status user status * * @return RetailcrmApiResponse */ public function usersStatus($id, $status) { - $statuses = array("free", "busy", "dinner", "break"); + $statuses = ['free', 'busy', 'dinner', 'break']; if (empty($status) || !in_array($status, $statuses)) { throw new \InvalidArgumentException( @@ -171,7 +172,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/users/$id/status", RetailcrmHttpClient::METHOD_POST, - array('status' => $status) + ['status' => $status] ); } @@ -179,14 +180,14 @@ class RetailcrmApiClientV5 * Get segments list * * @param array $filter - * @param null $limit - * @param null $page + * @param null $limit + * @param null $page * * @return RetailcrmApiResponse */ - public function segmentsList(array $filter = array(), $limit = null, $page = null) + public function segmentsList(array $filter = [], $limit = null, $page = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -209,14 +210,14 @@ class RetailcrmApiClientV5 * Get custom fields list * * @param array $filter - * @param null $limit - * @param null $page + * @param null $limit + * @param null $page * * @return RetailcrmApiResponse */ - public function customFieldsList(array $filter = array(), $limit = null, $page = null) + public function customFieldsList(array $filter = [], $limit = null, $page = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -245,17 +246,17 @@ class RetailcrmApiClientV5 */ public function customFieldsCreate($entity, $customField) { - if (!count($customField) || - empty($customField['code']) || - empty($customField['name']) || - empty($customField['type']) + if (!count($customField) + || empty($customField['code']) + || empty($customField['name']) + || empty($customField['type']) ) { throw new \InvalidArgumentException( 'Parameter `customField` must contain a data & fields `code`, `name` & `type` must be set' ); } - if (empty($entity) || $entity != 'customer' || $entity != 'order') { + if (empty($entity) || 'customer' != $entity || 'order' != $entity) { throw new \InvalidArgumentException( 'Parameter `entity` must contain a data & value must be `order` or `customer`' ); @@ -264,7 +265,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/custom-fields/$entity/create", RetailcrmHttpClient::METHOD_POST, - array('customField' => json_encode($customField)) + ['customField' => json_encode($customField)] ); } @@ -284,7 +285,7 @@ class RetailcrmApiClientV5 ); } - if (empty($entity) || $entity != 'customer' || $entity != 'order') { + if (empty($entity) || 'customer' != $entity || 'order' != $entity) { throw new \InvalidArgumentException( 'Parameter `entity` must contain a data & value must be `order` or `customer`' ); @@ -293,7 +294,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/custom-fields/$entity/edit/{$customField['code']}", RetailcrmHttpClient::METHOD_POST, - array('customField' => json_encode($customField)) + ['customField' => json_encode($customField)] ); } @@ -313,7 +314,7 @@ class RetailcrmApiClientV5 ); } - if (empty($entity) || $entity != 'customer' || $entity != 'order') { + if (empty($entity) || 'customer' != $entity || 'order' != $entity) { throw new \InvalidArgumentException( 'Parameter `entity` must contain a data & value must be `order` or `customer`' ); @@ -329,14 +330,14 @@ class RetailcrmApiClientV5 * Get custom dictionaries list * * @param array $filter - * @param null $limit - * @param null $page + * @param null $limit + * @param null $page * * @return RetailcrmApiResponse */ - public function customDictionariesList(array $filter = array(), $limit = null, $page = null) + public function customDictionariesList(array $filter = [], $limit = null, $page = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -364,9 +365,9 @@ class RetailcrmApiClientV5 */ public function customDictionariesCreate($customDictionary) { - if (!count($customDictionary) || - empty($customDictionary['code']) || - empty($customDictionary['elements']) + if (!count($customDictionary) + || empty($customDictionary['code']) + || empty($customDictionary['elements']) ) { throw new \InvalidArgumentException( 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' @@ -376,7 +377,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/custom-fields/dictionaries/{$customDictionary['code']}/create", RetailcrmHttpClient::METHOD_POST, - array('customDictionary' => json_encode($customDictionary)) + ['customDictionary' => json_encode($customDictionary)] ); } @@ -389,9 +390,9 @@ class RetailcrmApiClientV5 */ public function customDictionariesEdit($customDictionary) { - if (!count($customDictionary) || - empty($customDictionary['code']) || - empty($customDictionary['elements']) + if (!count($customDictionary) + || empty($customDictionary['code']) + || empty($customDictionary['elements']) ) { throw new \InvalidArgumentException( 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' @@ -401,7 +402,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/custom-fields/dictionaries/{$customDictionary['code']}/edit", RetailcrmHttpClient::METHOD_POST, - array('customDictionary' => json_encode($customDictionary)) + ['customDictionary' => json_encode($customDictionary)] ); } @@ -430,8 +431,8 @@ class RetailcrmApiClientV5 * Returns filtered orders list * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -439,9 +440,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function ordersList(array $filter = array(), $page = null, $limit = null) + public function ordersList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -463,8 +464,8 @@ class RetailcrmApiClientV5 /** * Create a order * - * @param array $order order data - * @param string $site (default: null) + * @param array $order order data + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -483,7 +484,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/orders/create', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('order' => json_encode($order))) + $this->fillSite($site, ['order' => json_encode($order)]) ); } @@ -500,7 +501,7 @@ class RetailcrmApiClientV5 */ public function ordersFixExternalIds(array $ids) { - if (! count($ids)) { + if (!count($ids)) { throw new \InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); @@ -509,15 +510,15 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/orders/fix-external-ids', RetailcrmHttpClient::METHOD_POST, - array('orders' => json_encode($ids) - ) + ['orders' => json_encode($ids), + ] ); } /** * Returns statuses of the orders * - * @param array $ids (default: array()) + * @param array $ids (default: array()) * @param array $externalIds (default: array()) * * @throws \InvalidArgumentException @@ -526,9 +527,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function ordersStatuses(array $ids = array(), array $externalIds = array()) + public function ordersStatuses(array $ids = [], array $externalIds = []) { - $parameters = array(); + $parameters = []; if (count($ids)) { $parameters['ids'] = $ids; @@ -547,8 +548,8 @@ class RetailcrmApiClientV5 /** * Upload array of the orders * - * @param array $orders array of orders - * @param string $site (default: null) + * @param array $orders array of orders + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -567,15 +568,15 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/orders/upload', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('orders' => json_encode($orders))) + $this->fillSite($site, ['orders' => json_encode($orders)]) ); } /** * Get order by id or externalId * - * @param string $id order identificator - * @param string $by (default: 'externalId') + * @param string $id order identificator + * @param string $by (default: 'externalId') * @param string $site (default: null) * * @throws \InvalidArgumentException @@ -591,16 +592,16 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/orders/$id", RetailcrmHttpClient::METHOD_GET, - $this->fillSite($site, array('by' => $by)) + $this->fillSite($site, ['by' => $by]) ); } /** * Edit a order * - * @param array $order order data - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param array $order order data + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -629,22 +630,23 @@ class RetailcrmApiClientV5 RetailcrmHttpClient::METHOD_POST, $this->fillSite( $site, - array('order' => json_encode($order), 'by' => $by) + ['order' => json_encode($order), 'by' => $by] ) ); } /** * Get orders history + * * @param array $filter * @param null $page * @param null $limit * * @return RetailcrmApiResponse */ - public function ordersHistory(array $filter = array(), $page = null, $limit = null) + public function ordersHistory(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -667,14 +669,14 @@ class RetailcrmApiClientV5 * Combine orders * * @param string $technique - * @param array $order - * @param array $resultOrder + * @param array $order + * @param array $resultOrder * * @return RetailcrmApiResponse */ public function ordersCombine($order, $resultOrder, $technique = 'ours') { - $techniques = array('ours', 'summ', 'theirs'); + $techniques = ['ours', 'summ', 'theirs']; if (!count($order) || !count($resultOrder)) { throw new \InvalidArgumentException( @@ -691,11 +693,11 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/orders/combine', RetailcrmHttpClient::METHOD_POST, - array( + [ 'technique' => $technique, 'order' => json_encode($order), - 'resultOrder' => json_encode($resultOrder) - ) + 'resultOrder' => json_encode($resultOrder), + ] ); } @@ -721,16 +723,16 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/orders/payments/create', RetailcrmHttpClient::METHOD_POST, - array('payment' => json_encode($payment)) + ['payment' => json_encode($payment)] ); } /** * Edit an order payment * - * @param array $payment order data - * @param string $by by key - * @param null $site site code + * @param array $payment order data + * @param string $by by key + * @param null $site site code * * @return RetailcrmApiResponse */ @@ -755,7 +757,7 @@ class RetailcrmApiClientV5 RetailcrmHttpClient::METHOD_POST, $this->fillSite( $site, - array('payment' => json_encode($payment), 'by' => $by) + ['payment' => json_encode($payment), 'by' => $by] ) ); } @@ -785,8 +787,8 @@ class RetailcrmApiClientV5 * Returns filtered customers list * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -794,9 +796,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function customersList(array $filter = array(), $page = null, $limit = null) + public function customersList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -818,8 +820,8 @@ class RetailcrmApiClientV5 /** * Create a customer * - * @param array $customer customer data - * @param string $site (default: null) + * @param array $customer customer data + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -829,7 +831,7 @@ class RetailcrmApiClientV5 */ public function customersCreate(array $customer, $site = null) { - if (! count($customer)) { + if (!count($customer)) { throw new \InvalidArgumentException( 'Parameter `customer` must contains a data' ); @@ -838,7 +840,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/customers/create', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('customer' => json_encode($customer))) + $this->fillSite($site, ['customer' => json_encode($customer)]) ); } @@ -855,7 +857,7 @@ class RetailcrmApiClientV5 */ public function customersFixExternalIds(array $ids) { - if (! count($ids)) { + if (!count($ids)) { throw new \InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); @@ -864,15 +866,15 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/customers/fix-external-ids', RetailcrmHttpClient::METHOD_POST, - array('customers' => json_encode($ids)) + ['customers' => json_encode($ids)] ); } /** * Upload array of the customers * - * @param array $customers array of customers - * @param string $site (default: null) + * @param array $customers array of customers + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -882,7 +884,7 @@ class RetailcrmApiClientV5 */ public function customersUpload(array $customers, $site = null) { - if (! count($customers)) { + if (!count($customers)) { throw new \InvalidArgumentException( 'Parameter `customers` must contains array of the customers' ); @@ -891,15 +893,15 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/customers/upload', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('customers' => json_encode($customers))) + $this->fillSite($site, ['customers' => json_encode($customers)]) ); } /** * Get customer by id or externalId * - * @param string $id customer identificator - * @param string $by (default: 'externalId') + * @param string $id customer identificator + * @param string $by (default: 'externalId') * @param string $site (default: null) * * @throws \InvalidArgumentException @@ -915,16 +917,16 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/customers/$id", RetailcrmHttpClient::METHOD_GET, - $this->fillSite($site, array('by' => $by)) + $this->fillSite($site, ['by' => $by]) ); } /** * Edit a customer * - * @param array $customer customer data - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param array $customer customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -953,22 +955,23 @@ class RetailcrmApiClientV5 RetailcrmHttpClient::METHOD_POST, $this->fillSite( $site, - array('customer' => json_encode($customer), 'by' => $by) + ['customer' => json_encode($customer), 'by' => $by] ) ); } /** * Get customers history + * * @param array $filter * @param null $page * @param null $limit * * @return RetailcrmApiResponse */ - public function customersHistory(array $filter = array(), $page = null, $limit = null) + public function customersHistory(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -997,7 +1000,6 @@ class RetailcrmApiClientV5 */ public function customersCombine(array $customers, $resultCustomer) { - if (!count($customers) || !count($resultCustomer)) { throw new \InvalidArgumentException( 'Parameters `customers` & `resultCustomer` must contains a data' @@ -1007,10 +1009,10 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/customers/combine', RetailcrmHttpClient::METHOD_POST, - array( + [ 'customers' => json_encode($customers), - 'resultCustomer' => json_encode($resultCustomer) - ) + 'resultCustomer' => json_encode($resultCustomer), + ] ); } @@ -1018,8 +1020,8 @@ class RetailcrmApiClientV5 * Returns filtered customers notes list * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1027,9 +1029,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function customersNotesList(array $filter = array(), $page = null, $limit = null) + public function customersNotesList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; } @@ -1039,6 +1041,7 @@ class RetailcrmApiClientV5 if (null !== $limit) { $parameters['limit'] = (int) $limit; } + return $this->client->makeRequest( '/customers/notes', RetailcrmHttpClient::METHOD_GET, @@ -1050,7 +1053,7 @@ class RetailcrmApiClientV5 * Create customer note * * @param array $note (default: array()) - * @param string $site (default: null) + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1065,17 +1068,18 @@ class RetailcrmApiClientV5 'Customer identifier must be set' ); } + return $this->client->makeRequest( '/customers/notes/create', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('note' => json_encode($note))) + $this->fillSite($site, ['note' => json_encode($note)]) ); } /** * Delete customer note * - * @param integer $id + * @param int $id * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1090,6 +1094,7 @@ class RetailcrmApiClientV5 'Note id must be set' ); } + return $this->client->makeRequest( "/customers/notes/$id/delete", RetailcrmHttpClient::METHOD_POST @@ -1100,8 +1105,8 @@ class RetailcrmApiClientV5 * Returns filtered corporate customers list * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1109,9 +1114,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function customersCorporateList(array $filter = array(), $page = null, $limit = null) + public function customersCorporateList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (isset($filter['contactIds'])) { $parameters['contactIds'] = $filter['contactIds']; @@ -1130,15 +1135,16 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate', - "GET", + 'GET', $parameters ); } + /** * Create a corporate customer * - * @param array $customerCorporate corporate customer data - * @param string $site (default: null) + * @param array $customerCorporate corporate customer data + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1148,7 +1154,7 @@ class RetailcrmApiClientV5 */ public function customersCorporateCreate(array $customerCorporate, $site = null) { - if (! count($customerCorporate)) { + if (!count($customerCorporate)) { throw new \InvalidArgumentException( 'Parameter `customerCorporate` must contains a data' ); @@ -1156,10 +1162,11 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/create', - "POST", - $this->fillSite($site, array('customerCorporate' => json_encode($customerCorporate))) + 'POST', + $this->fillSite($site, ['customerCorporate' => json_encode($customerCorporate)]) ); } + /** * Save corporate customer IDs' (id and externalId) association in the CRM * @@ -1173,7 +1180,7 @@ class RetailcrmApiClientV5 */ public function customersCorporateFixExternalIds(array $ids) { - if (! count($ids)) { + if (!count($ids)) { throw new \InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); @@ -1181,21 +1188,23 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/fix-external-ids', - "POST", - array('customersCorporate' => json_encode($ids)) + 'POST', + ['customersCorporate' => json_encode($ids)] ); } + /** * Get corporate customers history + * * @param array $filter * @param null $page * @param null $limit * * @return RetailcrmApiResponse */ - public function customersCorporateHistory(array $filter = array(), $page = null, $limit = null) + public function customersCorporateHistory(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -1210,16 +1219,17 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/history', - "GET", + 'GET', $parameters ); } + /** * Returns filtered corporate customers notes list * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1227,9 +1237,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function customersCorporateNotesList(array $filter = array(), $page = null, $limit = null) + public function customersCorporateNotesList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; } @@ -1242,15 +1252,16 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/notes', - "GET", + 'GET', $parameters ); } + /** * Create corporate customer note * * @param array $note (default: array()) - * @param string $site (default: null) + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1268,14 +1279,15 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/notes/create', - "POST", - $this->fillSite($site, array('note' => json_encode($note))) + 'POST', + $this->fillSite($site, ['note' => json_encode($note)]) ); } + /** * Delete corporate customer note * - * @param integer $id + * @param int $id * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1293,19 +1305,20 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/notes/$id/delete", - "POST" + 'POST' ); } + /** * Upload array of the corporate customers * - * @param array $customersCorporate array of corporate customers - * @param string $site (default: null) + * @param array $customersCorporate array of corporate customers + * @param string $site (default: null) * * @return RetailcrmApiResponse + * * @throws \RetailCrm\Exception\CurlException * @throws \RetailCrm\Exception\InvalidJsonException - * * @throws \InvalidArgumentException */ public function customersCorporateUpload(array $customersCorporate, $site = null) @@ -1318,15 +1331,16 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/upload', - "POST", - $this->fillSite($site, array('customersCorporate' => json_encode($customersCorporate))) + 'POST', + $this->fillSite($site, ['customersCorporate' => json_encode($customersCorporate)]) ); } + /** * Get corporate customer by id or externalId * - * @param string $id corporate customer identifier - * @param string $by (default: 'externalId') + * @param string $id corporate customer identifier + * @param string $by (default: 'externalId') * @param string $site (default: null) * * @throws \InvalidArgumentException @@ -1341,19 +1355,20 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id", - "GET", - $this->fillSite($site, array('by' => $by)) + 'GET', + $this->fillSite($site, ['by' => $by]) ); } + /** * Get corporate customer addresses by id or externalId * - * @param string $id corporate customer identifier - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param string $id corporate customer identifier + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1363,14 +1378,14 @@ class RetailcrmApiClientV5 */ public function customersCorporateAddresses( $id, - array $filter = array(), + array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null ) { $this->checkIdParameter($by); - $parameters = array('by' => $by); + $parameters = ['by' => $by]; if (count($filter)) { $parameters['filter'] = $filter; } @@ -1383,7 +1398,7 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id/addresses", - "GET", + 'GET', $this->fillSite($site, $parameters) ); } @@ -1391,10 +1406,10 @@ class RetailcrmApiClientV5 /** * Create corporate customer address * - * @param string $id corporate customer identifier - * @param array $address (default: array()) - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param string $id corporate customer identifier + * @param array $address (default: array()) + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1402,13 +1417,13 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function customersCorporateAddressesCreate($id, array $address = array(), $by = 'externalId', $site = null) + public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null) { /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id/addresses/create", - "POST", - $this->fillSite($site, array('address' => json_encode($address), 'by' => $by)) + 'POST', + $this->fillSite($site, ['address' => json_encode($address), 'by' => $by]) ); } @@ -1416,11 +1431,11 @@ class RetailcrmApiClientV5 * Edit corporate customer address * * @param string $customerId corporate customer identifier - * @param string $addressId corporate customer identifier - * @param array $address (default: array()) + * @param string $addressId corporate customer identifier + * @param array $address (default: array()) * @param string $customerBy (default: 'externalId') - * @param string $addressBy (default: 'externalId') - * @param string $site (default: null) + * @param string $addressBy (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1431,13 +1446,13 @@ class RetailcrmApiClientV5 public function customersCorporateAddressesEdit( $customerId, $addressId, - array $address = array(), + array $address = [], $customerBy = 'externalId', $addressBy = 'externalId', $site = null ) { $addressFiltered = array_filter($address); - if ((count(array_keys($addressFiltered)) <= 1) + if ((1 >= count(array_keys($addressFiltered))) && (!isset($addressFiltered['text']) || (isset($addressFiltered['text']) && empty($addressFiltered['text'])) ) @@ -1449,23 +1464,24 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$customerId/addresses/$addressId/edit", - "POST", - $this->fillSite($site, array( + 'POST', + $this->fillSite($site, [ 'address' => json_encode($address), 'by' => $customerBy, - 'entityBy' => $addressBy - )) + 'entityBy' => $addressBy, + ]) ); } + /** * Get corporate customer companies by id or externalId * - * @param string $id corporate customer identifier - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param string $id corporate customer identifier + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1475,14 +1491,14 @@ class RetailcrmApiClientV5 */ public function customersCorporateCompanies( $id, - array $filter = array(), + array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null ) { $this->checkIdParameter($by); - $parameters = array('by' => $by); + $parameters = ['by' => $by]; if (count($filter)) { $parameters['filter'] = $filter; } @@ -1495,17 +1511,18 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id/companies", - "GET", + 'GET', $this->fillSite($site, $parameters) ); } + /** * Create corporate customer company * - * @param string $id corporate customer identifier - * @param array $company (default: array()) - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param string $id corporate customer identifier + * @param array $company (default: array()) + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1513,35 +1530,36 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function customersCorporateCompaniesCreate($id, array $company = array(), $by = 'externalId', $site = null) + public function customersCorporateCompaniesCreate($id, array $company = [], $by = 'externalId', $site = null) { /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id/companies/create", - "POST", - $this->fillSite($site, array('company' => json_encode($company), 'by' => $by)) + 'POST', + $this->fillSite($site, ['company' => json_encode($company), 'by' => $by]) ); } + /** * Edit corporate customer company * * @param string $customerId corporate customer identifier - * @param string $companyId corporate customer identifier - * @param array $company (default: array()) + * @param string $companyId corporate customer identifier + * @param array $company (default: array()) * @param string $customerBy (default: 'externalId') - * @param string $companyBy (default: 'externalId') - * @param string $site (default: null) + * @param string $companyBy (default: 'externalId') + * @param string $site (default: null) * * @return RetailcrmApiResponse + * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException * @throws \RetailCrm\Exception\InvalidJsonException - * */ public function customersCorporateCompaniesEdit( $customerId, $companyId, - array $company = array(), + array $company = [], $customerBy = 'externalId', $companyBy = 'externalId', $site = null @@ -1549,23 +1567,24 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$customerId/companies/$companyId/edit", - "POST", - $this->fillSite($site, array( + 'POST', + $this->fillSite($site, [ 'company' => json_encode($company), 'by' => $customerBy, - 'entityBy' => $companyBy - )) + 'entityBy' => $companyBy, + ]) ); } + /** * Get corporate customer contacts by id or externalId * - * @param string $id corporate customer identifier - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param string $id corporate customer identifier + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1575,14 +1594,14 @@ class RetailcrmApiClientV5 */ public function customersCorporateContacts( $id, - array $filter = array(), + array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null ) { $this->checkIdParameter($by); - $parameters = array('by' => $by); + $parameters = ['by' => $by]; if (count($filter)) { $parameters['filter'] = $filter; } @@ -1595,53 +1614,55 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id/contacts", - "GET", + 'GET', $this->fillSite($site, $parameters) ); } + /** * Create corporate customer contact * - * @param string $id corporate customer identifier - * @param array $contact (default: array()) - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param string $id corporate customer identifier + * @param array $contact (default: array()) + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @return RetailcrmApiResponse + * * @throws \RetailCrm\Exception\CurlException * @throws \RetailCrm\Exception\InvalidJsonException - * * @throws \InvalidArgumentException */ - public function customersCorporateContactsCreate($id, array $contact = array(), $by = 'externalId', $site = null) + public function customersCorporateContactsCreate($id, array $contact = [], $by = 'externalId', $site = null) { /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$id/contacts/create", - "POST", - $this->fillSite($site, array('contact' => json_encode($contact), 'by' => $by)) + 'POST', + $this->fillSite($site, ['contact' => json_encode($contact), 'by' => $by]) ); } + /** * Edit corporate customer contact * * @param string $customerId corporate customer identifier - * @param string $contactId corporate customer identifier - * @param array $contact (default: array()) + * @param string $contactId corporate customer identifier + * @param array $contact (default: array()) * @param string $customerBy (default: 'externalId') - * @param string $contactBy (default: 'externalId') - * @param string $site (default: null) + * @param string $contactBy (default: 'externalId') + * @param string $site (default: null) * * @return RetailcrmApiResponse + * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException * @throws \RetailCrm\Exception\InvalidJsonException - * */ public function customersCorporateContactsEdit( $customerId, $contactId, - array $contact = array(), + array $contact = [], $customerBy = 'externalId', $contactBy = 'externalId', $site = null @@ -1649,20 +1670,21 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( "/customers-corporate/$customerId/contacts/$contactId/edit", - "POST", - $this->fillSite($site, array( + 'POST', + $this->fillSite($site, [ 'contact' => json_encode($contact), 'by' => $customerBy, - 'entityBy' => $contactBy - )) + 'entityBy' => $contactBy, + ]) ); } + /** * Edit a corporate customer * - * @param array $customerCorporate corporate customer data - * @param string $by (default: 'externalId') - * @param string $site (default: null) + * @param array $customerCorporate corporate customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1686,10 +1708,10 @@ class RetailcrmApiClientV5 /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( sprintf('/customers-corporate/%s/edit', $customerCorporate[$by]), - "POST", + 'POST', $this->fillSite( $site, - array('customerCorporate' => json_encode($customerCorporate), 'by' => $by) + ['customerCorporate' => json_encode($customerCorporate), 'by' => $by] ) ); } @@ -1698,8 +1720,8 @@ class RetailcrmApiClientV5 * Get orders assembly list * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1707,9 +1729,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function ordersPacksList(array $filter = array(), $page = null, $limit = null) + public function ordersPacksList(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -1731,7 +1753,7 @@ class RetailcrmApiClientV5 /** * Create orders assembly * - * @param array $pack pack data + * @param array $pack pack data * @param string $site (default: null) * * @throws \InvalidArgumentException @@ -1751,7 +1773,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/orders/packs/create', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('pack' => json_encode($pack))) + $this->fillSite($site, ['pack' => json_encode($pack)]) ); } @@ -1759,8 +1781,8 @@ class RetailcrmApiClientV5 * Get orders assembly history * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1768,9 +1790,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + public function ordersPacksHistory(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -1838,7 +1860,7 @@ class RetailcrmApiClientV5 /** * Edit orders assembly * - * @param array $pack pack data + * @param array $pack pack data * @param string $site (default: null) * * @throws \InvalidArgumentException @@ -1858,7 +1880,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/orders/packs/%s/edit', $pack['id']), RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('pack' => json_encode($pack))) + $this->fillSite($site, ['pack' => json_encode($pack)]) ); } @@ -1866,14 +1888,14 @@ class RetailcrmApiClientV5 * Get tasks list * * @param array $filter - * @param null $limit - * @param null $page + * @param null $limit + * @param null $page * * @return RetailcrmApiResponse */ - public function tasksList(array $filter = array(), $limit = null, $page = null) + public function tasksList(array $filter = [], $limit = null, $page = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -1896,10 +1918,9 @@ class RetailcrmApiClientV5 * Create task * * @param array $task - * @param null $site + * @param null $site * * @return RetailcrmApiResponse - * */ public function tasksCreate($task, $site = null) { @@ -1910,11 +1931,11 @@ class RetailcrmApiClientV5 } return $this->client->makeRequest( - "/tasks/create", + '/tasks/create', RetailcrmHttpClient::METHOD_POST, $this->fillSite( $site, - array('task' => json_encode($task)) + ['task' => json_encode($task)] ) ); } @@ -1923,10 +1944,9 @@ class RetailcrmApiClientV5 * Edit task * * @param array $task - * @param null $site + * @param null $site * * @return RetailcrmApiResponse - * */ public function tasksEdit($task, $site = null) { @@ -1941,7 +1961,7 @@ class RetailcrmApiClientV5 RetailcrmHttpClient::METHOD_POST, $this->fillSite( $site, - array('task' => json_encode($task)) + ['task' => json_encode($task)] ) ); } @@ -1971,8 +1991,8 @@ class RetailcrmApiClientV5 * Get products groups * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -1980,9 +2000,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function storeProductsGroups(array $filter = array(), $page = null, $limit = null) + public function storeProductsGroups(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -2005,8 +2025,8 @@ class RetailcrmApiClientV5 * Get purchase prices & stock balance * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -2014,9 +2034,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function storeInventories(array $filter = array(), $page = null, $limit = null) + public function storeInventories(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -2041,6 +2061,7 @@ class RetailcrmApiClientV5 * @param string $code get settings code * * @return RetailcrmApiResponse + * * @throws \RetailCrm\Exception\InvalidJsonException * @throws \RetailCrm\Exception\CurlException * @throws \InvalidArgumentException @@ -2088,8 +2109,8 @@ class RetailcrmApiClientV5 /** * Upload store inventories * - * @param array $offers offers data - * @param string $site (default: null) + * @param array $offers offers data + * @param string $site (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -2108,7 +2129,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/store/inventories/upload', RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('offers' => json_encode($offers))) + $this->fillSite($site, ['offers' => json_encode($offers)]) ); } @@ -2116,8 +2137,8 @@ class RetailcrmApiClientV5 * Get products * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: null) + * @param int $limit (default: null) * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -2125,9 +2146,9 @@ class RetailcrmApiClientV5 * * @return RetailcrmApiResponse */ - public function storeProducts(array $filter = array(), $page = null, $limit = null) + public function storeProducts(array $filter = [], $page = null, $limit = null) { - $parameters = array(); + $parameters = []; if (count($filter)) { $parameters['filter'] = $filter; @@ -2191,7 +2212,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($configuration)) + ['configuration' => json_encode($configuration)] ); } @@ -2199,7 +2220,7 @@ class RetailcrmApiClientV5 * Delivery tracking update * * @param string $code - * @param array $statusUpdate + * @param array $statusUpdate * * @throws \RetailCrm\Exception\InvalidJsonException * @throws \RetailCrm\Exception\CurlException @@ -2282,7 +2303,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/delivery-services/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('deliveryService' => json_encode($data)) + ['deliveryService' => json_encode($data)] ); } @@ -2325,7 +2346,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/delivery-types/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('deliveryType' => json_encode($data)) + ['deliveryType' => json_encode($data)] ); } @@ -2368,7 +2389,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/order-methods/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('orderMethod' => json_encode($data)) + ['orderMethod' => json_encode($data)] ); } @@ -2411,7 +2432,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/order-types/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('orderType' => json_encode($data)) + ['orderType' => json_encode($data)] ); } @@ -2454,7 +2475,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/payment-statuses/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('paymentStatus' => json_encode($data)) + ['paymentStatus' => json_encode($data)] ); } @@ -2497,7 +2518,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/payment-types/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('paymentType' => json_encode($data)) + ['paymentType' => json_encode($data)] ); } @@ -2540,7 +2561,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/product-statuses/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('productStatus' => json_encode($data)) + ['productStatus' => json_encode($data)] ); } @@ -2583,7 +2604,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/sites/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('site' => json_encode($data)) + ['site' => json_encode($data)] ); } @@ -2643,7 +2664,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/statuses/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('status' => json_encode($data)) + ['status' => json_encode($data)] ); } @@ -2692,7 +2713,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( sprintf('/reference/stores/%s/edit', $data['code']), RetailcrmHttpClient::METHOD_POST, - array('store' => json_encode($data)) + ['store' => json_encode($data)] ); } @@ -2722,20 +2743,19 @@ class RetailcrmApiClientV5 /** * Edit telephony settings * - * @param string $code symbolic code - * @param string $clientId client id - * @param boolean $active telephony activity - * @param mixed $name service name - * @param mixed $makeCallUrl service init url - * @param mixed $image service logo url(svg file) - * - * @param array $additionalCodes - * @param array $externalPhones - * @param bool $allowEdit - * @param bool $inputEventSupported - * @param bool $outputEventSupported - * @param bool $hangupEventSupported - * @param bool $changeUserStatusUrl + * @param string $code symbolic code + * @param string $clientId client id + * @param bool $active telephony activity + * @param mixed $name service name + * @param mixed $makeCallUrl service init url + * @param mixed $image service logo url(svg file) + * @param array $additionalCodes + * @param array $externalPhones + * @param bool $allowEdit + * @param bool $inputEventSupported + * @param bool $outputEventSupported + * @param bool $hangupEventSupported + * @param bool $changeUserStatusUrl * * @return RetailcrmApiResponse */ @@ -2746,15 +2766,14 @@ class RetailcrmApiClientV5 $name = false, $makeCallUrl = false, $image = false, - $additionalCodes = array(), - $externalPhones = array(), + $additionalCodes = [], + $externalPhones = [], $allowEdit = false, $inputEventSupported = false, $outputEventSupported = false, $hangupEventSupported = false, $changeUserStatusUrl = false - ) - { + ) { if (!isset($code)) { throw new \InvalidArgumentException('Code must be set'); } @@ -2820,7 +2839,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/telephony/setting/$code/edit", RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($parameters)) + ['configuration' => json_encode($parameters)] ); } @@ -2828,16 +2847,16 @@ class RetailcrmApiClientV5 * Call event * * @param string $phone phone number - * @param string $type call type - * @param array $codes + * @param string $type call type + * @param array $codes * @param string $hangupStatus * @param string $externalPhone - * @param array $webAnalyticsData + * @param array $webAnalyticsData * * @return RetailcrmApiResponse + * * @internal param string $code additional phone code * @internal param string $status call status - * */ public function telephonyCallEvent( $phone, @@ -2845,9 +2864,8 @@ class RetailcrmApiClientV5 $codes, $hangupStatus, $externalPhone = null, - $webAnalyticsData = array() - ) - { + $webAnalyticsData = [] + ) { if (!isset($phone)) { throw new \InvalidArgumentException('Phone number must be set'); } @@ -2867,11 +2885,10 @@ class RetailcrmApiClientV5 $parameters['callExternalId'] = $externalPhone; $parameters['webAnalyticsData'] = $webAnalyticsData; - return $this->client->makeRequest( '/telephony/call/event', RetailcrmHttpClient::METHOD_POST, - array('event' => json_encode($parameters)) + ['event' => json_encode($parameters)] ); } @@ -2897,15 +2914,15 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( '/telephony/calls/upload', RetailcrmHttpClient::METHOD_POST, - array('calls' => json_encode($calls)) + ['calls' => json_encode($calls)] ); } /** * Get call manager * - * @param string $phone phone number - * @param bool $details detailed information + * @param string $phone phone number + * @param bool $details detailed information * * @throws \InvalidArgumentException * @throws \RetailCrm\Exception\CurlException @@ -2970,7 +2987,7 @@ class RetailcrmApiClientV5 return $this->client->makeRequest( "/integration-modules/$code/edit", RetailcrmHttpClient::METHOD_POST, - array('integrationModule' => json_encode($configuration)) + ['integrationModule' => json_encode($configuration)] ); } @@ -2985,10 +3002,10 @@ class RetailcrmApiClientV5 */ protected function checkIdParameter($by) { - $allowedForBy = array( + $allowedForBy = [ 'externalId', - 'id' - ); + 'id', + ]; if (!in_array($by, $allowedForBy, false)) { throw new \InvalidArgumentException( @@ -3006,8 +3023,8 @@ class RetailcrmApiClientV5 /** * Fill params by site value * - * @param string $site site code - * @param array $params input parameters + * @param string $site site code + * @param array $params input parameters * * @return array */ diff --git a/retailcrm/lib/api/RetailcrmApiErrors.php b/retailcrm/lib/api/RetailcrmApiErrors.php index fc8500e..550bad4 100644 --- a/retailcrm/lib/api/RetailcrmApiErrors.php +++ b/retailcrm/lib/api/RetailcrmApiErrors.php @@ -40,7 +40,7 @@ class RetailcrmApiErrors /** @var array */ private static $errors; - /** @var integer */ + /** @var int */ private static $statusCode; /** @@ -69,6 +69,7 @@ class RetailcrmApiErrors public static function getErrors() { static::checkArray(); + return static::$errors; } @@ -78,7 +79,7 @@ class RetailcrmApiErrors * Returns false if incorrect data was passed to it. * * @param array $errors - * @param integer $statusCode + * @param int $statusCode * * @return bool */ @@ -102,7 +103,7 @@ class RetailcrmApiErrors private static function checkArray() { if (!is_array(static::$errors)) { - static::$errors = array(); + static::$errors = []; } } } diff --git a/retailcrm/lib/api/RetailcrmApiPaginatedRequest.php b/retailcrm/lib/api/RetailcrmApiPaginatedRequest.php index 1ef0cea..cc2e0d7 100644 --- a/retailcrm/lib/api/RetailcrmApiPaginatedRequest.php +++ b/retailcrm/lib/api/RetailcrmApiPaginatedRequest.php @@ -90,6 +90,7 @@ class RetailcrmApiPaginatedRequest public function setApi($api) { $this->api = $api; + return $this; } @@ -103,6 +104,7 @@ class RetailcrmApiPaginatedRequest public function setMethod($method) { $this->method = $method; + return $this; } @@ -116,6 +118,7 @@ class RetailcrmApiPaginatedRequest public function setParams($params) { $this->params = $params; + return $this; } @@ -129,6 +132,7 @@ class RetailcrmApiPaginatedRequest public function setDataKey($dataKey) { $this->dataKey = $dataKey; + return $this; } @@ -142,6 +146,7 @@ class RetailcrmApiPaginatedRequest public function setLimit($limit) { $this->limit = $limit; + return $this; } @@ -155,6 +160,7 @@ class RetailcrmApiPaginatedRequest public function setPageLimit($pageLimit) { $this->pageLimit = $pageLimit; + return $this; } @@ -165,13 +171,13 @@ class RetailcrmApiPaginatedRequest */ public function execute() { - $this->data = array(); + $this->data = []; $response = true; $page = 1; do { $response = call_user_func_array( - array($this->api, $this->method), + [$this->api, $this->method], $this->buildParams($this->params, $page) ); @@ -180,7 +186,7 @@ class RetailcrmApiPaginatedRequest $page = $response['pagination']['currentPage'] + 1; } - if($this->pageLimit !== null && $page > $this->pageLimit) { + if (null !== $this->pageLimit && $page > $this->pageLimit) { break; } @@ -211,7 +217,7 @@ class RetailcrmApiPaginatedRequest $this->method = ''; $this->limit = 100; $this->pageLimit = null; - $this->data = array(); + $this->data = []; return $this; } @@ -220,18 +226,18 @@ class RetailcrmApiPaginatedRequest * buildParams * * @param array $placeholderParams - * @param int $currentPage + * @param int $currentPage * * @return mixed */ private function buildParams($placeholderParams, $currentPage) { foreach ($placeholderParams as $key => $param) { - if ($param == '{{page}}') { + if ('{{page}}' == $param) { $placeholderParams[$key] = $currentPage; } - if ($param == '{{limit}}') { + if ('{{limit}}' == $param) { $placeholderParams[$key] = $this->limit; } } diff --git a/retailcrm/lib/api/RetailcrmApiRequest.php b/retailcrm/lib/api/RetailcrmApiRequest.php index d77a4f1..9385192 100644 --- a/retailcrm/lib/api/RetailcrmApiRequest.php +++ b/retailcrm/lib/api/RetailcrmApiRequest.php @@ -18,11 +18,13 @@ class RetailcrmApiRequest /** * @param mixed $api + * * @return RetailcrmApiRequest */ public function setApi($api) { $this->api = $api; + return $this; } @@ -40,6 +42,7 @@ class RetailcrmApiRequest public function setData($data) { $this->data = $data; + return $this; } @@ -57,8 +60,7 @@ class RetailcrmApiRequest public function setMethod($method) { $this->method = $method; + return $this; } - - -} \ No newline at end of file +} diff --git a/retailcrm/lib/api/RetailcrmApiResponse.php b/retailcrm/lib/api/RetailcrmApiResponse.php index 904108d..a7d21b0 100644 --- a/retailcrm/lib/api/RetailcrmApiResponse.php +++ b/retailcrm/lib/api/RetailcrmApiResponse.php @@ -47,7 +47,7 @@ class RetailcrmApiResponse implements \ArrayAccess /** * ApiResponse constructor. * - * @param int $statusCode HTTP status code + * @param int $statusCode HTTP status code * @param mixed $responseBody HTTP body * * @throws InvalidJsonException @@ -96,14 +96,14 @@ class RetailcrmApiResponse implements \ArrayAccess */ public function isSuccessful() { - return $this->statusCode < 400; + return 400 > $this->statusCode; } /** * Allow to access for the property throw class method * - * @param string $name method name - * @param mixed $arguments method parameters + * @param string $name method name + * @param mixed $arguments method parameters * * @throws \InvalidArgumentException * @@ -143,9 +143,10 @@ class RetailcrmApiResponse implements \ArrayAccess * Offset set * * @param mixed $offset offset - * @param mixed $value value + * @param mixed $value value * * @throws \BadMethodCallException + * * @return void */ public function offsetSet($offset, $value) @@ -159,6 +160,7 @@ class RetailcrmApiResponse implements \ArrayAccess * @param mixed $offset offset * * @throws \BadMethodCallException + * * @return void */ public function offsetUnset($offset) diff --git a/retailcrm/lib/api/RetailcrmHttpClient.php b/retailcrm/lib/api/RetailcrmHttpClient.php index 3357b2c..7b10aac 100644 --- a/retailcrm/lib/api/RetailcrmHttpClient.php +++ b/retailcrm/lib/api/RetailcrmHttpClient.php @@ -46,12 +46,12 @@ class RetailcrmHttpClient /** * Client constructor. * - * @param string $url api url - * @param array $defaultParameters array of parameters + * @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( @@ -76,9 +76,9 @@ class RetailcrmHttpClient /** * Make HTTP request * - * @param string $path request url - * @param string $method (default: 'GET') - * @param array $parameters (default: array()) + * @param string $path request url + * @param string $method (default: 'GET') + * @param array $parameters (default: array()) * * @SuppressWarnings(PHPMD.ExcessiveParameterList) * @@ -91,9 +91,9 @@ class RetailcrmHttpClient public function makeRequest( $path, $method, - array $parameters = array() + array $parameters = [] ) { - $allowedMethods = array(self::METHOD_GET, self::METHOD_POST); + $allowedMethods = [self::METHOD_GET, self::METHOD_POST]; if (!in_array($method, $allowedMethods, false)) { throw new \InvalidArgumentException( diff --git a/retailcrm/lib/api/RetailcrmProxy.php b/retailcrm/lib/api/RetailcrmProxy.php index 6c3116b..3513a4d 100755 --- a/retailcrm/lib/api/RetailcrmProxy.php +++ b/retailcrm/lib/api/RetailcrmProxy.php @@ -1,6 +1,5 @@ setAction(function ($request) { return call_user_func_array([$this->client, $request->getMethod()], $request->getData()); }) - ->build(); + ->build() + ; } public function __call($method, $arguments) @@ -76,7 +76,8 @@ class RetailcrmProxy $request->setApi($this->client) ->setMethod($method) - ->setData($arguments); + ->setData($arguments) + ; return $this->pipeline->run($request); } diff --git a/retailcrm/lib/api/index.php b/retailcrm/lib/api/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/lib/api/index.php +++ b/retailcrm/lib/api/index.php @@ -1,8 +1,9 @@ false, - 'errorMsg' => sprintf('Internal error: %s', $e->getMessage()) + 'errorMsg' => sprintf('Internal error: %s', $e->getMessage()), ])); } diff --git a/retailcrm/lib/api/middleware/RetailcrmLoggerMiddleware.php b/retailcrm/lib/api/middleware/RetailcrmLoggerMiddleware.php index 39b5533..f5fdbf6 100644 --- a/retailcrm/lib/api/middleware/RetailcrmLoggerMiddleware.php +++ b/retailcrm/lib/api/middleware/RetailcrmLoggerMiddleware.php @@ -36,18 +36,16 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - - class RetailcrmLoggerMiddleware implements RetailcrmMiddlewareInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function __invoke(RetailcrmApiRequest $request, callable $next = null) { $method = $request->getMethod(); - if (!is_null($method)) { + if (null !== $method) { RetailcrmLogger::writeDebug($method, print_r($request->getData(), true)); } diff --git a/retailcrm/lib/api/middleware/index.php b/retailcrm/lib/api/middleware/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/lib/api/middleware/index.php +++ b/retailcrm/lib/api/middleware/index.php @@ -1,8 +1,9 @@ pipeline; + return $pipeline($request); } /** * @param callable $action + * * @return $this */ public function setAction(callable $action) { $this->action = $action; + return $this; } /** * @param array $middlewares + * * @return $this */ public function setMiddlewares(array $middlewares) { $this->middlewares = $middlewares; + return $this; } @@ -64,7 +70,8 @@ class RetailcrmPipeline { return function ($stack, $middlewareClass) { return function ($request) use ($stack, $middlewareClass) { - $middleware = new $middlewareClass; + $middleware = new $middlewareClass(); + return $middleware($request, $stack); }; }; diff --git a/retailcrm/lib/api/pipeline/index.php b/retailcrm/lib/api/pipeline/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/lib/api/pipeline/index.php +++ b/retailcrm/lib/api/pipeline/index.php @@ -1,8 +1,9 @@ cliMode = (bool)$mode; + $this->cliMode = (bool) $mode; } /** @@ -72,7 +71,7 @@ abstract class RetailcrmAbstractEvent implements RetailcrmEventInterface */ public function setForce($force) { - $this->force = (bool)$force; + $this->force = (bool) $force; } /** @@ -82,8 +81,9 @@ abstract class RetailcrmAbstractEvent implements RetailcrmEventInterface */ public function setShopId($shopId = null) { - if (!is_null($shopId)) - $this->shopId = intval($shopId); + if (null !== $shopId) { + $this->shopId = (int) $shopId; + } } /** @@ -93,7 +93,7 @@ abstract class RetailcrmAbstractEvent implements RetailcrmEventInterface */ protected function isRunning() { - return !$this->force && (RetailcrmJobManager::getCurrentJob() !== '' || RetailcrmCli::getCurrentJob() !== ''); + return !$this->force && ('' !== RetailcrmJobManager::getCurrentJob() || '' !== RetailcrmCli::getCurrentJob()); } /** @@ -103,7 +103,7 @@ abstract class RetailcrmAbstractEvent implements RetailcrmEventInterface */ protected function setRunning() { - if($this->force) { + if ($this->force) { return true; } @@ -124,12 +124,12 @@ abstract class RetailcrmAbstractEvent implements RetailcrmEventInterface $shops = Shop::getShops(); if (Shop::isFeatureActive()) { - if ($this->shopId > 0) { + if (0 < $this->shopId) { if (isset($shops[$this->shopId])) { RetailcrmLogger::writeDebug( __METHOD__, sprintf( - "Running job for shop %s (%s).", + 'Running job for shop %s (%s).', $shops[$this->shopId]['name'], $this->shopId ) @@ -151,7 +151,6 @@ abstract class RetailcrmAbstractEvent implements RetailcrmEventInterface return $shops; } else { - return [$shops[Shop::getContextShopID()]]; } } diff --git a/retailcrm/lib/events/RetailcrmClearLogsEvent.php b/retailcrm/lib/events/RetailcrmClearLogsEvent.php index f3b8936..6395cb8 100644 --- a/retailcrm/lib/events/RetailcrmClearLogsEvent.php +++ b/retailcrm/lib/events/RetailcrmClearLogsEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmClearLogsEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -57,7 +56,7 @@ class RetailcrmClearLogsEvent extends RetailcrmAbstractEvent implements Retailcr } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/RetailcrmEventInterface.php b/retailcrm/lib/events/RetailcrmEventInterface.php index 5679b52..0daf12b 100644 --- a/retailcrm/lib/events/RetailcrmEventInterface.php +++ b/retailcrm/lib/events/RetailcrmEventInterface.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - interface RetailcrmEventInterface { /** diff --git a/retailcrm/lib/events/RetailcrmExportEvent.php b/retailcrm/lib/events/RetailcrmExportEvent.php index f21e871..efd3c3a 100644 --- a/retailcrm/lib/events/RetailcrmExportEvent.php +++ b/retailcrm/lib/events/RetailcrmExportEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmExportEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -54,7 +53,7 @@ class RetailcrmExportEvent extends RetailcrmAbstractEvent implements RetailcrmEv $shops = $this->getShops(); foreach ($shops as $shop) { - RetailcrmContextSwitcher::setShopContext(intval($shop['id_shop'])); + RetailcrmContextSwitcher::setShopContext((int) ($shop['id_shop'])); $api = RetailcrmTools::getApiClient(); @@ -76,7 +75,7 @@ class RetailcrmExportEvent extends RetailcrmAbstractEvent implements RetailcrmEv } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/RetailcrmIcmlEvent.php b/retailcrm/lib/events/RetailcrmIcmlEvent.php index 3355dc3..a218190 100644 --- a/retailcrm/lib/events/RetailcrmIcmlEvent.php +++ b/retailcrm/lib/events/RetailcrmIcmlEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmIcmlEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -54,7 +53,7 @@ class RetailcrmIcmlEvent extends RetailcrmAbstractEvent implements RetailcrmEven $shops = $this->getShops(); foreach ($shops as $shop) { - RetailcrmContextSwitcher::setShopContext(intval($shop['id_shop'])); + RetailcrmContextSwitcher::setShopContext((int) ($shop['id_shop'])); $job = new RetailcrmCatalog(); $data = $job->getData(); @@ -67,7 +66,7 @@ class RetailcrmIcmlEvent extends RetailcrmAbstractEvent implements RetailcrmEven } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/RetailcrmIcmlUpdateUrlEvent.php b/retailcrm/lib/events/RetailcrmIcmlUpdateUrlEvent.php index 39ba1e2..572f8b4 100644 --- a/retailcrm/lib/events/RetailcrmIcmlUpdateUrlEvent.php +++ b/retailcrm/lib/events/RetailcrmIcmlUpdateUrlEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmIcmlUpdateUrlEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -54,7 +53,7 @@ class RetailcrmIcmlUpdateUrlEvent extends RetailcrmAbstractEvent implements Reta $shops = $this->getShops(); foreach ($shops as $shop) { - RetailcrmContextSwitcher::setShopContext(intval($shop['id_shop'])); + RetailcrmContextSwitcher::setShopContext((int) ($shop['id_shop'])); if (!file_exists(RetailcrmCatalogHelper::getIcmlFilePath())) { continue; @@ -86,7 +85,7 @@ class RetailcrmIcmlUpdateUrlEvent extends RetailcrmAbstractEvent implements Reta } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/RetailcrmInventoriesEvent.php b/retailcrm/lib/events/RetailcrmInventoriesEvent.php index 00b6676..74785c7 100644 --- a/retailcrm/lib/events/RetailcrmInventoriesEvent.php +++ b/retailcrm/lib/events/RetailcrmInventoriesEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmInventoriesEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -54,7 +53,7 @@ class RetailcrmInventoriesEvent extends RetailcrmAbstractEvent implements Retail $shops = $this->getShops(); foreach ($shops as $shop) { - RetailcrmContextSwitcher::setShopContext(intval($shop['id_shop'])); + RetailcrmContextSwitcher::setShopContext((int) ($shop['id_shop'])); if (!Configuration::get(RetailCRM::ENABLE_BALANCES_RECEIVING)) { RetailcrmLogger::writeDebug( @@ -83,7 +82,7 @@ class RetailcrmInventoriesEvent extends RetailcrmAbstractEvent implements Retail } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/RetailcrmMissingEvent.php b/retailcrm/lib/events/RetailcrmMissingEvent.php index 93d1e06..1e4b0f1 100644 --- a/retailcrm/lib/events/RetailcrmMissingEvent.php +++ b/retailcrm/lib/events/RetailcrmMissingEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmMissingEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -78,25 +77,25 @@ class RetailcrmMissingEvent extends RetailcrmAbstractEvent implements RetailcrmE $payment = json_decode(Configuration::get(RetailCRM::PAYMENT), true); $status = json_decode(Configuration::get(RetailCRM::STATUS), true); - $order = array( + $order = [ 'externalId' => $orderInstance->id, 'createdAt' => $orderInstance->date_add, - ); + ]; - /** + /* * Add order customer info * */ if (!empty($orderInstance->id_customer)) { $orderCustomer = new Customer($orderInstance->id_customer); - $customer = array( + $customer = [ 'externalId' => $orderCustomer->id, 'firstName' => $orderCustomer->firstname, 'lastname' => $orderCustomer->lastname, 'email' => $orderCustomer->email, - 'createdAt' => $orderCustomer->date_add - ); + 'createdAt' => $orderCustomer->date_add, + ]; $response = $api->customersEdit($customer); @@ -110,13 +109,12 @@ class RetailcrmMissingEvent extends RetailcrmAbstractEvent implements RetailcrmE } } - - /** + /* * Add order status * */ - if ($orderInstance->current_state == 0) { + if (0 == $orderInstance->current_state) { $order['status'] = 'completed'; } else { $order['status'] = array_key_exists($orderInstance->current_state, $status) @@ -127,22 +125,20 @@ class RetailcrmMissingEvent extends RetailcrmAbstractEvent implements RetailcrmE /** * Add order address data - * */ - $cart = new Cart($orderInstance->getCartIdStatic($orderInstance->id)); $addressCollection = $cart->getAddressCollection(); $address = array_shift($addressCollection); if ($address instanceof Address) { - $phone = is_null($address->phone) - ? is_null($address->phone_mobile) ? '' : $address->phone_mobile + $phone = null === $address->phone + ? null === $address->phone_mobile ? '' : $address->phone_mobile : $address->phone ; $postcode = $address->postcode; $city = $address->city; - $addres_line = sprintf("%s %s", $address->address1, $address->address2); + $addres_line = sprintf('%s %s', $address->address1, $address->address2); } if (!empty($postcode)) { @@ -161,11 +157,11 @@ class RetailcrmMissingEvent extends RetailcrmAbstractEvent implements RetailcrmE $order['phone'] = $phone; } - /** + /* * Add payment & shippment data */ - if (Module::getInstanceByName('advancedcheckout') === false) { + if (false === Module::getInstanceByName('advancedcheckout')) { $paymentType = $orderInstance->module; } else { $paymentType = $orderInstance->payment; @@ -179,26 +175,24 @@ class RetailcrmMissingEvent extends RetailcrmAbstractEvent implements RetailcrmE $order['delivery']['code'] = $delivery[$orderInstance->id_carrier]; } - if (isset($orderInstance->total_shipping_tax_incl) && (int) $orderInstance->total_shipping_tax_incl > 0) { + if (isset($orderInstance->total_shipping_tax_incl) && 0 < (int) $orderInstance->total_shipping_tax_incl) { $order['delivery']['cost'] = round($orderInstance->total_shipping_tax_incl, 2); } /** * Add products - * */ - $products = $orderInstance->getProducts(); foreach ($products as $product) { - $item = array( + $item = [ //'productId' => $product['product_id'], - 'offer' => array('externalId' => $product['product_id']), + 'offer' => ['externalId' => $product['product_id']], 'productName' => $product['product_name'], 'quantity' => $product['product_quantity'], 'initialPrice' => round($product['product_price'], 2), - 'purchasePrice' => round($product['purchase_supplier_price'], 2) - ); + 'purchasePrice' => round($product['purchase_supplier_price'], 2), + ]; $order['items'][] = $item; } diff --git a/retailcrm/lib/events/RetailcrmSyncEvent.php b/retailcrm/lib/events/RetailcrmSyncEvent.php index c394ee0..c7df1e1 100644 --- a/retailcrm/lib/events/RetailcrmSyncEvent.php +++ b/retailcrm/lib/events/RetailcrmSyncEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmSyncEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -54,7 +53,7 @@ class RetailcrmSyncEvent extends RetailcrmAbstractEvent implements RetailcrmEven $shops = $this->getShops(); foreach ($shops as $shop) { - RetailcrmContextSwitcher::setShopContext(intval($shop['id_shop'])); + RetailcrmContextSwitcher::setShopContext((int) ($shop['id_shop'])); if (!Configuration::get(RetailCRM::ENABLE_HISTORY_UPLOADS)) { RetailcrmLogger::writeDebug( @@ -67,7 +66,7 @@ class RetailcrmSyncEvent extends RetailcrmAbstractEvent implements RetailcrmEven $apiUrl = Configuration::get(RetailCRM::API_URL); $apiKey = Configuration::get(RetailCRM::API_KEY); - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); if (!empty($apiUrl) && !empty($apiKey)) { RetailcrmHistory::$api = new RetailcrmProxy($apiUrl, $apiKey, RetailcrmLogger::getLogFile()); @@ -85,7 +84,7 @@ class RetailcrmSyncEvent extends RetailcrmAbstractEvent implements RetailcrmEven } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/RetailcrmUpdateSinceIdEvent.php b/retailcrm/lib/events/RetailcrmUpdateSinceIdEvent.php index 740892d..5610d74 100644 --- a/retailcrm/lib/events/RetailcrmUpdateSinceIdEvent.php +++ b/retailcrm/lib/events/RetailcrmUpdateSinceIdEvent.php @@ -35,13 +35,12 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - -require_once(dirname(__FILE__) . '/../RetailcrmPrestashopLoader.php'); +require_once __DIR__ . '/../RetailcrmPrestashopLoader.php'; class RetailcrmUpdateSinceIdEvent extends RetailcrmAbstractEvent implements RetailcrmEventInterface { /** - * @inheritDoc + * {@inheritDoc} */ public function execute() { @@ -54,7 +53,7 @@ class RetailcrmUpdateSinceIdEvent extends RetailcrmAbstractEvent implements Reta $shops = $this->getShops(); foreach ($shops as $shop) { - RetailcrmContextSwitcher::setShopContext(intval($shop['id_shop'])); + RetailcrmContextSwitcher::setShopContext((int) ($shop['id_shop'])); $api = RetailcrmTools::getApiClient(); @@ -71,7 +70,7 @@ class RetailcrmUpdateSinceIdEvent extends RetailcrmAbstractEvent implements Reta } /** - * @inheritDoc + * {@inheritDoc} */ public function getName() { diff --git a/retailcrm/lib/events/index.php b/retailcrm/lib/events/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/lib/events/index.php +++ b/retailcrm/lib/events/index.php @@ -1,8 +1,9 @@ address = $address; + return $this; } @@ -103,20 +104,21 @@ class RetailcrmCustomerSwitcherResult * Save customer (if exists) and order. * * @return $this + * * @throws \PrestaShopException */ public function save() { RetailcrmLogger::writeDebugArray( __METHOD__, - array( + [ 'Saving customer, address and order:', - array( + [ 'customer' => RetailcrmTools::dumpEntity($this->customer), 'address' => RetailcrmTools::dumpEntity($this->address), - 'order' => RetailcrmTools::dumpEntity($this->order) - ) - ) + 'order' => RetailcrmTools::dumpEntity($this->order), + ], + ] ); if (!empty($this->customer)) { diff --git a/retailcrm/lib/models/RetailcrmCustomerSwitcherState.php b/retailcrm/lib/models/RetailcrmCustomerSwitcherState.php index cbb677d..78d9f62 100644 --- a/retailcrm/lib/models/RetailcrmCustomerSwitcherState.php +++ b/retailcrm/lib/models/RetailcrmCustomerSwitcherState.php @@ -37,22 +37,22 @@ */ class RetailcrmCustomerSwitcherState { - /** @var \Order $order */ - private $order; + /** @var \Order */ + private $order; - /** @var array */ - private $newCustomer; + /** @var array */ + private $newCustomer; - /** @var array */ - private $newContact; + /** @var array */ + private $newContact; - /** @var string $newCompanyName */ + /** @var string */ private $newCompanyName; - /** @var array $companyAddress */ + /** @var array */ private $companyAddress; - /** @var array $crmOrderShippingAddress */ + /** @var array */ private $crmOrderShippingAddress; /** @@ -71,6 +71,7 @@ class RetailcrmCustomerSwitcherState public function setOrder($order) { $this->order = $order; + return $this; } @@ -90,6 +91,7 @@ class RetailcrmCustomerSwitcherState public function setNewCustomer($newCustomer) { $this->newCustomer = $newCustomer; + return $this; } @@ -109,6 +111,7 @@ class RetailcrmCustomerSwitcherState public function setNewContact($newContact) { $this->newContact = $newContact; + return $this; } @@ -128,6 +131,7 @@ class RetailcrmCustomerSwitcherState public function setNewCompanyName($newCompanyName) { $this->newCompanyName = $newCompanyName; + return $this; } @@ -147,6 +151,7 @@ class RetailcrmCustomerSwitcherState public function setCompanyAddress($companyAddress) { $this->companyAddress = $companyAddress; + return $this; } @@ -184,6 +189,7 @@ class RetailcrmCustomerSwitcherState public function setCrmOrderShippingAddress($crmOrderShippingAddress) { $this->crmOrderShippingAddress = $crmOrderShippingAddress; + return $this; } @@ -202,6 +208,7 @@ class RetailcrmCustomerSwitcherState * Throws an exception if state is not valid * * @throws \InvalidArgumentException + * * @return void */ public function validate() @@ -217,11 +224,11 @@ class RetailcrmCustomerSwitcherState if (!empty($this->newCustomer) && !empty($this->newContact)) { RetailcrmLogger::writeDebugArray( __METHOD__, - array( + [ 'State data (customer and contact):' . PHP_EOL, $this->getNewCustomer(), - $this->getNewContact() - ) + $this->getNewContact(), + ] ); throw new \InvalidArgumentException( 'Too much data in state - cannot determine which customer should be used.' diff --git a/retailcrm/lib/models/index.php b/retailcrm/lib/models/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/lib/models/index.php +++ b/retailcrm/lib/models/index.php @@ -1,8 +1,9 @@ module = $module; $this->smarty = $smarty; $this->assets = $assets; - $this->errors = array(); - $this->warnings = array(); - $this->informations = array(); - $this->confirmations = array(); + $this->errors = []; + $this->warnings = []; + $this->informations = []; + $this->confirmations = []; } /** @@ -106,6 +106,7 @@ abstract class RetailcrmAbstractTemplate * @param $file * * @return mixed + * * @throws RuntimeException */ public function render($file) @@ -114,21 +115,21 @@ abstract class RetailcrmAbstractTemplate $this->setTemplate(); if (null === $this->template) { - throw new \RuntimeException("Template not be blank"); + throw new \RuntimeException('Template not be blank'); } // set url post for forms if (empty($this->smarty->getTemplateVars('url_post'))) { $this->data['url_post'] = $this->smarty->getTemplateVars('current') - .'&token='.$this->smarty->getTemplateVars('token'); + . '&token=' . $this->smarty->getTemplateVars('token'); } - $this->smarty->assign(\array_merge($this->data, array( + $this->smarty->assign(\array_merge($this->data, [ 'moduleErrors' => $this->errors, 'moduleWarnings' => $this->warnings, 'moduleConfirmations' => $this->confirmations, 'moduleInfos' => $this->informations, - ))); + ])); return $this->module->display($file, "views/templates/admin/$this->template"); } @@ -204,5 +205,6 @@ abstract class RetailcrmAbstractTemplate } abstract protected function buildParams(); + abstract protected function setTemplate(); } diff --git a/retailcrm/lib/templates/RetailcrmBaseTemplate.php b/retailcrm/lib/templates/RetailcrmBaseTemplate.php index b856e8c..9012a9c 100644 --- a/retailcrm/lib/templates/RetailcrmBaseTemplate.php +++ b/retailcrm/lib/templates/RetailcrmBaseTemplate.php @@ -57,14 +57,14 @@ class RetailcrmBaseTemplate extends RetailcrmAbstractTemplate break; } - $this->data = array( + $this->data = [ 'assets' => $this->assets, 'apiUrl' => RetailCRM::API_URL, 'apiKey' => RetailCRM::API_KEY, 'promoVideoUrl' => $promoVideoUrl, 'registerUrl' => $registerUrl, - 'supportEmail' => $supportEmail - ); + 'supportEmail' => $supportEmail, + ]; } /** @@ -72,6 +72,6 @@ class RetailcrmBaseTemplate extends RetailcrmAbstractTemplate */ protected function setTemplate() { - $this->template = "index.tpl"; + $this->template = 'index.tpl'; } } diff --git a/retailcrm/lib/templates/RetailcrmSettingsTemplate.php b/retailcrm/lib/templates/RetailcrmSettingsTemplate.php index 32421a2..a7ac5a1 100644 --- a/retailcrm/lib/templates/RetailcrmSettingsTemplate.php +++ b/retailcrm/lib/templates/RetailcrmSettingsTemplate.php @@ -44,10 +44,10 @@ class RetailcrmSettingsTemplate extends RetailcrmAbstractTemplate * RetailcrmSettingsTemplate constructor. * * @param \Module $module - * @param $smarty - * @param $assets - * @param $settings - * @param $settingsNames + * @param $smarty + * @param $assets + * @param $settings + * @param $settingsNames */ public function __construct(Module $module, $smarty, $assets, $settings, $settingsNames) { @@ -64,7 +64,7 @@ class RetailcrmSettingsTemplate extends RetailcrmAbstractTemplate */ protected function getParams() { - $params = array(); + $params = []; if ($this->module->api) { $params['statusesDefaultExport'] = $this->module->reference->getStatuseDefaultExport(); @@ -103,10 +103,10 @@ class RetailcrmSettingsTemplate extends RetailcrmAbstractTemplate protected function buildParams() { $this->data = array_merge( - array( + [ 'assets' => $this->assets, 'cartsDelays' => $this->module->getSynchronizedCartsTimeSelect(), - ), + ], $this->getParams(), $this->settingsNames, $this->settings @@ -118,6 +118,6 @@ class RetailcrmSettingsTemplate extends RetailcrmAbstractTemplate */ protected function setTemplate() { - $this->template = "settings.tpl"; + $this->template = 'settings.tpl'; } } diff --git a/retailcrm/lib/templates/index.php b/retailcrm/lib/templates/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/lib/templates/index.php +++ b/retailcrm/lib/templates/index.php @@ -1,8 +1,9 @@ 'Icml update URL', 'RetailcrmSyncEvent' => 'History synchronization', 'RetailcrmInventoriesEvent' => 'Inventories uploads', - 'RetailcrmClearLogsEvent' => 'Clearing logs' + 'RetailcrmClearLogsEvent' => 'Clearing logs', ]; const TABS_TO_VALIDATE = [ @@ -101,22 +100,22 @@ class RetailCRM extends Module ]; /** - * @var array $templateErrors + * @var array */ private $templateErrors; /** - * @var array $templateWarnings + * @var array */ private $templateWarnings; /** - * @var array $templateConfirms + * @var array */ private $templateConfirms; /** - * @var array $templateInfos + * @var array */ private $templateInfos; @@ -154,7 +153,7 @@ class RetailCRM extends Module $this->default_country = (int) Configuration::get('PS_COUNTRY_DEFAULT'); $this->apiUrl = Configuration::get(static::API_URL); $this->apiKey = Configuration::get(static::API_KEY); - $this->ps_versions_compliancy = array('min' => '1.6.1.0', 'max' => _PS_VERSION_); + $this->ps_versions_compliancy = ['min' => '1.6.1.0', 'max' => _PS_VERSION_]; $this->psVersion = Tools::substr(_PS_VERSION_, 0, 3); $this->log = RetailcrmLogger::getLogFile(); $this->module_key = 'dff3095326546f5fe8995d9e86288491'; @@ -165,7 +164,7 @@ class RetailCRM extends Module $this->name . '/views'; - if ($this->psVersion == '1.6') { + if ('1.6' == $this->psVersion) { $this->bootstrap = true; $this->use_new_hooks = false; } @@ -184,19 +183,19 @@ class RetailCRM extends Module Shop::setContext(Shop::CONTEXT_ALL); } - return ( - parent::install() && - $this->registerHook('newOrder') && - $this->registerHook('actionOrderStatusPostUpdate') && - $this->registerHook('actionPaymentConfirmation') && - $this->registerHook('actionCustomerAccountAdd') && - $this->registerHook('actionOrderEdited') && - $this->registerHook('actionCarrierUpdate') && - $this->registerHook('header') && - ($this->use_new_hooks ? $this->registerHook('actionCustomerAccountUpdate') : true) && - ($this->use_new_hooks ? $this->registerHook('actionValidateCustomerAddressForm') : true) && - $this->installDB() - ); + return + parent::install() + && $this->registerHook('newOrder') + && $this->registerHook('actionOrderStatusPostUpdate') + && $this->registerHook('actionPaymentConfirmation') + && $this->registerHook('actionCustomerAccountAdd') + && $this->registerHook('actionOrderEdited') + && $this->registerHook('actionCarrierUpdate') + && $this->registerHook('header') + && ($this->use_new_hooks ? $this->registerHook('actionCustomerAccountUpdate') : true) + && ($this->use_new_hooks ? $this->registerHook('actionValidateCustomerAddressForm') : true) + && $this->installDB() + ; } public function hookHeader() @@ -225,50 +224,50 @@ class RetailCRM extends Module $this->integrationModule($api, $clientId, false); } - return parent::uninstall() && - Configuration::deleteByName(static::API_URL) && - Configuration::deleteByName(static::API_KEY) && - Configuration::deleteByName(static::DELIVERY) && - Configuration::deleteByName(static::STATUS) && - Configuration::deleteByName(static::OUT_OF_STOCK_STATUS) && - Configuration::deleteByName(static::PAYMENT) && - Configuration::deleteByName(static::DELIVERY_DEFAULT) && - Configuration::deleteByName(static::PAYMENT_DEFAULT) && - Configuration::deleteByName(static::STATUS_EXPORT) && - Configuration::deleteByName(static::CLIENT_ID) && - Configuration::deleteByName(static::COLLECTOR_ACTIVE) && - Configuration::deleteByName(static::COLLECTOR_KEY) && - Configuration::deleteByName(static::SYNC_CARTS_ACTIVE) && - Configuration::deleteByName(static::SYNC_CARTS_STATUS) && - Configuration::deleteByName(static::SYNC_CARTS_DELAY) && - Configuration::deleteByName(static::UPLOAD_ORDERS) && - Configuration::deleteByName(static::MODULE_LIST_CACHE_CHECKSUM) && - Configuration::deleteByName(static::ENABLE_CORPORATE_CLIENTS) && - Configuration::deleteByName(static::ENABLE_HISTORY_UPLOADS) && - Configuration::deleteByName(static::ENABLE_BALANCES_RECEIVING) && - Configuration::deleteByName(static::ENABLE_ORDER_NUMBER_SENDING) && - Configuration::deleteByName(static::ENABLE_ORDER_NUMBER_RECEIVING) && - Configuration::deleteByName(static::ENABLE_DEBUG_MODE) && - Configuration::deleteByName(static::ENABLE_WEB_JOBS) && - Configuration::deleteByName('RETAILCRM_LAST_SYNC') && - Configuration::deleteByName('RETAILCRM_LAST_ORDERS_SYNC') && - Configuration::deleteByName('RETAILCRM_LAST_CUSTOMERS_SYNC') && - Configuration::deleteByName(RetailcrmJobManager::LAST_RUN_NAME) && - Configuration::deleteByName(RetailcrmJobManager::LAST_RUN_DETAIL_NAME) && - Configuration::deleteByName(RetailcrmCatalogHelper::ICML_INFO_NAME) && - Configuration::deleteByName(RetailcrmJobManager::IN_PROGRESS_NAME) && - Configuration::deleteByName(RetailcrmJobManager::CURRENT_TASK) && - Configuration::deleteByName(RetailcrmCli::CURRENT_TASK_CLI) && - $this->uninstallDB(); + return parent::uninstall() + && Configuration::deleteByName(static::API_URL) + && Configuration::deleteByName(static::API_KEY) + && Configuration::deleteByName(static::DELIVERY) + && Configuration::deleteByName(static::STATUS) + && Configuration::deleteByName(static::OUT_OF_STOCK_STATUS) + && Configuration::deleteByName(static::PAYMENT) + && Configuration::deleteByName(static::DELIVERY_DEFAULT) + && Configuration::deleteByName(static::PAYMENT_DEFAULT) + && Configuration::deleteByName(static::STATUS_EXPORT) + && Configuration::deleteByName(static::CLIENT_ID) + && Configuration::deleteByName(static::COLLECTOR_ACTIVE) + && Configuration::deleteByName(static::COLLECTOR_KEY) + && Configuration::deleteByName(static::SYNC_CARTS_ACTIVE) + && Configuration::deleteByName(static::SYNC_CARTS_STATUS) + && Configuration::deleteByName(static::SYNC_CARTS_DELAY) + && Configuration::deleteByName(static::UPLOAD_ORDERS) + && Configuration::deleteByName(static::MODULE_LIST_CACHE_CHECKSUM) + && Configuration::deleteByName(static::ENABLE_CORPORATE_CLIENTS) + && Configuration::deleteByName(static::ENABLE_HISTORY_UPLOADS) + && Configuration::deleteByName(static::ENABLE_BALANCES_RECEIVING) + && Configuration::deleteByName(static::ENABLE_ORDER_NUMBER_SENDING) + && Configuration::deleteByName(static::ENABLE_ORDER_NUMBER_RECEIVING) + && Configuration::deleteByName(static::ENABLE_DEBUG_MODE) + && Configuration::deleteByName(static::ENABLE_WEB_JOBS) + && Configuration::deleteByName('RETAILCRM_LAST_SYNC') + && Configuration::deleteByName('RETAILCRM_LAST_ORDERS_SYNC') + && Configuration::deleteByName('RETAILCRM_LAST_CUSTOMERS_SYNC') + && Configuration::deleteByName(RetailcrmJobManager::LAST_RUN_NAME) + && Configuration::deleteByName(RetailcrmJobManager::LAST_RUN_DETAIL_NAME) + && Configuration::deleteByName(RetailcrmCatalogHelper::ICML_INFO_NAME) + && Configuration::deleteByName(RetailcrmJobManager::IN_PROGRESS_NAME) + && Configuration::deleteByName(RetailcrmJobManager::CURRENT_TASK) + && Configuration::deleteByName(RetailcrmCli::CURRENT_TASK_CLI) + && $this->uninstallDB(); } public function installDB() { return Db::getInstance()->execute( - 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'retailcrm_abandonedcarts` ( + 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'retailcrm_abandonedcarts` ( `id_cart` INT UNSIGNED UNIQUE NOT NULL, `last_uploaded` DATETIME, - FOREIGN KEY (id_cart) REFERENCES '._DB_PREFIX_.'cart (id_cart) + FOREIGN KEY (id_cart) REFERENCES ' . _DB_PREFIX_ . 'cart (id_cart) ON DELETE CASCADE ON UPDATE CASCADE ) DEFAULT CHARSET=utf8;' @@ -277,7 +276,7 @@ class RetailCRM extends Module public function uninstallDB() { - return Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'retailcrm_abandonedcarts`;'); + return Db::getInstance()->execute('DROP TABLE IF EXISTS `' . _DB_PREFIX_ . 'retailcrm_abandonedcarts`;'); } public function getContent() @@ -288,13 +287,13 @@ class RetailCRM extends Module if (Tools::isSubmit('submit' . $this->name)) { // todo all those vars & ifs to one $command var and check in switch - $jobName = (string)(Tools::getValue(static::RUN_JOB)); - $ordersIds = (string)(Tools::getValue(static::UPLOAD_ORDERS)); - $exportOrders = (int)(Tools::getValue(static::EXPORT_ORDERS)); - $exportCustomers = (int)(Tools::getValue(static::EXPORT_CUSTOMERS)); - $updateSinceId = (bool)(Tools::getValue(static::UPDATE_SINCE_ID)); - $downloadLogs = (bool)(Tools::getValue(static::DOWNLOAD_LOGS)); - $resetJobs = (bool)(Tools::getValue(static::RESET_JOBS)); + $jobName = (string) (Tools::getValue(static::RUN_JOB)); + $ordersIds = (string) (Tools::getValue(static::UPLOAD_ORDERS)); + $exportOrders = (int) (Tools::getValue(static::EXPORT_ORDERS)); + $exportCustomers = (int) (Tools::getValue(static::EXPORT_CUSTOMERS)); + $updateSinceId = (bool) (Tools::getValue(static::UPDATE_SINCE_ID)); + $downloadLogs = (bool) (Tools::getValue(static::DOWNLOAD_LOGS)); + $resetJobs = (bool) (Tools::getValue(static::RESET_JOBS)); if (!empty($ordersIds)) { $output .= $this->uploadOrders(RetailcrmTools::partitionId($ordersIds)); @@ -329,17 +328,18 @@ class RetailCRM extends Module ->setWarnings($this->getWarningMessage()) ->setInformations($this->getInformationMessages()) ->setConfirmations($this->getConfirmationMessages()) - ->render(__FILE__); + ->render(__FILE__) + ; } public function uploadOrders($orderIds) { - if (count($orderIds) > 10) { + if (10 < count($orderIds)) { return $this->displayError($this->l("Can't upload more than 10 orders per request")); } - if (count($orderIds) < 1) { - return $this->displayError($this->l("At least one order ID should be specified")); + if (1 > count($orderIds)) { + return $this->displayError($this->l('At least one order ID should be specified')); } if (!($this->api instanceof RetailcrmProxy)) { @@ -354,7 +354,7 @@ class RetailCRM extends Module $result = ''; $isSuccessful = true; - $skippedOrders = array(); + $skippedOrders = []; RetailcrmExport::$api = $this->api; $receiveOrderNumber = (bool) (Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING)); @@ -398,6 +398,7 @@ class RetailCRM extends Module /** * @param string $jobName + * * @return string */ public function runJob($jobName) @@ -430,12 +431,13 @@ class RetailCRM extends Module public function runJobMultistore($jobName) { - RetailcrmContextSwitcher::runInContext(array($this, 'runJob'), array($jobName)); + RetailcrmContextSwitcher::runInContext([$this, 'runJob'], [$jobName]); } /** * @param int $step * @param string $entity + * * @return bool */ public function export($step, $entity = 'order') @@ -444,8 +446,8 @@ class RetailCRM extends Module return RetailcrmJsonResponse::invalidResponse('This method allow only in ajax mode'); } - $step--; - if ($step < 0) { + --$step; + if (0 > $step) { return RetailcrmJsonResponse::invalidResponse('Invalid request data'); } @@ -458,13 +460,13 @@ class RetailCRM extends Module RetailcrmExport::init(); RetailcrmExport::$api = $api; - if ($entity === 'order') { + if ('order' === $entity) { $stepSize = RetailcrmExport::RETAILCRM_EXPORT_ORDERS_STEP_SIZE_WEB; RetailcrmExport::$ordersOffset = $stepSize; RetailcrmExport::exportOrders($step * $stepSize, $stepSize); - // todo maybe save current step to database - } elseif ($entity === 'customer') { + // todo maybe save current step to database + } elseif ('customer' === $entity) { $stepSize = RetailcrmExport::RETAILCRM_EXPORT_CUSTOMERS_STEP_SIZE_WEB; RetailcrmExport::$customersOffset = $stepSize; @@ -500,7 +502,7 @@ class RetailCRM extends Module return false; } - $name = (string)(Tools::getValue(static::DOWNLOAD_LOGS_NAME)); + $name = (string) (Tools::getValue(static::DOWNLOAD_LOGS_NAME)); if (!empty($name)) { if (false === ($filePath = RetailcrmLogger::checkFileName($name))) { return false; @@ -541,7 +543,7 @@ class RetailCRM extends Module */ public function resetJobs() { - $errors = array(); + $errors = []; try { if (!RetailcrmJobManager::reset()) { $errors[] = 'Job manager internal state was NOT cleared.'; @@ -595,7 +597,7 @@ class RetailCRM extends Module $addressBuilder = new RetailcrmAddressBuilder(); /** @var Address|\AddressCore|array $address */ - $address = array(); + $address = []; if (isset($customerSend['externalId'])) { $customerData = $this->api->customersGet($customerSend['externalId']); @@ -640,7 +642,8 @@ class RetailCRM extends Module $addressBuilder ->setMode(RetailcrmAddressBuilder::MODE_ORDER_DELIVERY) ->setAddressId($cart->id_address_invoice) - ->build(); + ->build() + ; } $customerSend = RetailcrmTools::mergeCustomerAddress($customerSend, $addressBuilder->getDataArray()); @@ -658,7 +661,7 @@ class RetailCRM extends Module public function hookActionValidateCustomerAddressForm($params) { $customer = new Customer($params['cart']->id_customer); - $customerAddress = array('customer' => $customer, 'cart' => $params['cart']); + $customerAddress = ['customer' => $customer, 'cart' => $params['cart']]; return $this->hookActionCustomerAccountUpdate($customerAddress); } @@ -733,7 +736,7 @@ class RetailCRM extends Module } $status = json_decode(Configuration::get(static::STATUS), true); - $receiveOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING)); + $receiveOrderNumber = (bool) (Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING)); if (isset($params['orderStatus'])) { try { @@ -755,10 +758,10 @@ class RetailCRM extends Module if (isset($orderStatus)) { $this->api->ordersEdit( - array( + [ 'externalId' => $params['id_order'], - 'status' => $orderStatus - ) + 'status' => $orderStatus, + ] ); return true; @@ -791,7 +794,7 @@ class RetailCRM extends Module $response = $this->api->ordersGet(RetailcrmTools::getCartOrderExternalId($params['cart'])); - if ($response !== false && isset($response['order'])) { + if (false !== $response && isset($response['order'])) { $externalId = RetailcrmTools::getCartOrderExternalId($params['cart']); } else { if (version_compare(_PS_VERSION_, '1.7.1.0', '>=')) { @@ -800,7 +803,7 @@ class RetailCRM extends Module $id_order = (int) Order::getOrderByCartId((int) $params['cart']->id); } - if ($id_order > 0) { + if (0 < $id_order) { // do not update payment if the order in Cart and OrderPayment aren't the same if ($params['paymentCC']->order_reference) { $order = Order::getByReference($params['paymentCC']->order_reference)->getFirst(); @@ -810,17 +813,17 @@ class RetailCRM extends Module } $response = $this->api->ordersGet($id_order); - if ($response !== false && isset($response['order'])) { + if (false !== $response && isset($response['order'])) { $externalId = $id_order; } } } - if ($externalId === false) { + if (false === $externalId) { return false; } - $status = (round($params['paymentCC']->amount, 2) > 0 ? 'paid' : null); + $status = (0 < round($params['paymentCC']->amount, 2) ? 'paid' : null); $orderCRM = $response['order']; if ($orderCRM && $orderCRM['payments']) { @@ -837,16 +840,16 @@ class RetailCRM extends Module if (isset($updatePayment)) { $this->api->ordersPaymentEdit($updatePayment, 'id'); } else { - $createPayment = array( + $createPayment = [ 'externalId' => $params['paymentCC']->id, - 'amount' => $params['paymentCC']->amount, - 'paidAt' => $params['paymentCC']->date_add, - 'type' => $paymentType, - 'status' => $status, - 'order' => array( + 'amount' => $params['paymentCC']->amount, + 'paidAt' => $params['paymentCC']->date_add, + 'type' => $paymentType, + 'status' => $status, + 'order' => [ 'externalId' => $externalId, - ), - ); + ], + ]; $this->api->ordersPaymentCreate($createPayment); } @@ -867,7 +870,7 @@ class RetailCRM extends Module $consultantCode = (string) Tools::getValue(static::CONSULTANT_SCRIPT); if (!empty($url) && !empty($apiKey)) { - $settings = array( + $settings = [ 'url' => rtrim($url, '/'), 'apiKey' => $apiKey, 'address' => (string) (Tools::getValue(static::API_URL)), @@ -878,24 +881,24 @@ class RetailCRM extends Module 'deliveryDefault' => json_encode(Tools::getValue(static::DELIVERY_DEFAULT)), 'paymentDefault' => json_encode(Tools::getValue(static::PAYMENT_DEFAULT)), 'statusExport' => (string) (Tools::getValue(static::STATUS_EXPORT)), - 'enableCorporate' => (Tools::getValue(static::ENABLE_CORPORATE_CLIENTS) !== false), - 'enableHistoryUploads' => (Tools::getValue(static::ENABLE_HISTORY_UPLOADS) !== false), - 'enableBalancesReceiving' => (Tools::getValue(static::ENABLE_BALANCES_RECEIVING) !== false), - 'enableOrderNumberSending' => (Tools::getValue(static::ENABLE_ORDER_NUMBER_SENDING) !== false), - 'enableOrderNumberReceiving' => (Tools::getValue(static::ENABLE_ORDER_NUMBER_RECEIVING) !== false), - 'debugMode' => (Tools::getValue(static::ENABLE_DEBUG_MODE) !== false), - 'webJobs' => (Tools::getValue(static::ENABLE_WEB_JOBS, true) !== false ? '1' : '0'), - 'collectorActive' => (Tools::getValue(static::COLLECTOR_ACTIVE) !== false), + 'enableCorporate' => (false !== Tools::getValue(static::ENABLE_CORPORATE_CLIENTS)), + 'enableHistoryUploads' => (false !== Tools::getValue(static::ENABLE_HISTORY_UPLOADS)), + 'enableBalancesReceiving' => (false !== Tools::getValue(static::ENABLE_BALANCES_RECEIVING)), + 'enableOrderNumberSending' => (false !== Tools::getValue(static::ENABLE_ORDER_NUMBER_SENDING)), + 'enableOrderNumberReceiving' => (false !== Tools::getValue(static::ENABLE_ORDER_NUMBER_RECEIVING)), + 'debugMode' => (false !== Tools::getValue(static::ENABLE_DEBUG_MODE)), + 'webJobs' => (false !== Tools::getValue(static::ENABLE_WEB_JOBS, true) ? '1' : '0'), + 'collectorActive' => (false !== Tools::getValue(static::COLLECTOR_ACTIVE)), 'collectorKey' => (string) (Tools::getValue(static::COLLECTOR_KEY)), 'clientId' => Configuration::get(static::CLIENT_ID), - 'synchronizeCartsActive' => (Tools::getValue(static::SYNC_CARTS_ACTIVE) !== false), + 'synchronizeCartsActive' => (false !== Tools::getValue(static::SYNC_CARTS_ACTIVE)), 'synchronizedCartStatus' => (string) (Tools::getValue(static::SYNC_CARTS_STATUS)), - 'synchronizedCartDelay' => (string) (Tools::getValue(static::SYNC_CARTS_DELAY)) - ); + 'synchronizedCartDelay' => (string) (Tools::getValue(static::SYNC_CARTS_DELAY)), + ]; $output .= $this->validateForm($settings, $output); - if ($output === '') { + if ('' === $output) { Configuration::updateValue(static::API_URL, $settings['url']); Configuration::updateValue(static::API_KEY, $settings['apiKey']); Configuration::updateValue(static::DELIVERY, $settings['delivery']); @@ -926,7 +929,7 @@ class RetailCRM extends Module $this->api = new RetailcrmProxy($this->apiUrl, $this->apiKey, $this->log); $this->reference = new RetailcrmReferences($this->api); - if ($this->isRegisteredInHook('actionPaymentCCAdd') == 0) { + if (0 == $this->isRegisteredInHook('actionPaymentCCAdd')) { $this->registerHook('actionPaymentCCAdd'); } } @@ -955,9 +958,9 @@ class RetailCRM extends Module * * @param \RetailcrmProxy $apiClient * @param string $clientId - * @param boolean $active + * @param bool $active * - * @return boolean + * @return bool */ private function integrationModule($apiClient, $clientId, $active = true) { @@ -966,15 +969,15 @@ class RetailCRM extends Module $integrationCode = 'prestashop'; $name = 'PrestaShop'; $accountUrl = $scheme . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; - $configuration = array( + $configuration = [ 'clientId' => $clientId, 'code' => $integrationCode . '-' . $clientId, 'integrationCode' => $integrationCode, 'active' => $active, 'name' => $name, 'logo' => $logo, - 'accountUrl' => $accountUrl - ); + 'accountUrl' => $accountUrl, + ]; $response = $apiClient->integrationModulesEdit($configuration); if (!$response) { @@ -1006,7 +1009,7 @@ class RetailCRM extends Module $response = $api->apiVersions(); - if ($response !== false && isset($response['versions']) && !empty($response['versions'])) { + if (false !== $response && isset($response['versions']) && !empty($response['versions'])) { foreach ($response['versions'] as $version) { if ($version == static::LATEST_API_VERSION || Tools::substr($version, 0, 1) == static::LATEST_API_VERSION @@ -1042,7 +1045,7 @@ class RetailCRM extends Module */ private function validateCartStatus($statuses, $statusExport, $cartStatus) { - if ($cartStatus != '' && ($cartStatus == $statusExport || stripos($statuses, $cartStatus))) { + if ('' != $cartStatus && ($cartStatus == $statusExport || stripos($statuses, $cartStatus))) { return false; } @@ -1060,7 +1063,7 @@ class RetailCRM extends Module { $data = json_decode($statuses, true); - if (json_last_error() != JSON_ERROR_NONE || !is_array($data)) { + if (JSON_ERROR_NONE != json_last_error() || !is_array($data)) { return true; } @@ -1075,29 +1078,29 @@ class RetailCRM extends Module public function validateStoredSettings() { - $output = array(); - $checkApiMethods = array( + $output = []; + $checkApiMethods = [ 'delivery' => 'getApiDeliveryTypes', 'statuses' => 'getApiStatuses', 'payment' => 'getApiPaymentTypes', - ); + ]; foreach (self::TABS_TO_VALIDATE as $tabName => $settingName) { $storedValues = Tools::getIsset($settingName) ? Tools::getValue($settingName) : json_decode(Configuration::get($settingName), true); - if ($storedValues !== false && $storedValues !== null) { + if (false !== $storedValues && null !== $storedValues) { if (!$this->validateMappingSelected($storedValues)) { $output[] = $tabName; } else { if (array_key_exists($tabName, $checkApiMethods)) { - $crmValues = call_user_func(array($this->reference, $checkApiMethods[$tabName])); + $crmValues = call_user_func([$this->reference, $checkApiMethods[$tabName]]); $crmCodes = array_column($crmValues, 'id_option'); if (!empty(array_diff($storedValues, $crmCodes))) { $output[] = $tabName; - }; + } } } } @@ -1139,8 +1142,8 @@ class RetailCRM extends Module if (!$icmlInfo || !isset($icmlInfo['lastGenerated'])) { $urlConfiguredAt = RetailcrmTools::getConfigurationCreatedAtByName(self::API_KEY); - if ($urlConfiguredAt instanceof DateTime) { - $now = new DateTime(); + if ($urlConfiguredAt instanceof DateTimeImmutable) { + $now = new DateTimeImmutable(); /** @var DateInterval $diff */ $diff = $urlConfiguredAt->diff($now); @@ -1148,7 +1151,7 @@ class RetailCRM extends Module return false; } } - } elseif ($icmlInfo['isOutdated'] || (isset($icmlInfo['isUrlActual']) && $icmlInfo['isUrlActual'] === false)) { + } elseif ($icmlInfo['isOutdated'] || !$icmlInfo['isUrlActual']) { return false; } @@ -1162,7 +1165,7 @@ class RetailCRM extends Module */ private function validateCatalogMultistore() { - $results = RetailcrmContextSwitcher::runInContext(array($this, 'validateCatalog')); + $results = RetailcrmContextSwitcher::runInContext([$this, 'validateCatalog']); $results = array_filter($results, function ($item) { return !$item; }); @@ -1182,7 +1185,7 @@ class RetailCRM extends Module { if (!RetailcrmTools::validateCrmAddress($settings['url']) || !Validate::isGenericName($settings['url'])) { $output .= $this->displayError($this->l('Invalid or empty crm address')); - } elseif (!$settings['apiKey'] || $settings['apiKey'] == '') { + } elseif (!$settings['apiKey'] || '' == $settings['apiKey']) { $output .= $this->displayError($this->l('Invalid or empty crm api token')); } elseif (!$this->validateApiVersion($settings)) { $output .= $this->displayError($this->l('The selected version of the API is unavailable')); @@ -1234,7 +1237,7 @@ class RetailCRM extends Module private static function requireModulesCache() { if (file_exists(static::getModulesCache())) { - return require_once(static::getModulesCache()); + return require_once static::getModulesCache(); } return false; @@ -1257,7 +1260,7 @@ class RetailCRM extends Module $cacheDir = _PS_ROOT_DIR_ . '/cache'; - if (realpath($cacheDir) !== false && is_dir($cacheDir)) { + if (false !== realpath($cacheDir) && is_dir($cacheDir)) { return $cacheDir . '/retailcrm_modules_cache.php'; } @@ -1274,35 +1277,35 @@ class RetailCRM extends Module $syncCartsDelay = (string) (Configuration::get(static::SYNC_CARTS_DELAY)); // Use 15 minutes as default interval but don't change immediate interval to it if user already made decision - if (empty($syncCartsDelay) && $syncCartsDelay !== "0") { - $syncCartsDelay = "900"; + if (empty($syncCartsDelay) && '0' !== $syncCartsDelay) { + $syncCartsDelay = '900'; } - return array( - 'url' => (string)(Configuration::get(static::API_URL)), - 'apiKey' => (string)(Configuration::get(static::API_KEY)), + return [ + 'url' => (string) (Configuration::get(static::API_URL)), + 'apiKey' => (string) (Configuration::get(static::API_KEY)), 'delivery' => json_decode(Configuration::get(static::DELIVERY), true), 'status' => json_decode(Configuration::get(static::STATUS), true), 'outOfStockStatus' => json_decode(Configuration::get(static::OUT_OF_STOCK_STATUS), true), 'payment' => json_decode(Configuration::get(static::PAYMENT), true), 'deliveryDefault' => json_decode(Configuration::get(static::DELIVERY_DEFAULT), true), 'paymentDefault' => json_decode(Configuration::get(static::PAYMENT_DEFAULT), true), - 'statusExport' => (string)(Configuration::get(static::STATUS_EXPORT)), + 'statusExport' => (string) (Configuration::get(static::STATUS_EXPORT)), 'collectorActive' => (Configuration::get(static::COLLECTOR_ACTIVE)), - 'collectorKey' => (string)(Configuration::get(static::COLLECTOR_KEY)), + 'collectorKey' => (string) (Configuration::get(static::COLLECTOR_KEY)), 'clientId' => Configuration::get(static::CLIENT_ID), 'synchronizeCartsActive' => (Configuration::get(static::SYNC_CARTS_ACTIVE)), - 'synchronizedCartStatus' => (string)(Configuration::get(static::SYNC_CARTS_STATUS)), + 'synchronizedCartStatus' => (string) (Configuration::get(static::SYNC_CARTS_STATUS)), 'synchronizedCartDelay' => $syncCartsDelay, - 'consultantScript' => (string)(Configuration::get(static::CONSULTANT_SCRIPT)), - 'enableCorporate' => (bool)(Configuration::get(static::ENABLE_CORPORATE_CLIENTS)), - 'enableHistoryUploads' => (bool)(Configuration::get(static::ENABLE_HISTORY_UPLOADS)), - 'enableBalancesReceiving' => (bool)(Configuration::get(static::ENABLE_BALANCES_RECEIVING)), - 'enableOrderNumberSending' => (bool)(Configuration::get(static::ENABLE_ORDER_NUMBER_SENDING)), - 'enableOrderNumberReceiving' => (bool)(Configuration::get(static::ENABLE_ORDER_NUMBER_RECEIVING)), + 'consultantScript' => (string) (Configuration::get(static::CONSULTANT_SCRIPT)), + 'enableCorporate' => (bool) (Configuration::get(static::ENABLE_CORPORATE_CLIENTS)), + 'enableHistoryUploads' => (bool) (Configuration::get(static::ENABLE_HISTORY_UPLOADS)), + 'enableBalancesReceiving' => (bool) (Configuration::get(static::ENABLE_BALANCES_RECEIVING)), + 'enableOrderNumberSending' => (bool) (Configuration::get(static::ENABLE_ORDER_NUMBER_SENDING)), + 'enableOrderNumberReceiving' => (bool) (Configuration::get(static::ENABLE_ORDER_NUMBER_RECEIVING)), 'debugMode' => RetailcrmTools::isDebug(), - 'webJobs' => RetailcrmTools::isWebJobsEnabled() - ); + 'webJobs' => RetailcrmTools::isWebJobsEnabled(), + ]; } /** @@ -1312,7 +1315,7 @@ class RetailCRM extends Module */ public static function getSettingsNames() { - return array( + return [ 'urlName' => static::API_URL, 'apiKeyName' => static::API_KEY, 'deliveryName' => static::DELIVERY, @@ -1338,8 +1341,8 @@ class RetailCRM extends Module 'enableOrderNumberReceivingName' => static::ENABLE_ORDER_NUMBER_RECEIVING, 'debugModeName' => static::ENABLE_DEBUG_MODE, 'webJobsName' => static::ENABLE_WEB_JOBS, - 'jobsNames' => static::JOBS_NAMES - ); + 'jobsNames' => static::JOBS_NAMES, + ]; } /** @@ -1354,7 +1357,7 @@ class RetailCRM extends Module $calculatedHash = md5(implode('#', Module::getModulesDirOnDisk(true))); if ($storedHash != $calculatedHash) { - $serializedModules = array(); + $serializedModules = []; static::$moduleListCache = Module::getModulesOnDisk(true); foreach (static::$moduleListCache as $module) { @@ -1373,13 +1376,13 @@ class RetailCRM extends Module $modulesList = static::requireModulesCache(); - if ($modulesList === false) { + if (false === $modulesList) { Configuration::updateValue(static::MODULE_LIST_CACHE_CHECKSUM, 'not exist'); return static::getCachedCmsModulesList(); } - static::$moduleListCache = array(); + static::$moduleListCache = []; foreach ($modulesList as $serializedModule) { $deserialized = json_decode($serializedModule); @@ -1416,7 +1419,7 @@ class RetailCRM extends Module { $file = fopen(static::getModulesCache(), 'w+'); - if ($file !== false) { + if (false !== $file) { fwrite($file, ' '900', - 'name' => $this->l('After 15 minutes') - ), - array( + 'name' => $this->l('After 15 minutes'), + ], + [ 'id_option' => '1800', - 'name' => $this->l('After 30 minutes') - ), - array( + 'name' => $this->l('After 30 minutes'), + ], + [ 'id_option' => '2700', - 'name' => $this->l('After 45 minute') - ), - array( + 'name' => $this->l('After 45 minute'), + ], + [ 'id_option' => '3600', - 'name' => $this->l('After 1 hour') - ), - ); + 'name' => $this->l('After 1 hour'), + ], + ]; } /** @@ -1458,20 +1461,20 @@ class RetailCRM extends Module */ private function initializeTemplateMessages() { - if (is_null($this->templateErrors)) { - $this->templateErrors = array(); + if (null === $this->templateErrors) { + $this->templateErrors = []; } - if (is_null($this->templateWarnings)) { - $this->templateWarnings = array(); + if (null === $this->templateWarnings) { + $this->templateWarnings = []; } - if (is_null($this->templateConfirms)) { - $this->templateConfirms = array(); + if (null === $this->templateConfirms) { + $this->templateConfirms = []; } - if (is_null($this->templateErrors)) { - $this->templateInfos = array(); + if (null === $this->templateErrors) { + $this->templateInfos = []; } } @@ -1483,7 +1486,7 @@ class RetailCRM extends Module protected function getErrorMessages() { if (empty($this->templateErrors)) { - return array(); + return []; } return $this->templateErrors; @@ -1497,7 +1500,7 @@ class RetailCRM extends Module protected function getWarningMessage() { if (empty($this->templateWarnings)) { - return array(); + return []; } return $this->templateWarnings; @@ -1511,7 +1514,7 @@ class RetailCRM extends Module protected function getInformationMessages() { if (empty($this->templateInfos)) { - return array(); + return []; } return $this->templateInfos; @@ -1525,7 +1528,7 @@ class RetailCRM extends Module protected function getConfirmationMessages() { if (empty($this->templateConfirms)) { - return array(); + return []; } return $this->templateConfirms; diff --git a/retailcrm/translations/es.php b/retailcrm/translations/es.php index b6cce43..213efe3 100644 --- a/retailcrm/translations/es.php +++ b/retailcrm/translations/es.php @@ -1,7 +1,7 @@ retailcrm_9b1e2d4b35252401dbdab3cbad2735c4'] = 'Simla.com'; $_MODULE['<{retailcrm}prestashop>retailcrm_5e36a81536959d8cde52246dd15a6fca'] = 'Módulo de integración para Simla.com'; $_MODULE['<{retailcrm}prestashop>retailcrm_876f23178c29dc2552c0b48bf23cd9bd'] = '¿Está seguro de que desea eliminar el módulo?'; diff --git a/retailcrm/translations/index.php b/retailcrm/translations/index.php index e71af0e..7e187a2 100644 --- a/retailcrm/translations/index.php +++ b/retailcrm/translations/index.php @@ -1 +1,3 @@ -retailcrm_9b1e2d4b35252401dbdab3cbad2735c4'] = 'Simla.com'; $_MODULE['<{retailcrm}prestashop>retailcrm_5e36a81536959d8cde52246dd15a6fca'] = 'Интеграционный модуль для Simla.com'; $_MODULE['<{retailcrm}prestashop>retailcrm_876f23178c29dc2552c0b48bf23cd9bd'] = 'Вы уверены, что хотите удалить модуль?'; diff --git a/retailcrm/upgrade/index.php b/retailcrm/upgrade/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/upgrade/index.php +++ b/retailcrm/upgrade/index.php @@ -1,8 +1,9 @@ execute( - 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'retailcrm_abandonedcarts` ( + 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'retailcrm_abandonedcarts` ( `id_cart` INT UNSIGNED UNIQUE NOT NULL, `last_uploaded` DATETIME, - FOREIGN KEY (id_cart) REFERENCES '._DB_PREFIX_.'cart (id_cart) + FOREIGN KEY (id_cart) REFERENCES ' . _DB_PREFIX_ . 'cart (id_cart) ON DELETE CASCADE ON UPDATE CASCADE ) DEFAULT CHARSET=utf8;' diff --git a/retailcrm/upgrade/upgrade-3.0.2.php b/retailcrm/upgrade/upgrade-3.0.2.php index b4fc20f..a47d8bb 100644 --- a/retailcrm/upgrade/upgrade-3.0.2.php +++ b/retailcrm/upgrade/upgrade-3.0.2.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - if (!defined('_PS_VERSION_')) { exit; } diff --git a/retailcrm/upgrade/upgrade-3.3.0.php b/retailcrm/upgrade/upgrade-3.3.0.php index 10ceeed..c96b2f2 100644 --- a/retailcrm/upgrade/upgrade-3.3.0.php +++ b/retailcrm/upgrade/upgrade-3.3.0.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - if (!defined('_PS_VERSION_')) { exit; } @@ -75,13 +74,13 @@ function retailcrm_upgrade_recursive_copy($src, $dst, $childFolder = '') mkdir($dst); } - if ($childFolder != '') { + if ('' != $childFolder) { if (!file_exists($dst . '/' . $childFolder)) { mkdir($dst . '/' . $childFolder); } while (false !== ($file = readdir($dir))) { - if (($file != '.') && ($file != '..')) { + if (('.' != $file) && ('..' != $file)) { if (is_dir($src . '/' . $file)) { retailcrm_upgrade_recursive_copy($src . '/' . $file, $dst . '/' . $childFolder . '/' . $file); } else { @@ -91,7 +90,7 @@ function retailcrm_upgrade_recursive_copy($src, $dst, $childFolder = '') } } else { while (false !== ($file = readdir($dir))) { - if (($file != '.') && ($file != '..')) { + if (('.' != $file) && ('..' != $file)) { if (is_dir($src . '/' . $file)) { retailcrm_upgrade_recursive_copy($src . '/' . $file, $dst . '/' . $file); } else { diff --git a/retailcrm/upgrade/upgrade-3.3.2.php b/retailcrm/upgrade/upgrade-3.3.2.php index 5ae1d0b..e492f8c 100644 --- a/retailcrm/upgrade/upgrade-3.3.2.php +++ b/retailcrm/upgrade/upgrade-3.3.2.php @@ -35,7 +35,6 @@ * Don't forget to prefix your containers with your own identifier * to avoid any conflicts with others containers. */ - if (!defined('_PS_VERSION_')) { exit; } @@ -114,8 +113,8 @@ function upgrade_module_3_3_2($module) } if (!$response->isSuccessful() - || $response['siteAccess'] !== 'access_selective' - || count($response['sitesAvailable']) !== 1 + || 'access_selective' !== $response['siteAccess'] + || 1 !== count($response['sitesAvailable']) || !in_array('/api/reference/sites', $response['credentials']) || !in_array('/api/reference/sites/{code}/edit', $response['credentials']) ) { diff --git a/retailcrm/views/css/index.php b/retailcrm/views/css/index.php index 6a1c957..63eec81 100644 --- a/retailcrm/views/css/index.php +++ b/retailcrm/views/css/index.php @@ -1,8 +1,9 @@ corporateCustomer ->setDataCrm($this->getDataCrm()) - ->build(); + ->build() + ; $result = new RetailcrmCustomerBuilderResult(null, null); @@ -28,7 +29,8 @@ class RetailcrmCorporateCustomerBuilderTest extends RetailcrmTestCase $this->corporateCustomer ->setDataCrm($this->getDataCrm()) - ->build(); + ->build() + ; $builtCustomer = $this->corporateCustomer->getData()->getCustomer(); $builtAddress = $this->corporateCustomer->getData()->getCustomerAddress(); @@ -49,12 +51,13 @@ class RetailcrmCorporateCustomerBuilderTest extends RetailcrmTestCase ->setCustomer($this->getDataBuilder()) ->setCompanyName('Test') ->setCompanyInn(5666) - ->build(); + ->build() + ; $customerResult = $this->corporateCustomer->getData()->getCustomer(); $this->assertEquals('April', $customerResult->firstname); $this->assertEquals('Iphone', $customerResult->lastname); - $this->assertEquals(false, $customerResult->newsletter); + $this->assertFalse($customerResult->newsletter); $this->assertEquals('1997-04-09', $customerResult->birthday); $this->assertEquals(2, $customerResult->id_gender); $this->assertEquals('hello@world.ru', $customerResult->email); @@ -67,44 +70,46 @@ class RetailcrmCorporateCustomerBuilderTest extends RetailcrmTestCase $this->assertEquals(5666, $addressResult->vat_number); } - private function getDataBuilder() { - return array( + private function getDataBuilder() + { + return [ 'type' => 'customer_corporate', 'id' => 9090, 'nickName' => 'TestName', - 'mainAddress' => array( + 'mainAddress' => [ 'id' => 4001, - 'name' => 'Test' - ), + 'name' => 'Test', + ], 'createdAt' => '2020-02-17 07:44:31', 'vip' => false, 'bad' => false, 'site' => 'opencart', - 'tags' => array(), + 'tags' => [], 'marginSumm' => 0, 'totalSumm' => 0, 'averageSumm' => 0, 'ordersCount' => 0, 'costSumm' => 0, - 'customFields' => array(), + 'customFields' => [], 'personalDiscount' => 0, - 'mainCustomerContact' => array( + 'mainCustomerContact' => [ 'id' => 37, - 'customer' => array( - 'id' => 9089 - ), - 'companies' => array() - ), - 'mainCompany' => array( + 'customer' => [ + 'id' => 9089, + ], + 'companies' => [], + ], + 'mainCompany' => [ 'id' => 34, 'name' => 'Test', - 'contragentInn' => 5666 - ) - ); + 'contragentInn' => 5666, + ], + ]; } - private function getDataCrm() { - return array( + private function getDataCrm() + { + return [ 'type' => 'customer', 'id' => 9000, 'externalId' => '1777754', @@ -113,32 +118,32 @@ class RetailcrmCorporateCustomerBuilderTest extends RetailcrmTestCase 'vip' => true, 'bad' => true, 'site' => '127-0-0-1-8080', - 'contragent' => array( - 'contragentType' => 'individual' - ), - 'tags' => array(), + 'contragent' => [ + 'contragentType' => 'individual', + ], + 'subscribed' => false, + 'tags' => [], 'marginSumm' => 0, 'totalSumm' => 0, 'averageSumm' => 0, 'ordersCount' => 0, 'costSumm' => 0, - 'customFields' => array(), + 'customFields' => [], 'personalDiscount' => 0, - 'address' => array( + 'address' => [ 'id' => 9718, 'countryIso' => 'RU', 'region' => 'Moscow', 'city' => 'г. Москва', 'index' => '344004', - 'text' => 'MAY' - ), - 'segments' => array(), + 'text' => 'MAY', + ], + 'segments' => [], 'firstName' => 'April', 'lastName' => 'Iphone', 'email' => 'hello@world.ru', 'sex' => 'female', - 'birthday' =>'1997-04-09' - ); + 'birthday' => '1997-04-09', + ]; } } - diff --git a/tests/RetailcrmCustomerAddressBuilderTest.php b/tests/RetailcrmCustomerAddressBuilderTest.php index 91afa51..838223d 100644 --- a/tests/RetailcrmCustomerAddressBuilderTest.php +++ b/tests/RetailcrmCustomerAddressBuilderTest.php @@ -5,7 +5,7 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase protected $customerAddress; protected $customer; - public function setUp() + protected function setUp() { parent::setUp(); } @@ -16,7 +16,8 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase $this->customerAddress ->setDataCrm($this->getDataBuilder()) - ->build(); + ->build() + ; $this->assertNotEmpty($this->customerAddress->getData()); } @@ -27,7 +28,8 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase $this->customerAddress ->setCustomerAddress(new AddressCore(9999)) - ->build(); + ->build() + ; $this->assertNotEmpty($this->customerAddress->getData()); } @@ -41,7 +43,8 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase ->setFirstName('Test') ->setLastName('Test2') ->setPhone('+7999999999') - ->build(); + ->build() + ; $addressResult = $this->customerAddress->getData(); $this->assertEquals('Test', $addressResult->firstname); @@ -61,7 +64,8 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase ->setFirstName('Test') ->setLastName('Test2') ->setPhone('+7999999999') - ->build(); + ->build() + ; $addressResult = $this->customerAddress->getData(); $this->customerAddress @@ -69,7 +73,8 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase ->setDataCrm($this->getDataBuilderOverride()) ->setFirstName('Test override') ->setPhone('+7111111111') - ->build(); + ->build() + ; $addressResultOverridden = $this->customerAddress->getData(); $this->assertEquals('Test override', $addressResultOverridden->firstname); @@ -81,24 +86,24 @@ class RetailcrmCustomerAddressBuilderTest extends RetailcrmTestCase $this->assertEquals('+7111111111', $addressResultOverridden->phone); } - private function getDataBuilder() { - return array( + private function getDataBuilder() + { + return [ 'id' => 9718, 'countryIso' => 'RU', 'region' => 'Moscow', 'city' => 'г. Москва', 'index' => '344004', - 'text' => 'MAY' - ); + 'text' => 'MAY', + ]; } private function getDataBuilderOverride() { - return array( + return [ 'id' => 9718, 'city' => 'г. Москва Override', 'index' => '444444', - ); + ]; } } - diff --git a/tests/RetailcrmCustomerBuilderTest.php b/tests/RetailcrmCustomerBuilderTest.php index aad9acb..c117021 100644 --- a/tests/RetailcrmCustomerBuilderTest.php +++ b/tests/RetailcrmCustomerBuilderTest.php @@ -4,7 +4,7 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase { protected $customer; - public function setUp() + protected function setUp() { parent::setUp(); } @@ -15,7 +15,8 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase $this->customer ->setDataCrm($this->getDataCrm()) - ->build(); + ->build() + ; $result = new RetailcrmCustomerBuilderResult(null, null); @@ -28,7 +29,8 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase $this->customer ->setCustomer(new Customer(9719)) - ->build(); + ->build() + ; $this->assertNotEmpty($this->customer->getData()); } @@ -39,7 +41,8 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase $this->customer ->setDataCrm($this->getDataCrm()) - ->build(); + ->build() + ; $builtCustomer = $this->customer->getData()->getCustomer(); $builtAddress = $this->customer->getData()->getCustomerAddress(); @@ -57,7 +60,7 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase $this->customer->buildAddress(); - $this->assertEquals(null, $this->customer->getData()->getCustomerAddress()); + $this->assertNull($this->customer->getData()->getCustomerAddress()); } public function testCorrectDataCustomer() @@ -66,13 +69,14 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase $this->customer ->setDataCrm($this->getDataCrm()) - ->build(); + ->build() + ; $customerResult = $this->customer->getData()->getCustomer(); $this->assertEquals('April', $customerResult->firstname); $this->assertEquals('Iphone', $customerResult->lastname); - $this->assertEquals(false, $customerResult->newsletter); + $this->assertFalse($customerResult->newsletter); $this->assertEquals('1997-04-09', $customerResult->birthday); $this->assertEquals(2, $customerResult->id_gender); $this->assertEquals('hello@world.ru', $customerResult->email); @@ -83,8 +87,9 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase $this->assertEquals('г. Москва', $addressResult->city); } - private function getDataCrm() { - return array( + private function getDataCrm() + { + return [ 'type' => 'customer', 'id' => 9000, 'externalId' => '1777754', @@ -93,32 +98,32 @@ class RetailcrmCustomerBuilderTest extends RetailcrmTestCase 'vip' => true, 'bad' => true, 'site' => '127-0-0-1-8080', - 'contragent' => array( - 'contragentType' => 'individual' - ), - 'tags' => array(), + 'contragent' => [ + 'contragentType' => 'individual', + ], + 'subscribed' => false, + 'tags' => [], 'marginSumm' => 0, 'totalSumm' => 0, 'averageSumm' => 0, 'ordersCount' => 0, 'costSumm' => 0, - 'customFields' => array(), + 'customFields' => [], 'personalDiscount' => 0, - 'address' => array( + 'address' => [ 'id' => 9718, 'countryIso' => 'RU', 'region' => 'Moscow', 'city' => 'г. Москва', 'index' => '344004', - 'text' => 'MAY' - ), - 'segments' => array(), + 'text' => 'MAY', + ], + 'segments' => [], 'firstName' => 'April', 'lastName' => 'Iphone', 'email' => 'hello@world.ru', 'sex' => 'female', - 'birthday' =>'1997-04-09' - ); + 'birthday' => '1997-04-09', + ]; } } - diff --git a/tests/RetailcrmOrderBuilderTest.php b/tests/RetailcrmOrderBuilderTest.php index b2cfa26..b5be4e8 100644 --- a/tests/RetailcrmOrderBuilderTest.php +++ b/tests/RetailcrmOrderBuilderTest.php @@ -2,7 +2,7 @@ class RetailcrmOrderBuilderTest extends RetailcrmTestCase { - public function setUp() + protected function setUp() { parent::setUp(); } @@ -39,22 +39,22 @@ class RetailcrmOrderBuilderTest extends RetailcrmTestCase */ private function getDataItemInitialPriceZero() { - return array( + return [ 'id' => 160, 'initialPrice' => 0, 'createdAt' => '2018-01-01 00:00:00', 'quantity' => 1, 'status' => 'new', - 'offer' => array( + 'offer' => [ 'id' => 1, 'externalId' => 1, 'xmlId' => '1', 'name' => 'Test name', - 'vatRate' => 'none' - ), - 'properties' => array(), - 'purchasePrice' => 50 - ); + 'vatRate' => 'none', + ], + 'properties' => [], + 'purchasePrice' => 50, + ]; } /** @@ -62,7 +62,7 @@ class RetailcrmOrderBuilderTest extends RetailcrmTestCase */ private function getDataOrder() { - $order = array( + $order = [ 'slug' => 1, 'id' => 1, 'number' => '1C', @@ -81,38 +81,38 @@ class RetailcrmOrderBuilderTest extends RetailcrmTestCase 'phone' => '80000000000', 'call' => false, 'expired' => false, - 'customer' => array( - 'segments' => array(), + 'customer' => [ + 'segments' => [], 'id' => 1, 'externalId' => '777', 'type' => 'customer', 'firstName' => 'Test', 'lastName' => 'Test', 'email' => 'email@test.ru', - 'phones' => array( - array( - 'number' => '111111111111111' - ), - array( - 'number' => '+7111111111' - ) - ), - 'address' => array( + 'phones' => [ + [ + 'number' => '111111111111111', + ], + [ + 'number' => '+7111111111', + ], + ], + 'address' => [ 'id_customer' => 2222, 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Test region', 'city' => 'Test', - 'text' => 'Test text address' - ), + 'text' => 'Test text address', + ], 'createdAt' => '2018-01-01 00:00:00', 'managerId' => 1, 'vip' => false, 'bad' => false, 'site' => 'test-com', - 'contragent' => array( - 'contragentType' => 'individual' - ), + 'contragent' => [ + 'contragentType' => 'individual', + ], 'personalDiscount' => 0, 'cumulativeDiscount' => 0, 'marginSumm' => 58654, @@ -120,61 +120,60 @@ class RetailcrmOrderBuilderTest extends RetailcrmTestCase 'averageSumm' => 15387.25, 'ordersCount' => 4, 'costSumm' => 101, - 'customFields' => array( - 'custom' => 'test' - ) - ), - 'contragent' => array(), - 'delivery' => array( + 'customFields' => [ + 'custom' => 'test', + ], + ], + 'contragent' => [], + 'delivery' => [ 'code' => 'delivery', 'cost' => 100, 'netCost' => 0, - 'address' => array( + 'address' => [ 'id_customer' => 2222, 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Test region', 'city' => 'Test', - 'text' => 'Test text address' - ) - ), + 'text' => 'Test text address', + ], + ], 'site' => 'test-com', 'status' => 'new', - 'items' => array( - array( + 'items' => [ + [ 'id' => 160, 'initialPrice' => 100, 'createdAt' => '2018-01-01 00:00:00', 'quantity' => 1, 'status' => 'new', - 'offer' => array( + 'offer' => [ 'id' => 1, 'externalId' => 1, 'xmlId' => '1', 'name' => 'Test name', - 'vatRate' => 'none' - ), - 'properties' => array(), - 'purchasePrice' => 50 - ), - ), + 'vatRate' => 'none', + ], + 'properties' => [], + 'purchasePrice' => 50, + ], + ], 'fromApi' => false, 'length' => 0, 'width' => 0, 'height' => 0, 'shipmentStore' => 'main', 'shipped' => false, - 'customFields' => array(), - 'uploadedToExternalStoreSystem' => false - ); + 'customFields' => [], + 'uploadedToExternalStoreSystem' => false, + ]; - $order['payments'][] = array( + $order['payments'][] = [ 'id' => 97, 'type' => 'cheque', - 'amount' => 210 - ); + 'amount' => 210, + ]; return $order; } } - diff --git a/tests/RetailcrmTest.php b/tests/RetailcrmTest.php index 6f55c39..aa79598 100644 --- a/tests/RetailcrmTest.php +++ b/tests/RetailcrmTest.php @@ -5,7 +5,7 @@ class RetailCRMTest extends RetailcrmTestCase private $retailcrmModule; private $apiMock; - public function setUp() + protected function setUp() { parent::setUp(); @@ -22,7 +22,7 @@ class RetailCRMTest extends RetailcrmTestCase return $this->getMockBuilder('RetailcrmProxy') ->disableOriginalConstructor() ->setMethods( - array( + [ 'customersCreate', 'customersEdit', 'customersGet', @@ -30,9 +30,10 @@ class RetailCRMTest extends RetailcrmTestCase 'ordersEdit', 'ordersGet', 'ordersPaymentEdit', - 'ordersPaymentCreate' - ) - ); + 'ordersPaymentCreate', + ] + ) + ; } public function testUploadOrders() @@ -44,19 +45,19 @@ class RetailCRMTest extends RetailcrmTestCase $updReference = 'test'; $this->apiMock->expects($this->any())->method('ordersGet')->willReturn(new RetailcrmApiResponse( 200, - json_encode(array( + json_encode([ 'success' => true, - 'order' => array(), - )) + 'order' => [], + ]) )); $this->apiMock->expects($this->any())->method('ordersCreate')->willReturn(new RetailcrmApiResponse( 200, - json_encode(array( + json_encode([ 'success' => true, - 'order' => array( + 'order' => [ 'number' => $updReference, - ), - )) + ], + ]) )); Configuration::updateValue(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING, false); @@ -75,7 +76,7 @@ class RetailCRMTest extends RetailcrmTestCase public function testHookActionCustomerAccountAdd() { $newCustomer = new Customer(1); - $params = array('newCustomer' => $newCustomer); + $params = ['newCustomer' => $newCustomer]; $this->assertTrue($this->retailcrmModule->hookActionCustomerAccountAdd($params)); } @@ -83,7 +84,7 @@ class RetailCRMTest extends RetailcrmTestCase public function testHookActionCustomerAccountUpdate() { $customer = new Customer(1); - $params = array('customer' => $customer); + $params = ['customer' => $customer]; $this->assertTrue($this->retailcrmModule->hookActionCustomerAccountUpdate($params)); } @@ -92,29 +93,28 @@ class RetailCRMTest extends RetailcrmTestCase { $order = new Order(1); $customer = new Customer($order->id_customer); - $params = array('order' => $order, 'customer' => $customer); + $params = ['order' => $order, 'customer' => $customer]; $reference = $order->reference; $updReference = 'test'; $this->apiMock->expects($this->any())->method('ordersGet')->willReturn(new RetailcrmApiResponse( 200, - json_encode(array( + json_encode([ 'success' => true, - 'order' => array() - )) + 'order' => [], + ]) )); $this->apiMock->expects($this->any())->method('ordersCreate')->willReturn(new RetailcrmApiResponse( 200, - json_encode(array( + json_encode([ 'success' => true, - 'order' => array( + 'order' => [ 'number' => $updReference, - ), - )) + ], + ]) )); - Configuration::updateValue(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING, false); $this->assertTrue($this->retailcrmModule->hookActionOrderEdited($params)); @@ -141,40 +141,40 @@ class RetailCRMTest extends RetailcrmTestCase $reference = $order->reference; $updReference = 'test'; - if ($newOrder === false) { + if (false === $newOrder) { $status->id = 11; - $params = array( + $params = [ 'newOrderStatus' => $status, - 'id_order' => $order->id - ); + 'id_order' => $order->id, + ]; } else { $status->id = 'new'; - $params = array( + $params = [ 'orderStatus' => $status, 'customer' => $customer, 'order' => $order, 'cart' => $cart, - ); + ]; $this->apiMock->expects($this->any())->method('ordersGet')->willReturn(new RetailcrmApiResponse( 200, - json_encode(array( + json_encode([ 'success' => true, - 'order' => array() - )) + 'order' => [], + ]) )); } $this->apiMock->expects($this->any())->method('ordersCreate')->willReturn(new RetailcrmApiResponse( 200, - json_encode(array( + json_encode([ 'success' => true, - 'order' => array( + 'order' => [ 'number' => $updReference, - ), - )) + ], + ]) )); Configuration::updateValue(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING, false); @@ -199,10 +199,10 @@ class RetailCRMTest extends RetailcrmTestCase $orderPayment = RetailcrmTestHelper::createOrderPayment($order->reference); $cart = new Cart($order->id_cart); - $params = array( + $params = [ 'paymentCC' => $orderPayment, - 'cart' => $cart - ); + 'cart' => $cart, + ]; $referenceMock = $this->createMock('RetailcrmReferences'); $referenceMock->expects($this->once())->method('getSystemPaymentModules')->willReturn($this->getSystemPaymentModules()); @@ -222,14 +222,14 @@ class RetailCRMTest extends RetailcrmTestCase */ public function dataProvider() { - return array( - array( - 'newOrder' => true - ), - array( - 'newOrder' => false - ) - ); + return [ + [ + 'newOrder' => true, + ], + [ + 'newOrder' => false, + ], + ]; } /** @@ -237,34 +237,34 @@ class RetailCRMTest extends RetailcrmTestCase */ public function ordersGetDataProvider() { - return array( - array( - 'ordersGet' => array( + return [ + [ + 'ordersGet' => [ 'success' => true, - 'order' => array( - 'payments' => array( - array( - 'type' => 'bankwire' - ) - ), - 'totalSumm' => 1500 - ) - ) - ), - array( - 'ordersGet' => array( + 'order' => [ + 'payments' => [ + [ + 'type' => 'bankwire', + ], + ], + 'totalSumm' => 1500, + ], + ], + ], + [ + 'ordersGet' => [ 'success' => true, - 'order' => array( - 'payments' => array( - array( - 'type' => 'cheque' - ) - ), - 'totalSumm' => 1500 - ) - ) - ) - ); + 'order' => [ + 'payments' => [ + [ + 'type' => 'cheque', + ], + ], + 'totalSumm' => 1500, + ], + ], + ], + ]; } /** @@ -272,26 +272,26 @@ class RetailCRMTest extends RetailcrmTestCase */ private function getProducts() { - return array( - array( + return [ + [ 'id_product_attribute' => 1, 'id_product' => 1, 'attributes' => '', 'rate' => 1, 'price' => 100, 'name' => 'Test product 1', - 'quantity' => 2 - ), - array( + 'quantity' => 2, + ], + [ 'id_product_attribute' => 1, 'id_product' => 2, 'attributes' => '', 'rate' => 1, 'price' => 100, 'name' => 'Test product 2', - 'quantity' => 1 - ) - ); + 'quantity' => 1, + ], + ]; } /** @@ -301,7 +301,7 @@ class RetailCRMTest extends RetailcrmTestCase { $address = new Address(1); - return array($address); + return [$address]; } /** @@ -309,17 +309,17 @@ class RetailCRMTest extends RetailcrmTestCase */ private function getSystemPaymentModules() { - return array ( - array ( + return [ + [ 'id' => '3', 'code' => 'bankwire', 'name' => 'Bank wire', - ), - array ( + ], + [ 'id' => '30', 'code' => 'cheque', 'name' => 'Payment by check', - ) - ); + ], + ]; } } diff --git a/tests/helpers/RetailcrmTestCase.php b/tests/helpers/RetailcrmTestCase.php index 576a498..5b0d967 100644 --- a/tests/helpers/RetailcrmTestCase.php +++ b/tests/helpers/RetailcrmTestCase.php @@ -8,7 +8,7 @@ abstract class RetailcrmTestCase extends \PHPUnit\Framework\TestCase { protected $contextMock; - public function setUp() + protected function setUp() { parent::setUp(); @@ -21,25 +21,25 @@ abstract class RetailcrmTestCase extends \PHPUnit\Framework\TestCase protected function setConfig() { $delivery = json_encode( - array( - 1 => 'delivery' - ) + [ + 1 => 'delivery', + ] ); $status = json_encode( - array( + [ 9 => 'status', 10 => 'new', - 11 => 'completed' - ) + 11 => 'completed', + ] ); $payment = json_encode( - array( + [ 'ps_checkpayment' => 'ps_checkpayment', 'bankwire' => 'bankwire', - 'cheque' => 'cheque' - ) + 'cheque' => 'cheque', + ] ); Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery); diff --git a/tests/helpers/RetailcrmTestHelper.php b/tests/helpers/RetailcrmTestHelper.php index 7143e3e..17065d1 100644 --- a/tests/helpers/RetailcrmTestHelper.php +++ b/tests/helpers/RetailcrmTestHelper.php @@ -6,7 +6,7 @@ class RetailcrmTestHelper { $orderPayment = new OrderPayment(); $orderPayment->order_reference = $order_reference; - $orderPayment->id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT'); + $orderPayment->id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); $orderPayment->conversion_rate = 1.000000; $orderPayment->amount = 100; $orderPayment->payment_method = 'Bank wire'; diff --git a/tests/lib/RetailcrmAddressBuilderTest.php b/tests/lib/RetailcrmAddressBuilderTest.php index 58bd9d1..ddc3991 100644 --- a/tests/lib/RetailcrmAddressBuilderTest.php +++ b/tests/lib/RetailcrmAddressBuilderTest.php @@ -2,16 +2,16 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase { - /** @var \AddressCore|Address $address */ + /** @var \AddressCore|Address */ protected $address; - /** @var int $defaultLang */ + /** @var int */ protected $defaultLang; /** * setUp test */ - public function setUp() + protected function setUp() { parent::setUp(); @@ -42,7 +42,8 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase ->setWithExternalId(true) ->setExternalIdSuffix('suffix') ->build() - ->getDataArray(); + ->getDataArray() + ; $this->assertNotEmpty($result); $this->assertArrayHasKey('address', $result); @@ -64,7 +65,8 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase ->setWithExternalId(true) ->setExternalIdSuffix('suffix') ->build() - ->getDataArray(); + ->getDataArray() + ; $this->assertNotEmpty($result); $this->assertNotEmpty($result['externalId']); @@ -82,7 +84,8 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase ->setWithExternalId(true) ->setExternalIdSuffix('suffix') ->build() - ->getDataArray(); + ->getDataArray() + ; $this->assertNotEmpty($result); $this->assertArrayHasKey('delivery', $result); @@ -96,7 +99,7 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase $this->assertArrayHasKey('additionalPhone', $result); $this->assertNotEmpty($result['phone']); $this->assertNotEmpty($result['additionalPhone']); - $this->assertFieldsNotEmpty($result['delivery']['address'], array('countryIso')); + $this->assertFieldsNotEmpty($result['delivery']['address'], ['countryIso']); } /** @@ -116,7 +119,8 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase ->setWithExternalId(true) ->setExternalIdSuffix('suffix') ->build() - ->getDataArray(); + ->getDataArray() + ; $this->assertNotEmpty($result); $this->assertArrayHasKey('delivery', $result); @@ -130,7 +134,7 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase * * @param array $address */ - private function assertFieldsNotEmpty($address, $skip = array()) + private function assertFieldsNotEmpty($address, $skip = []) { foreach (array_diff($this->getCheckableFields(), $skip) as $field) { $this->assertArrayHasKey($field, $address); @@ -140,23 +144,23 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase public function getAddressLines() { - return array( - array( + return [ + [ 'addressline 1', 'addressline 2', - 'addressline 1' . RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER . 'addressline 2' - ), - array( + 'addressline 1' . RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER . 'addressline 2', + ], + [ 'addressline 1', '', - 'addressline 1' - ), - array( + 'addressline 1', + ], + [ '', 'addressline 2', - RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER . 'addressline 2' - ), - ); + RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER . 'addressline 2', + ], + ]; } /** @@ -166,6 +170,6 @@ class RetailcrmAddressBuilderTest extends RetailcrmTestCase */ private function getCheckableFields() { - return array('index', 'city', 'countryIso', 'text', 'region'); + return ['index', 'city', 'countryIso', 'text', 'region']; } } diff --git a/tests/lib/RetailcrmCatalogTest.php b/tests/lib/RetailcrmCatalogTest.php index 790360a..33fa2a1 100644 --- a/tests/lib/RetailcrmCatalogTest.php +++ b/tests/lib/RetailcrmCatalogTest.php @@ -4,7 +4,7 @@ class RetailcrmCatalogTest extends RetailcrmTestCase { protected $data; - public function setUp() + protected function setUp() { parent::setUp(); @@ -45,7 +45,7 @@ class RetailcrmCatalogTest extends RetailcrmTestCase public function testIsPricesWithTax() { $products = $this->data[1]; - $productsPresta = array(); + $productsPresta = []; $productsPrestaList = Product::getProducts( (int) Configuration::get('PS_LANG_DEFAULT'), 0, @@ -69,7 +69,7 @@ class RetailcrmCatalogTest extends RetailcrmTestCase ? round($prestaProduct['price'], 2) + (round($prestaProduct['price'], 2) * $prestaProduct['rate'] / 100) : round($prestaProduct['price'], 2); - if (strpos($product['id'], '#') !== false) { + if (false !== strpos($product['id'], '#')) { $offerId = explode('#', $product['id']); $offerId = $offerId[1]; $offerCombination = new Combination($offerId); @@ -78,7 +78,7 @@ class RetailcrmCatalogTest extends RetailcrmTestCase ? round($offerCombination->price, 2) + (round($offerCombination->price, 2) * $prestaProduct['rate'] / 100) : round($offerCombination->price, 2); $offerPrice = round($offerCombinationPrice, 2) + $price; - $offerPrice = $offerPrice > 0 ? $offerPrice : $price; + $offerPrice = 0 < $offerPrice ? $offerPrice : $price; $this->assertEquals(round($offerPrice, 2), round($product['price'], 2)); } else { @@ -93,6 +93,6 @@ class RetailcrmCatalogTest extends RetailcrmTestCase $icml->generate($this->data[0], $this->data[1]); $this->assertFileExists(_PS_ROOT_DIR_ . '/retailcrm.xml'); $xml = simplexml_load_file(_PS_ROOT_DIR_ . '/retailcrm.xml'); - $this->assertNotEquals(false, $xml); + $this->assertNotFalse($xml); } } diff --git a/tests/lib/RetailcrmHistoryTest.php b/tests/lib/RetailcrmHistoryTest.php index fdd2bff..fc6e11b 100644 --- a/tests/lib/RetailcrmHistoryTest.php +++ b/tests/lib/RetailcrmHistoryTest.php @@ -5,14 +5,14 @@ class RetailcrmHistoryTest extends RetailcrmTestCase private $apiMock; private $product; - public function setUp() + protected function setUp() { parent::setUp(); $this->apiMock = $this->getMockBuilder('RetailcrmProxy') ->disableOriginalConstructor() ->setMethods( - array( + [ 'customersHistory', 'ordersHistory', 'ordersGet', @@ -20,10 +20,11 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'customersGet', 'customersFixExternalIds', 'ordersFixExternalIds', - 'customersCorporateAddressesEdit' - ) + 'customersCorporateAddressesEdit', + ] ) - ->getMock(); + ->getMock() + ; $catalog = new RetailcrmCatalog(); $data = $catalog->getData(); @@ -46,7 +47,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryDataNewCustomer() ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('customersGet') @@ -54,20 +56,20 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'customer' => $this->getApiCustomer() - ) + [ + 'customer' => $this->getApiCustomer(), + ] ) ) - ); + ) + ; - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $this->apiMock; $externalId = isset($this->getApiCustomer()['externalId']) ? $this->getApiCustomer()['externalId'] : null; - if (!empty($externalId)) - { + if (!empty($externalId)) { $oldCustomer = new Customer($externalId); RetailcrmHistory::customersHistory(); $newCustomer = new Customer($externalId); @@ -81,12 +83,12 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->assertTrue($newLastId > $oldLastId); } - $this->assertEquals(true, RetailcrmHistory::customersHistory()); + $this->assertTrue(RetailcrmHistory::customersHistory()); } public function testOrdersHistory() { - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $this->apiMock; $order = new Order(1); @@ -94,10 +96,10 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $updReference = 'test'; $crmOrder = $this->getApiOrder(); $crmOrder['number'] = $updReference; - $checkArgs = array( - 'externalId' => 1, + $checkArgs = [ + 'externalId' => 1, 'number' => $reference, - ); + ]; $this->apiMock->expects($this->any()) ->method('ordersHistory') @@ -108,7 +110,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryExistOrder($crmOrder) ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersGet') @@ -116,12 +119,13 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( + [ 'order' => $crmOrder, - ) + ] ) ) - ); + ) + ; $this->apiMock->expects($this->once()) ->method('ordersEdit') @@ -130,12 +134,13 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'order' => array(), - ) + [ + 'order' => [], + ] ) ) - ); + ) + ; Configuration::updateValue(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING, false); Configuration::updateValue(RetailCRM::ENABLE_ORDER_NUMBER_SENDING, false); @@ -154,7 +159,7 @@ class RetailcrmHistoryTest extends RetailcrmTestCase private function orderCreate($apiMock, $orderData) { - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $apiMock; $oldLastId = RetailcrmTestHelper::getMaxOrderId(); @@ -169,15 +174,16 @@ class RetailcrmHistoryTest extends RetailcrmTestCase // delivery address $address = new Address($order->id_address_delivery); - $this->assertEquals($orderData['firstName'],$address->firstname); - $this->assertEquals($orderData['lastName'],$address->lastname); + $this->assertEquals($orderData['firstName'], $address->firstname); + $this->assertEquals($orderData['lastName'], $address->lastname); $builder = new RetailcrmAddressBuilder(); $addressDelivery = $builder ->setMode(RetailcrmAddressBuilder::MODE_ORDER_DELIVERY) ->setAddress($address) ->build() - ->getDataArray(); + ->getDataArray() + ; $this->assertEquals($orderData['delivery']['address']['countryIso'], $addressDelivery['countryIso']); unset($orderData['delivery']['address']['countryIso']); @@ -187,16 +193,17 @@ class RetailcrmHistoryTest extends RetailcrmTestCase // customer address $address = new Address($order->id_address_invoice); - $this->assertEquals($orderData['customer']['firstName'],$address->firstname); - $this->assertEquals($orderData['customer']['lastName'],$address->lastname); + $this->assertEquals($orderData['customer']['firstName'], $address->firstname); + $this->assertEquals($orderData['customer']['lastName'], $address->lastname); $addressInvoice = $builder ->setMode(RetailcrmAddressBuilder::MODE_CUSTOMER) ->setAddress($address) ->build() - ->getDataArray(); + ->getDataArray() + ; - if(isset($orderData['customer']['address']['id'])) { + if (isset($orderData['customer']['address']['id'])) { unset($orderData['customer']['address']['id']); } $this->assertEquals($orderData['customer']['address'], $addressInvoice['address']); @@ -211,7 +218,7 @@ class RetailcrmHistoryTest extends RetailcrmTestCase private function switchCustomer() { - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $this->apiMock; $history = $this->getHistoryExistOrder(); @@ -236,7 +243,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryExistOrder() ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersGet') @@ -244,17 +252,17 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'order' => $this->getApiOrder() - ) + [ + 'order' => $this->getApiOrder(), + ] ) ) - ); + ) + ; $this->switchCustomer(); } - public function testOrderSwitchCorporateCustomer() { $this->apiMock->expects($this->any()) @@ -266,7 +274,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryExistOrder() ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersGet') @@ -274,12 +283,13 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'order' => $this->getApiOrderWitchCorporateCustomer() - ) + [ + 'order' => $this->getApiOrderWitchCorporateCustomer(), + ] ) ) - ); + ) + ; $this->switchCustomer(); } @@ -297,7 +307,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryDataNewOrder($orderData) ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersGet') @@ -305,12 +316,13 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'order' => $orderData - ) + [ + 'order' => $orderData, + ] ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersEdit') @@ -321,7 +333,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getEditedOrder($orderData) ) ) - ); + ) + ; $this->orderCreate($this->apiMock, $orderData); } @@ -339,7 +352,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryDataNewOrder($orderData) ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersGet') @@ -347,12 +361,13 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'order' => $orderData - ) + [ + 'order' => $orderData, + ] ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersEdit') @@ -363,7 +378,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getEditedOrder($orderData) ) ) - ); + ) + ; $this->orderCreate($this->apiMock, $orderData); } @@ -381,15 +397,15 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getUpdatePaymentStatus($lastId) ) ) - ); + ) + ; - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $this->apiMock; RetailcrmHistory::ordersHistory(); } - public function testOrderAddressUpdate() { $orderId = RetailcrmTestHelper::getMaxOrderId(); @@ -404,7 +420,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryAddressUpdated($orderId) ) ) - ); + ) + ; $this->apiMock->expects($this->any()) ->method('ordersGet') @@ -412,14 +429,15 @@ class RetailcrmHistoryTest extends RetailcrmTestCase new RetailcrmApiResponse( '200', json_encode( - array( - 'order' => $crmOrder - ) + [ + 'order' => $crmOrder, + ] ) ) - ); + ) + ; - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $this->apiMock; $order = new Order($orderId); @@ -439,7 +457,8 @@ class RetailcrmHistoryTest extends RetailcrmTestCase ->setMode(RetailcrmAddressBuilder::MODE_ORDER_DELIVERY) ->setAddressId($idAddressAfter) ->build() - ->getDataArray(); + ->getDataArray() + ; $this->assertEquals($crmOrder['delivery']['address']['countryIso'], $result['countryIso']); unset($crmOrder['delivery']['address']['countryIso']); @@ -447,7 +466,6 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->assertEquals($crmOrder['delivery']['address'], $result['delivery']['address']); } - public function testOrderNameUpdate() { $orderId = RetailcrmTestHelper::getMaxOrderId(); @@ -462,9 +480,10 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->getHistoryNameAndPhoneUpdated($orderId) ) ) - ); + ) + ; - RetailcrmHistory::$default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); + RetailcrmHistory::$default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); RetailcrmHistory::$api = $this->apiMock; $order = new Order($orderId); @@ -485,87 +504,86 @@ class RetailcrmHistoryTest extends RetailcrmTestCase $this->assertEquals($crmOrder['phone'], $addressAfter->phone); } - private function getHistoryExistOrder() { - return array( + return [ 'success' => true, - 'history' => array( - array( + 'history' => [ + [ 'id' => 19752, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'api', 'field' => 'customer', - 'apiKey' => array('current' => false), - 'oldValue' => array( + 'apiKey' => ['current' => false], + 'oldValue' => [ 'id' => 7778, 'externalId' => '1', - 'site' => '127.0.0.1:8000' - ), - 'newValue' => array( + 'site' => '127.0.0.1:8000', + ], + 'newValue' => [ 'id' => 7777, 'externalId' => '777', - 'site' => '127.0.0.1:8000' - ), - 'order' => array( + 'site' => '127.0.0.1:8000', + ], + 'order' => [ 'id' => 6025, 'externalId' => '1', 'site' => '127.0.0.1:8000', - 'status' => 'new' - ) - ) - ), - 'pagination' => array( + 'status' => 'new', + ], + ], + ], + 'pagination' => [ 'limit' => 20, 'totalCount' => 1, 'currentPage' => 1, - 'totalPageCount' => 1 - ) - ); + 'totalPageCount' => 1, + ], + ]; } private function getHistoryDataNewOrder($orderData) { - return array( + return [ 'success' => true, - 'history' => array( - array( + 'history' => [ + [ 'id' => 1, 'createdAt' => '2018-01-01 00:00:00', 'created' => true, 'source' => 'user', - 'user' => array( - 'id' => 1 - ), + 'user' => [ + 'id' => 1, + ], 'field' => 'status', 'oldValue' => null, - 'newValue' => array( - 'code' => 'new' - ), - 'order' => $orderData - ) - ), - 'pagination' => array( + 'newValue' => [ + 'code' => 'new', + ], + 'order' => $orderData, + ], + ], + 'pagination' => [ 'limit' => 20, 'totalCount' => 1, 'currentPage' => 1, - 'totalPageCount' => 1 - ) - ); + 'totalPageCount' => 1, + ], + ]; } private function getEditedOrder($orderData) { - return array( + return [ 'success' => true, 'id' => $orderData['id'], - 'order' => $orderData - ); + 'order' => $orderData, + ]; } private function getApiOrder() { - $order = array( + $order = [ 'slug' => 1, 'id' => 1, 'number' => '1C', @@ -584,37 +602,37 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'phone' => '80000000000', 'call' => false, 'expired' => false, - 'customer' => array( - 'segments' => array(), + 'customer' => [ + 'segments' => [], 'id' => 1, 'externalId' => '777', 'type' => 'customer', 'firstName' => 'Test', 'lastName' => 'Test', 'email' => 'email@test.ru', - 'phones' => array( - array( - 'number' => '111111111111111' - ), - array( - 'number' => '+7111111111' - ) - ), - 'address' => array( + 'phones' => [ + [ + 'number' => '111111111111111', + ], + [ + 'number' => '+7111111111', + ], + ], + 'address' => [ 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Buenos Aires', 'city' => 'Test', - 'text' => 'Test text address' - ), + 'text' => 'Test text address', + ], 'createdAt' => '2018-01-01 00:00:00', 'managerId' => 1, 'vip' => false, 'bad' => false, 'site' => 'test-com', - 'contragent' => array( - 'contragentType' => 'individual' - ), + 'contragent' => [ + 'contragentType' => 'individual', + ], 'personalDiscount' => 0, 'cumulativeDiscount' => 0, 'marginSumm' => 58654, @@ -622,66 +640,66 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'averageSumm' => 15387.25, 'ordersCount' => 4, 'costSumm' => 101, - 'customFields' => array( - 'custom' => 'test' - ) - ), - 'contragent' => array(), - 'delivery' => array( + 'customFields' => [ + 'custom' => 'test', + ], + ], + 'contragent' => [], + 'delivery' => [ 'code' => 'delivery', 'cost' => 100, 'netCost' => 0, - 'address' => array( + 'address' => [ 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Buenos Aires', 'city' => 'Test', - 'text' => 'Test text address' - ) - ), + 'text' => 'Test text address', + ], + ], 'site' => 'test-com', 'status' => 'new', - 'items' => array( - array( + 'items' => [ + [ 'id' => 160, 'initialPrice' => 100, 'createdAt' => '2018-01-01 00:00:00', 'quantity' => 1, 'status' => 'new', - 'offer' => array( + 'offer' => [ 'id' => 1, 'externalId' => $this->product['id'], 'xmlId' => '1', 'name' => 'Test name', - 'vatRate' => 'none' - ), - 'properties' => array(), - 'purchasePrice' => 50 - ), - array_merge(RetailcrmOrderBuilder::getGiftItem(10), array('id' => 25919)) - ), + 'vatRate' => 'none', + ], + 'properties' => [], + 'purchasePrice' => 50, + ], + array_merge(RetailcrmOrderBuilder::getGiftItem(10), ['id' => 25919]), + ], 'fromApi' => false, 'length' => 0, 'width' => 0, 'height' => 0, 'shipmentStore' => 'main', 'shipped' => false, - 'customFields' => array(), - 'uploadedToExternalStoreSystem' => false - ); + 'customFields' => [], + 'uploadedToExternalStoreSystem' => false, + ]; - $order['payments'][] = array( + $order['payments'][] = [ 'id' => 97, 'type' => 'cheque', - 'amount' => 210 - ); + 'amount' => 210, + ]; return $order; } private function getApiOrderWitchCorporateCustomer() { - $orderWithCorporateCustomer = array( + $orderWithCorporateCustomer = [ 'slug' => 1, 'id' => 2, 'number' => '1C', @@ -700,38 +718,38 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'phone' => '80000000000', 'call' => false, 'expired' => false, - 'customer' => array( - 'segments' => array(), + 'customer' => [ + 'segments' => [], 'id' => 1, 'externalId' => '777', 'type' => 'customer_corporate', 'firstName' => 'Test', 'lastName' => 'Test', 'email' => 'email@test.ru', - 'phones' => array( - array( - 'number' => '111111111111111' - ), - array( - 'number' => '+7111111111' - ) - ), - 'address' => array( + 'phones' => [ + [ + 'number' => '111111111111111', + ], + [ + 'number' => '+7111111111', + ], + ], + 'address' => [ 'id' => 2345, 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Buenos Aires', 'city' => 'Test', - 'text' => 'Test text address' - ), + 'text' => 'Test text address', + ], 'createdAt' => '2018-01-01 00:00:00', 'managerId' => 1, 'vip' => false, 'bad' => false, 'site' => 'test-com', - 'contragent' => array( - 'contragentType' => 'individual' - ), + 'contragent' => [ + 'contragentType' => 'individual', + ], 'personalDiscount' => 0, 'cumulativeDiscount' => 0, 'marginSumm' => 58654, @@ -739,11 +757,11 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'averageSumm' => 15387.25, 'ordersCount' => 4, 'costSumm' => 101, - 'customFields' => array( - 'custom' => 'test' - ) - ), - 'contact' => array( + 'customFields' => [ + 'custom' => 'test', + ], + ], + 'contact' => [ 'id' => 1, 'externalId' => '7777', 'type' => 'customer_corporate', @@ -751,161 +769,161 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'isContact' => true, 'vip' => false, 'bad' => false, - ), - 'contragent' => array(), - 'delivery' => array( + ], + 'contragent' => [], + 'delivery' => [ 'code' => 'delivery', 'cost' => 100, 'netCost' => 0, - 'address' => array( + 'address' => [ 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Buenos Aires', 'city' => 'Test', - 'text' => 'Test text address' - ) - ), - 'company' => array( + 'text' => 'Test text address', + ], + ], + 'company' => [ 'id' => 7777, - 'contragent' => array( + 'contragent' => [ 'legalName' => 'test', - 'INN' => '255222' - ), - 'address' => array( + 'INN' => '255222', + ], + 'address' => [ 'id' => 1, 'index' => '111111', 'countryIso' => 'RU', 'region' => 'Buenos Aires', 'city' => 'Test', - 'text' => 'Test text address' - ) - ), + 'text' => 'Test text address', + ], + ], 'site' => 'test-com', 'status' => 'new', - 'items' => array( - array( + 'items' => [ + [ 'id' => 160, 'initialPrice' => 100, 'createdAt' => '2018-01-01 00:00:00', 'quantity' => 1, 'status' => 'new', - 'offer' => array( + 'offer' => [ 'id' => 1, 'externalId' => $this->product['id'], 'xmlId' => '1', 'name' => 'Test name', - 'vatRate' => 'none' - ), - 'properties' => array(), - 'purchasePrice' => 50 - ), - array_merge(RetailcrmOrderBuilder::getGiftItem(10), array('id' => 25919)) - ), + 'vatRate' => 'none', + ], + 'properties' => [], + 'purchasePrice' => 50, + ], + array_merge(RetailcrmOrderBuilder::getGiftItem(10), ['id' => 25919]), + ], 'fromApi' => false, 'length' => 0, 'width' => 0, 'height' => 0, 'shipmentStore' => 'main', 'shipped' => false, - 'customFields' => array(), - 'uploadedToExternalStoreSystem' => false - ); + 'customFields' => [], + 'uploadedToExternalStoreSystem' => false, + ]; - $orderWithCorporateCustomer['payments'][] = array( + $orderWithCorporateCustomer['payments'][] = [ 'id' => 97, 'type' => 'cheque', - 'amount' => 210 - ); + 'amount' => 210, + ]; return $orderWithCorporateCustomer; } private function getUpdatePaymentStatus($orderId) { - return array( + return [ 'success' => true, - 'pagination' => array( + 'pagination' => [ 'limit' => 20, 'totalCount' => 1, 'currentPage' => 1, - 'totalPageCount' => 1 - ), - 'history' => array( - array( + 'totalPageCount' => 1, + ], + 'history' => [ + [ 'id' => 654, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'user', - 'user' => array( - 'id' => 1 - ), + 'user' => [ + 'id' => 1, + ], 'field' => 'full_paid_at', 'oldValue' => null, 'newValue' => '2018-01-01 00:00:00', - 'order' => array( + 'order' => [ 'id' => 1, 'externalId' => $orderId, 'site' => 'test-com', - 'status' => 'new' - ) - ), - array( - 'id'=> 655, + 'status' => 'new', + ], + ], + [ + 'id' => 655, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'user', - 'user' => array( - 'id' => 1 - ), + 'user' => [ + 'id' => 1, + ], 'field' => 'payments.paid_at', 'oldValue' => null, 'newValue' => '2018-01-01 00:00:00', - 'order' => array( + 'order' => [ 'id' => 1, 'externalId' => $orderId, 'site' => 'test-com', - 'status' => 'new' - ), - 'payment'=> array( - 'id'=> 102, - 'type'=> 'cheque', - 'externalId' => 1 - ) - ), - array( + 'status' => 'new', + ], + 'payment' => [ + 'id' => 102, + 'type' => 'cheque', + 'externalId' => 1, + ], + ], + [ 'id' => 656, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'user', - 'user' => array( - 'id' => 1 - ), + 'user' => [ + 'id' => 1, + ], 'field' => 'payments.status', - 'oldValue' => array( - 'code' => 'not-paid' - ), - 'newValue' => array( - 'code' => 'paid' - ), - 'order' => array( + 'oldValue' => [ + 'code' => 'not-paid', + ], + 'newValue' => [ + 'code' => 'paid', + ], + 'order' => [ 'id' => 1, 'externalId' => $orderId, 'site' => 'test-com', - 'status' => 'new' - ), - 'payment' => array( + 'status' => 'new', + ], + 'payment' => [ 'id' => 102, 'type' => 'cheque', - 'externalId' => 1 - ) - ) - ) - ); + 'externalId' => 1, + ], + ], + ], + ]; } private function getHistoryDataNewCustomer() { - return array( + return [ 'success' => true, - 'history' => array( - array( + 'history' => [ + [ 'id' => 1, 'createdAt' => '2018-01-01 00:00:00', 'created' => true, @@ -913,21 +931,21 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'field' => 'id', 'oldValue' => null, 'newValue' => 4949, - 'customer' => $this->getApiCustomer() - ) - ), - 'pagination' => array( + 'customer' => $this->getApiCustomer(), + ], + ], + 'pagination' => [ 'limit' => 20, 'totalCount' => 1, 'currentPage' => 1, - 'totalPageCount' => 1 - ) - ); + 'totalPageCount' => 1, + ], + ]; } private function getApiCustomer() { - return array( + return [ 'type' => 'customer', 'id' => 1, 'externalId' => '1', @@ -936,10 +954,10 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'vip' => false, 'bad' => false, 'site' => 'example.com', - 'contragent'=> array( - 'contragentType'=> 'individual' - ), - 'tags' => array(), + 'contragent' => [ + 'contragentType' => 'individual', + ], + 'tags' => [], 'marginSumm' => 0, 'totalSumm' => 0, 'averageSumm' => 0, @@ -947,136 +965,135 @@ class RetailcrmHistoryTest extends RetailcrmTestCase 'costSumm' => 0, 'customFields' => [], 'personalDiscount' => 0, - 'address' => array( + 'address' => [ 'id' => 4053, 'countryIso' => 'RU', 'index' => '2170', 'city' => 'Buenos Aires', 'street' => 'Good', 'building' => '17', - 'text' => 'Good, д. 17' - ), - 'segments' => array(), + 'text' => 'Good, д. 17', + ], + 'segments' => [], 'email' => 'test@example.com', 'firstName' => 'Test', 'lastName' => 'Test', - 'phones' => array( - 'number' => '+79999999999' - ) - ); + 'phones' => [ + 'number' => '+79999999999', + ], + ]; } private function getHistoryAddressUpdated($orderId) { - return array( + return [ 'success' => true, - 'history' => array( - array( + 'history' => [ + [ 'id' => 19752, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'api', 'field' => 'delivery_address.city', - 'apiKey' => array('current' => false), + 'apiKey' => ['current' => false], 'oldValue' => 'Order City old', 'newValue' => 'Order City new', - 'order' => array( + 'order' => [ 'id' => 6025, - 'externalId' => (string)$orderId, + 'externalId' => (string) $orderId, 'site' => '127.0.0.1:8000', - 'status' => 'new' - ) - ), - array( + 'status' => 'new', + ], + ], + [ 'id' => 19753, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'api', 'field' => 'delivery_address.index', - 'apiKey' => array('current' => false), + 'apiKey' => ['current' => false], 'oldValue' => '111', 'newValue' => '222', - 'order' => array( + 'order' => [ 'id' => 6025, - 'externalId' => (string)$orderId, + 'externalId' => (string) $orderId, 'site' => '127.0.0.1:8000', - 'status' => 'new' - ) - ), - array( + 'status' => 'new', + ], + ], + [ 'id' => 19754, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'api', 'field' => 'delivery_address.street', - 'apiKey' => array('current' => false), + 'apiKey' => ['current' => false], 'oldValue' => null, 'newValue' => 'Test updated address', - 'order' => array( + 'order' => [ 'id' => 6025, - 'externalId' => (string)$orderId, + 'externalId' => (string) $orderId, 'site' => '127.0.0.1:8000', - 'status' => 'new' - ) - ) - ), - 'pagination' => array( + 'status' => 'new', + ], + ], + ], + 'pagination' => [ 'limit' => 20, 'totalCount' => 3, 'currentPage' => 1, - 'totalPageCount' => 1 - ) - ); + 'totalPageCount' => 1, + ], + ]; } - private function getHistoryNameAndPhoneUpdated($orderId) { - return array( + return [ 'success' => true, - 'history' => array( - array( + 'history' => [ + [ 'id' => 19752, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'api', 'field' => 'first_name', - 'apiKey' => array('current' => false), + 'apiKey' => ['current' => false], 'oldValue' => 'name old', 'newValue' => 'name new', - 'order' => array( + 'order' => [ 'id' => 6025, - 'externalId' => (string)$orderId, + 'externalId' => (string) $orderId, 'site' => '127.0.0.1:8000', - 'status' => 'new' - ) - ), - array( + 'status' => 'new', + ], + ], + [ 'id' => 19753, 'createdAt' => '2018-01-01 00:00:00', 'source' => 'api', 'field' => 'phone', - 'apiKey' => array('current' => false), + 'apiKey' => ['current' => false], 'oldValue' => '111', 'newValue' => '222222', - 'order' => array( + 'order' => [ 'id' => 6025, - 'externalId' => (string)$orderId, + 'externalId' => (string) $orderId, 'site' => '127.0.0.1:8000', - 'status' => 'new' - ) - ) - ), - 'pagination' => array( + 'status' => 'new', + ], + ], + ], + 'pagination' => [ 'limit' => 20, 'totalCount' => 2, 'currentPage' => 1, - 'totalPageCount' => 1 - ) - ); + 'totalPageCount' => 1, + ], + ]; } private function getApiOrderAddressUpdate($orderId) { $order = $this->getApiOrder(); - $order['externalId'] = (string)$orderId; + $order['externalId'] = (string) $orderId; $order['delivery']['address']['city'] = 'Order City new'; $order['delivery']['address']['index'] = '222'; $order['delivery']['address']['text'] = 'Test updated address'; @@ -1085,16 +1102,14 @@ class RetailcrmHistoryTest extends RetailcrmTestCase return $order; } - private function getApiOrderNameAndPhoneUpdate($orderId) { $order = $this->getApiOrder(); - $order['externalId'] = (string)$orderId; + $order['externalId'] = (string) $orderId; $order['firstName'] = 'name new'; $order['phone'] = '222222'; return $order; } } - diff --git a/tests/lib/RetailcrmInventoriesTest.php b/tests/lib/RetailcrmInventoriesTest.php index c587de6..94087ac 100644 --- a/tests/lib/RetailcrmInventoriesTest.php +++ b/tests/lib/RetailcrmInventoriesTest.php @@ -5,22 +5,23 @@ class RetailcrmInventoriesTest extends RetailcrmTestCase private $apiMock; private $product1; private $product2; - + const PRODUCT1_QUANTITY = 10; const PRODUCT2_QUANTITY = 15; - public function setUp() + protected function setUp() { parent::setUp(); $this->apiMock = $this->getMockBuilder('RetailcrmProxy') ->disableOriginalConstructor() ->setMethods( - array( - 'storeInventories' - ) + [ + 'storeInventories', + ] ) - ->getMock(); + ->getMock() + ; $catalog = new RetailcrmCatalog(); $data = $catalog->getData(); @@ -37,7 +38,7 @@ class RetailcrmInventoriesTest extends RetailcrmTestCase */ public function testLoadStocks($response) { - if ($response['success'] == true) { + if (true == $response['success']) { $this->apiMock->expects($this->any()) ->method('storeInventories') ->willReturn( @@ -47,11 +48,13 @@ class RetailcrmInventoriesTest extends RetailcrmTestCase $this->getApiInventories() ) ) - ); + ) + ; } else { - $this->apiMock->expects($this->any()) - ->method('storeInventories') - ->willReturn($response); + $this->apiMock->expects($this->any()) + ->method('storeInventories') + ->willReturn($response) + ; } RetailcrmInventories::$api = $this->apiMock; @@ -60,14 +63,14 @@ class RetailcrmInventoriesTest extends RetailcrmTestCase $product1Id = explode('#', $this->product1['id']); $product2Id = explode('#', $this->product2['id']); - - if (isset($product1Id[1])){ + + if (isset($product1Id[1])) { $prod1Quantity = StockAvailable::getQuantityAvailableByProduct($product1Id[0], $product1Id[1]); } else { $prod1Quantity = StockAvailable::getQuantityAvailableByProduct($product1Id[0], 0); } - - if (isset($product2Id[1])){ + + if (isset($product2Id[1])) { $prod2Quantity = StockAvailable::getQuantityAvailableByProduct($product2Id[0], $product2Id[1]); } else { $prod2Quantity = StockAvailable::getQuantityAvailableByProduct($product2Id[0], 0); @@ -81,46 +84,46 @@ class RetailcrmInventoriesTest extends RetailcrmTestCase { $response = $this->getResponseData(); - return array( - array( - 'response' => $response['true'] - ), - array( - 'response' => $response['false'] - ) - ); + return [ + [ + 'response' => $response['true'], + ], + [ + 'response' => $response['false'], + ], + ]; } private function getResponseData() { - return array( + return [ 'true' => $this->getApiInventories(), - 'false' => false - ); + 'false' => false, + ]; } private function getApiInventories() { - return array( - "success" => true, - "pagination"=> array( - "limit"=> 250, - "totalCount"=> 1, - "currentPage"=> 1, - "totalPageCount"=> 1 - ), - "offers" => array( - array( + return [ + 'success' => true, + 'pagination' => [ + 'limit' => 250, + 'totalCount' => 1, + 'currentPage' => 1, + 'totalPageCount' => 1, + ], + 'offers' => [ + [ 'externalId' => $this->product1['id'], 'xmlId' => 'xmlId', 'quantity' => self::PRODUCT1_QUANTITY, - ), - array( + ], + [ 'externalId' => $this->product2['id'], 'xmlId' => 'xmlId', 'quantity' => self::PRODUCT2_QUANTITY, - ) - ) - ); + ], + ], + ]; } } diff --git a/tests/lib/RetailcrmReferencesTest.php b/tests/lib/RetailcrmReferencesTest.php index 64acd5c..299c5b1 100644 --- a/tests/lib/RetailcrmReferencesTest.php +++ b/tests/lib/RetailcrmReferencesTest.php @@ -4,7 +4,7 @@ class RetailcrmReferencesTest extends RetailcrmTestCase { private $retailcrmReferences; - public function setUp() + protected function setUp() { parent::setUp(); diff --git a/tests/lib/RetailcrmToolsTest.php b/tests/lib/RetailcrmToolsTest.php index 1396468..65397b8 100644 --- a/tests/lib/RetailcrmToolsTest.php +++ b/tests/lib/RetailcrmToolsTest.php @@ -2,7 +2,6 @@ class RetailcrmToolsTest extends RetailcrmTestCase { - /** * @dataProvider equalCustomerAddresses */ @@ -17,185 +16,185 @@ class RetailcrmToolsTest extends RetailcrmTestCase 'Equal addresses' => [ [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], - true + true, ], 'Changed phone' => [ [ 'phones' => [ - ['number' => '222'] + ['number' => '222'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], - false + false, ], 'Changed index' => [ [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '222', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], - false + false, ], 'Reduced address' => [ [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', - ] + ], ], - false + false, ], 'Expanded address' => [ [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], - false + false, ], 'Reduced phone' => [ [ 'phones' => [ - ['number' => '111',], - ['number' => '222',] + ['number' => '111'], + ['number' => '222'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], - false + false, ], 'Expanded phone' => [ [ 'phones' => [ - ['number' => '111',], + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ ['number' => '222'], - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], - false + false, ], 'Replaced field' => [ [ 'phones' => [ - ['number' => '111',], + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'text' => 'Address line 1 (client Address 2)', - ] + ], ], [ 'phones' => [ - ['number' => '111'] + ['number' => '111'], ], 'address' => [ 'index' => '398055', 'city' => 'Order City here', 'region' => 'Region', - ] + ], ], - false + false, ], ]; } -} \ No newline at end of file +} diff --git a/tests/lib/api/RetailcrmApiPaginatedRequestTest.php b/tests/lib/api/RetailcrmApiPaginatedRequestTest.php index b12149b..bfcf308 100644 --- a/tests/lib/api/RetailcrmApiPaginatedRequestTest.php +++ b/tests/lib/api/RetailcrmApiPaginatedRequestTest.php @@ -4,27 +4,28 @@ class RetailcrmApiPaginatedRequestTest extends RetailcrmTestCase { private $apiMock; - public function setUp() + protected function setUp() { parent::setUp(); $this->apiMock = $this->getMockBuilder('RetailcrmProxy') ->disableOriginalConstructor() ->setMethods( - array( + [ 'ordersHistory', - ) + ] ) - ->getMock(); + ->getMock() + ; } public function getPageLimits() { - return array( - 'Big history' => array(2, 3, 12, 6), - 'Equal history' => array(2, 3, 6, 6), - 'Small history' => array(2, 3, 3, 3), - ); + return [ + 'Big history' => [2, 3, 12, 6], + 'Equal history' => [2, 3, 6, 6], + 'Small history' => [2, 3, 3, 3], + ]; } /** @@ -34,18 +35,20 @@ class RetailcrmApiPaginatedRequestTest extends RetailcrmTestCase { $this->apiMock->expects($this->any()) ->method('ordersHistory') - ->willReturnOnConsecutiveCalls(...$this->getHistory($limit, $totalCount)); + ->willReturnOnConsecutiveCalls(...$this->getHistory($limit, $totalCount)) + ; $request = new RetailcrmApiPaginatedRequest(); $history = $request ->setApi($this->apiMock) ->setMethod('ordersHistory') - ->setParams(array(array(), '{{page}}')) + ->setParams([[], '{{page}}']) ->setDataKey('history') ->setLimit($limit) ->setPageLimit($pageLimit) ->execute() - ->getData(); + ->getData() + ; $lastId = end($history)['id']; @@ -59,7 +62,7 @@ class RetailcrmApiPaginatedRequestTest extends RetailcrmTestCase $currentPage = 0; while ($currentPage < $totalPageCount) { - $history = array(); + $history = []; $from = ($limit * $currentPage) + 1; $to = ($limit * $currentPage) + $limit; @@ -68,28 +71,27 @@ class RetailcrmApiPaginatedRequestTest extends RetailcrmTestCase } foreach (range($from, $to) as $historyId) { - $history[] = array( + $history[] = [ 'id' => $historyId, - ); + ]; } - $currentPage++; + ++$currentPage; yield new RetailcrmApiResponse( '200', json_encode( - array( + [ 'success' => true, 'history' => $history, - 'pagination' => array( + 'pagination' => [ 'limit' => $limit, 'totalCount' => $totalCount, 'currentPage' => $currentPage, - 'totalPageCount' => $totalPageCount - ) - ) + 'totalPageCount' => $totalPageCount, + ], + ] ) ); } - } -} \ No newline at end of file +} diff --git a/tests/lib/api/RetailcrmExceptionMiddlewareTest.php b/tests/lib/api/RetailcrmExceptionMiddlewareTest.php index 1238693..d553399 100644 --- a/tests/lib/api/RetailcrmExceptionMiddlewareTest.php +++ b/tests/lib/api/RetailcrmExceptionMiddlewareTest.php @@ -1,11 +1,10 @@ 'ordersGet', 'params' => [406, 'idd'], - 'errorMsg' => 'Value "idd" for "by" param is not valid. Allowed values are externalId, id.' + 'errorMsg' => 'Value "idd" for "by" param is not valid. Allowed values are externalId, id.', ], [ 'method' => 'ordersEdit', 'params' => [['id' => 406], 'idd'], - 'errorMsg' => 'Value "idd" for "by" param is not valid. Allowed values are externalId, id.' + 'errorMsg' => 'Value "idd" for "by" param is not valid. Allowed values are externalId, id.', ], [ 'method' => 'ordersEdit', 'params' => [['id' => 406], 'externalId'], - 'errorMsg' => 'Order array must contain the "externalId" parameter.' + 'errorMsg' => 'Order array must contain the "externalId" parameter.', ], [ 'method' => 'ordersFixExternalIds', 'params' => [[]], - 'errorMsg' => 'Method parameter must contains at least one IDs pair' + 'errorMsg' => 'Method parameter must contains at least one IDs pair', ], [ 'method' => 'ordersCreate', 'params' => [[]], - 'errorMsg' => 'Parameter `order` must contains a data' + 'errorMsg' => 'Parameter `order` must contains a data', ], [ 'method' => 'ordersUpload', 'params' => [[]], - 'errorMsg' => 'Parameter `orders` must contains array of the orders' + 'errorMsg' => 'Parameter `orders` must contains array of the orders', ], [ 'method' => 'ordersPaymentCreate', 'params' => [[]], - 'errorMsg' => 'Parameter `payment` must contains a data' + 'errorMsg' => 'Parameter `payment` must contains a data', ], [ 'method' => 'ordersPaymentEdit', 'params' => [['id' => 406], 'idd'], - 'errorMsg' => 'Value "idd" for "by" param is not valid. Allowed values are externalId, id.' + 'errorMsg' => 'Value "idd" for "by" param is not valid. Allowed values are externalId, id.', ], [ 'method' => 'ordersPaymentEdit', 'params' => [['id' => 406], 'externalId'], - 'errorMsg' => 'Order array must contain the "externalId" parameter.' + 'errorMsg' => 'Order array must contain the "externalId" parameter.', ], ]; }