diff --git a/Console/Command/Import.php b/Console/Command/Import.php index 69db969..05a1bb0 100644 --- a/Console/Command/Import.php +++ b/Console/Command/Import.php @@ -3,8 +3,6 @@ namespace Sailthru\MageSail\Console\Command; use Magento\Catalog\Api\ProductRepositoryInterface\Proxy as ProductRepositoryInterface; -use Magento\Catalog\Block\Product\AbstractProduct; -use Magento\Catalog\Helper\Image; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Attribute\Source\Status; use Magento\Catalog\Model\ResourceModel\Product\Collection\Proxy as Collection; @@ -98,8 +96,8 @@ protected function execute( $storeName = $this->storeManager->getStore($storeId)->getName(); $output->writeln("Checking {$this->productCollection->getSize()} products to import for Store #$storeId $storeName"); - $sailClient = $this->clientManager->getClient(true, $storeId); - $sailClient->_eventType = $this::EVENT_NAME; + $client = $this->clientManager->getClient($storeId); + $client->_eventType = $this::EVENT_NAME; $actionId = time(); $checkedProducts = 0; @@ -122,7 +120,7 @@ protected function execute( if ($status == Status::STATUS_ENABLED and $payload = $this->productIntercept->getProductData($product, $storeId)) { $payload['integration_action'] = $this::EVENT_NAME; $payload['integration_action_id'] = $actionId; - $sailClient->apiPost('content', $payload); + $client->apiPost('content', $payload); $syncedProducts++; } else { $skippedProducts[] = $product; diff --git a/Helper/ClientManager.php b/Helper/ClientManager.php index 50072d1..2ae4b65 100644 --- a/Helper/ClientManager.php +++ b/Helper/ClientManager.php @@ -13,15 +13,14 @@ class ClientManager extends AbstractHelper { + const XML_API_KEY = 'magesail_config/service/api_key'; + const XML_API_SECRET = 'magesail_config/service/secret_key'; + const XML_JS_ENABLED = 'magesail_config/js/enabled'; + const XML_JS_CUSTOMER_ID = 'magesail_config/js/customer_id'; + const API_SUCCESS_MESSAGE = 'Successfully Validated!'; - const XML_API_KEY = "magesail_config/service/api_key"; - const XML_API_SECRET = "magesail_config/service/secret_key"; - const XML_JS_ENABLED = "magesail_config/js/enabled"; - const XML_JS_CUSTOMER_ID = "magesail_config/js/customer_id"; - const API_SUCCESS_MESSAGE = "Successfully Validated!"; - - /** @var MageClient */ - protected $client; + /** @var MageClient[] */ + protected $clientsRegistry = []; /** @var ModuleListInterface */ private $moduleList; @@ -29,9 +28,6 @@ class ClientManager extends AbstractHelper /** @var array */ private $settings; - /** @var string */ - private $customerId; - public function __construct( Context $context, StoreManager $storeManager, @@ -54,19 +50,30 @@ public function __construct( $this->moduleList = $moduleList; } - public function initClient($storeId = null) + public function getClient($storeId = null) { - $apiKey = $this->getSettingsVal(self::XML_API_KEY, $storeId); - $apiSecret = $this->getSettingsVal(self::XML_API_SECRET, $storeId); - $this->client = new MageClient($apiKey, $apiSecret, $this->getSetupVersion(), $this->logger, $this->scopeResolver); + $cacheKey = (int)$storeId; + if (!isset($this->clientsRegistry[$cacheKey])) { + $this->clientsRegistry[$cacheKey] = $this->initClient($storeId); + } + + return $this->clientsRegistry[$cacheKey]; } - public function getClient($update=false, $storeId = null) + /** + * @param null|int|string $storeId + * + * @return MageClient + */ + public function initClient($storeId = null) { - if ($update or !$this->client) { - $this->initClient($storeId); - } - return $this->client; + return new MageClient( + $this->getSettingsVal(self::XML_API_KEY, $storeId), + $this->getSettingsVal(self::XML_API_SECRET, $storeId), + $this->getSetupVersion(), + $this->logger, + $this->scopeResolver + ); } public function getSettings($update = false) @@ -74,6 +81,7 @@ public function getSettings($update = false) if ($update || empty($this->settings)) { $this->settings = $this->getClient()->getSettings(); } + return $this->settings; } @@ -96,7 +104,7 @@ public function apiValidate() { try { $result = $this->getSettings(true); - if (!array_key_exists("error", $result)) { + if (!array_key_exists('error', $result)) { return [1, self::API_SUCCESS_MESSAGE]; } else { return 0; @@ -109,15 +117,17 @@ public function apiValidate() public function isValid() { $check = $this->apiValidate(); + return $check[0]; } private function getSetupVersion() { $moduleData = $this->moduleList->getOne('Sailthru_MageSail'); + return isset($moduleData['setup_version']) ? $moduleData['setup_version'] - : ""; + : ''; } } diff --git a/Helper/ScopeResolver.php b/Helper/ScopeResolver.php index cba6420..a19bf7c 100644 --- a/Helper/ScopeResolver.php +++ b/Helper/ScopeResolver.php @@ -18,21 +18,22 @@ use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Model\Website; -class ScopeResolver extends AbstractHelper { +class ScopeResolver extends AbstractHelper +{ - /** @var State */ + /** @var State */ protected $appState; - /** @var WebapiRequest */ + /** @var WebapiRequest */ protected $webapiRequest; - /** @var StoreManagerInterface */ + /** @var StoreManagerInterface */ protected $storeManager; - /** @var OrderRepositoryInterface */ + /** @var OrderRepositoryInterface */ protected $orderRepo; - /** @var ShipmentRepositoryInterface */ + /** @var ShipmentRepositoryInterface */ protected $shipmentRepo; private static $ADMIN_AREAS = [ @@ -61,7 +62,6 @@ public function getScope() { if ($store = $this->getStore()) { return [$store->getCode(), ScopeInterface::SCOPE_STORE]; - } elseif ($website = $this->getWebsite()) { return [$website->getCode(), ScopeInterface::SCOPE_WEBSITE]; } @@ -71,22 +71,20 @@ public function getScope() /** * @return StoreInterface|null + * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function getStore() { - if ($this->isFrontendArea()){ - $this->_logger->info("frontend"); - return $this->_getStore(); + if ($this->isFrontendArea()) { + return $this->_getStore(); } elseif ($storeId = $this->getRequestStoreScope()) { - $this->_logger->info("store request"); - return $this->_getStore($storeId); - } elseif ($this->isSalesRequest()) { - $this->_logger->info("sales request"); - $storeId = $this->getStoreIdFromSalesRequest(); return $this->_getStore($storeId); + } elseif ($this->isSalesRequest()) { + $storeId = $this->getStoreIdFromSalesRequest(); + return $this->_getStore($storeId); } return null; @@ -99,7 +97,6 @@ public function getWebsite() { if ($this->isFrontendArea() and $website = $this->_getWebsite()) { return $website; - } elseif ($wid = $this->getRequestWebsiteScope()) { return $this->_getWebsite($wid); } @@ -116,13 +113,14 @@ protected function getStoreIdFromSalesRequest() { $orderId = $this->getRequestOrderId(); $shipmentId = $this->getRequestShipmentId(); - $entityId = $orderId ?: $shipmentId; + $entityId = $orderId ? : $shipmentId; $repository = $orderId ? $this->orderRepo : $this->shipmentRepo; try { $entity = $repository->get($entityId); } catch (\Exception $e) { - $this->_logger->error("Error resolving sales scope.", $e); + $this->_logger->error('Error resolving sales scope.', $e); + return null; } @@ -131,47 +129,49 @@ protected function getStoreIdFromSalesRequest() protected function isAdminArea() { - return in_array($this->getAreaCode(), self::$ADMIN_AREAS); + return in_array($this->getAreaCode(), self::$ADMIN_AREAS); } protected function isFrontendArea() { - return $this->getAreaCode() === "frontend"; + return $this->getAreaCode() === Area::AREA_FRONTEND || $this->getAreaCode() === Area::AREA_WEBAPI_REST; } protected function getRequestStoreScope() { - return $this->_request->getParam("store"); + return $this->_request->getParam('store'); } protected function getRequestWebsiteScope() { - return $this->_request->getParam("website"); + return $this->_request->getParam('website'); } - + protected function getRequestOrderId() { - return $this->_request->getParam('order_id') ?: $this->webapiRequest->getParam('orderId'); + return $this->_request->getParam('order_id') ? : $this->webapiRequest->getParam('orderId'); } protected function getRequestShipmentId() { - return $this->_request->getParam("shipment_id"); + return $this->_request->getParam('shipment_id'); } /** * @param WebsiteInterface $website + * * @return null|int */ protected function getWebsiteSingleStore(WebsiteInterface $website) { - if ($website instanceof Website) { - $stores = $website->getStores(); - if ($stores and count($stores) == 1) { - return array_values($stores)[0]; // getStores returns indexed by store ID - } - } - return null; + if ($website instanceof Website) { + $stores = $website->getStores(); + if ($stores and count($stores) == 1) { + return array_values($stores)[0]; // getStores returns indexed by store ID + } + } + + return null; } /** @@ -183,13 +183,16 @@ private function getAreaCode() return $this->appState->getAreaCode(); } catch (LocalizedException $e) { $this->_logger->error("Error getting area code: {$e->getMessage()}"); + return null; } } /** - * @param null|int $storeId + * @param null|int|string $storeId + * * @return StoreInterface + * @throws \Magento\Framework\Exception\NoSuchEntityException */ private function _getStore($storeId = null) { @@ -198,6 +201,7 @@ private function _getStore($storeId = null) /** * @param null|int $websiteId + * * @return null|WebsiteInterface */ private function _getWebsite($websiteId = null) @@ -206,8 +210,9 @@ private function _getWebsite($websiteId = null) return $this->storeManager->getWebsite($websiteId); } catch (LocalizedException $e) { $this->_logger->error("Error getting website: {$e->getMessage()}"); + return null; } } -} \ No newline at end of file +} diff --git a/Helper/Templates.php b/Helper/Templates.php index 11587eb..b2df306 100644 --- a/Helper/Templates.php +++ b/Helper/Templates.php @@ -10,15 +10,16 @@ use Sailthru\MageSail\Model\Template as TemplateModel; use Sailthru\MageSail\Model\SailthruTemplates; -class Templates extends AbstractHelper { +class Templates extends AbstractHelper +{ - /** @var array */ + /** @var array */ private $templates = []; - /** @var ClientManager */ + /** @var ClientManager */ private $clientManager; - /** @var SailthruTemplates */ + /** @var SailthruTemplates */ protected $sailthruTemplates; public function __construct( @@ -32,7 +33,15 @@ public function __construct( ClientManager $clientManager, SailthruTemplates $sailthruTemplates ) { - parent::__construct($context, $storeManager, $logger, $templateModel, $templateConfig, $objectManager, $scopeResolver); + parent::__construct( + $context, + $storeManager, + $logger, + $templateModel, + $templateConfig, + $objectManager, + $scopeResolver + ); $this->clientManager = $clientManager; $this->sailthruTemplates = $sailthruTemplates; } @@ -59,36 +68,38 @@ public function templateExists($templateIdentifier, $storeId = null) $templates = $this->getSailthruTemplates($storeId); if (isset($templates['templates'])) { $templates = array_column($templates['templates'], 'name'); + return in_array($templateIdentifier, $templates); } + return false; } /** * To create template in Sailthru. * - * @param string $templateIdentifier - * @param string $sender + * @param string $templateIdentifier + * @param string $sender * @param null|int $storeId */ public function saveTemplate($templateIdentifier, $sender, $storeId = null) { $data = [ - "content_html" => "{content} {beacon}", - "subject" => "{subj}", - "from_email" => $sender, - "is_link_tracking" => 1 + 'content_html' => '{content} {beacon}', + 'subject' => '{subj}', + 'from_email' => $sender, + 'is_link_tracking' => 1 ]; - $client = $this->clientManager->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); try { $response = $client->saveTemplate($templateIdentifier, $data); - if (isset($response['error'])) + if (isset($response['error'])) { $client->logger($response['errormsg']); + } } catch (\Exception $e) { $client->logger($e->getMessage()); } } - -} \ No newline at end of file +} diff --git a/Mail/Transport.php b/Mail/Transport.php index 5e583bb..e0bc682 100755 --- a/Mail/Transport.php +++ b/Mail/Transport.php @@ -1,4 +1,5 @@ clientManager->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $message = ZendMessage::fromString($this->getMessage()->getRawMessage()); $vars = [ - "subj" => $this->prepareSubject($message), - "content" => $this->getMessage()->getDecodedBodyText(), + 'subj' => $this->prepareSubject($message), + 'content' => $this->getMessage()->getDecodedBodyText(), ]; try { @@ -120,17 +121,18 @@ public function sendViaAPI($templateData, $storeId) $templateName = $template['name']; if (!$this->sailthruTemplates->templateExists($templateName, $storeId)) { - $this->sailthruTemplates->saveTemplate($templateName, $this->sailthruSettings->getSender($storeId), $storeId); + $this->sailthruTemplates->saveTemplate($templateName, $this->sailthruSettings->getSender($storeId), + $storeId); } $params = [ - "template" => $templateName, - "email" => $this->prepareRecipients($message), - "vars" => $vars, + 'template' => $templateName, + 'email' => $this->prepareRecipients($message), + 'vars' => $vars, ]; $response = $client->apiPost('send', $params); - if (isset($response["error"])) { + if (isset($response['error'])) { $client->logger($response['errormsg']); throw new MailException(__($response['errormsg'])); } @@ -142,12 +144,13 @@ public function sendViaAPI($templateData, $storeId) /** * Prepare recipients list * - * @param \Zend\Mail\Message $message - * @throws RuntimeException + * @param \Zend\Mail\Message $message * * @return string * * @throws RuntimeException + * + * @throws RuntimeException */ protected function prepareRecipients(\Zend\Mail\Message $message) { @@ -160,12 +163,12 @@ protected function prepareRecipients(\Zend\Mail\Message $message) ); } - if (! $hasTo) { + if (!$hasTo) { return ''; } /** @var Mail\Header\To $to */ - $to = $headers->get('to'); + $to = $headers->get('to'); $list = $to->getAddressList(); if (count($list) == 0) { throw new RuntimeException('Invalid "To" header; contains no addresses'); @@ -182,34 +185,38 @@ protected function prepareRecipients(\Zend\Mail\Message $message) $addresses[] = $address->getEmail(); } $addresses = implode(', ', $addresses); + return $addresses; } /** * Prepare the subject line string * - * @param \Zend\Mail\Message $message + * @param \Zend\Mail\Message $message + * * @return string */ protected function prepareSubject(\Zend\Mail\Message $message) { $headers = $message->getHeaders(); - if (! $headers->has('subject')) { + if (!$headers->has('subject')) { return; } $header = $headers->get('subject'); + return $header->getFieldValue(HeaderInterface::FORMAT_ENCODED); } /** * Prepare the body string * - * @param \Zend\Mail\Message $message + * @param \Zend\Mail\Message $message + * * @return string */ protected function prepareBody(\Zend\Mail\Message $message) { - if (! $this->isWindowsOs()) { + if (!$this->isWindowsOs()) { // *nix platforms can simply return the body text return $message->getBodyText(); } @@ -217,6 +224,7 @@ protected function prepareBody(\Zend\Mail\Message $message) // On windows, lines beginning with a full stop need to be fixed $text = $message->getBodyText(); $text = str_replace("\n.", "\n..", $text); + return $text; } @@ -227,9 +235,10 @@ protected function prepareBody(\Zend\Mail\Message $message) */ protected function isWindowsOs() { - if (! $this->operatingSystem) { + if (!$this->operatingSystem) { $this->operatingSystem = strtoupper(substr(PHP_OS, 0, 3)); } + return ($this->operatingSystem == 'WIN'); } @@ -241,11 +250,17 @@ public function cleanEmail($str) } $email = substr($str, $startPart + 1); $email = substr($email, 0, -1); + return $email; } + /** + * @param string $emailStr + * + * @return string + */ public function cleanEmails($emailStr) { - return implode(",", array_map([ $this, 'cleanEmail' ], explode(",", $emailStr))); + return implode(',', array_map([$this, 'cleanEmail'], explode(',', $emailStr))); } -} \ No newline at end of file +} diff --git a/Model/SailthruTemplates.php b/Model/SailthruTemplates.php index 3e76549..de214bc 100644 --- a/Model/SailthruTemplates.php +++ b/Model/SailthruTemplates.php @@ -3,7 +3,6 @@ namespace Sailthru\MageSail\Model; use Magento\Framework\App\Cache; -use Magento\Framework\App\Cache\State; use Psr\Log\LoggerInterface; use Sailthru\MageSail\Helper\ClientManager; use Sailthru\MageSail\Helper\Settings; @@ -122,7 +121,7 @@ protected function loadTemplates($storeId, $attempt = 1) } try { - $client = $this->clientManager->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); return $client->getTemplates(); } catch (\Exception $e) { diff --git a/Observer/Frontend/CustomerAccountEdit.php b/Observer/Frontend/CustomerAccountEdit.php index 7f8c4bd..78ce994 100644 --- a/Observer/Frontend/CustomerAccountEdit.php +++ b/Observer/Frontend/CustomerAccountEdit.php @@ -15,14 +15,28 @@ class CustomerAccountEdit implements ObserverInterface { - + /** @var Manager */ private $moduleManager; + + /** @var Customer */ private $customerModel; + + /** @var StoreManagerInterface */ private $storeManager; - private $sailthruClient; + + /** @var ClientManager */ + private $clientManager; + + /** @var SailthruCookie */ private $sailthruCookie; + + /** @var SailthruCustomer */ private $sailthruCustomer; + + /** @var SailthruSettings */ private $sailthruSettings; + + /** @var VarHelper */ private $sailthruVars; public function __construct( @@ -38,30 +52,30 @@ public function __construct( $this->moduleManager = $moduleManager; $this->customerModel = $customerModel; $this->storeManager = $storeManager; - $this->sailthruClient = $clientManager; + $this->clientManager = $clientManager; $this->sailthruSettings = $sailthruSettings; $this->sailthruCookie = $sailthruCookie; $this->sailthruCustomer = $sailthruCustomer; $this->sailthruVars = $sailthruVars; } - public function execute(Observer $observer) { + public function execute(Observer $observer) + { $websiteId = $this->storeManager->getWebsite()->getWebsiteId(); $this->customerModel->setWebsiteId($websiteId); $email = $observer->getData('email'); $customer = $this->customerModel->loadByEmail($email); $storeId = $customer->getStore()->getId(); - $this->sailthruClient = $this->sailthruClient->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $sid = $customer->getData('sailthru_id'); $selectedCase = $this->sailthruSettings->getSelectCase($storeId); $varKeys = $this->sailthruVars->getVarKeys($selectedCase); try { - $this->sailthruClient->_eventType = 'CustomerUpdate'; - + $client->_eventType = 'CustomerUpdate'; $data = [ 'id' => $sid ? $sid : $email, - 'fields' => [ 'keys' => 1 ], + 'fields' => ['keys' => 1], 'keysconflict' => 'merge', 'keys' => [ 'email' => $email @@ -69,7 +83,7 @@ public function execute(Observer $observer) { 'vars' => [ $varKeys['firstname'] => $customer->getFirstname(), $varKeys['lastname'] => $customer->getLastname(), - 'name' => "{$customer->getFirstname()} {$customer->getLastname()}" + 'name' => "{$customer->getFirstname()} {$customer->getLastname()}" ] ]; @@ -80,15 +94,15 @@ public function execute(Observer $observer) { if ($this->sailthruSettings->newsletterListEnabled($storeId) && $customer->getCustomAttribute('is_subscribed') ) { - $data["lists"] = [ "Newsletter" => 1 ]; + $data['lists'] = ['Newsletter' => 1]; } - $response = $this->sailthruClient->apiPost('user', $data); - $this->sailthruCookie->set($response["keys"]["cookie"]); + $response = $client->apiPost('user', $data); + $this->sailthruCookie->set($response['keys']['cookie']); } catch (\Sailthru_Client_Exception $e) { - $this->sailthruClient->logger($e); + $client->logger($e); } catch (\Exception $e) { - $this->sailthruClient->logger($e); + $client->logger($e); } } } diff --git a/Observer/Frontend/CustomerLoggedIn.php b/Observer/Frontend/CustomerLoggedIn.php index 9334335..27e32a6 100644 --- a/Observer/Frontend/CustomerLoggedIn.php +++ b/Observer/Frontend/CustomerLoggedIn.php @@ -14,13 +14,13 @@ class CustomerLoggedIn implements ObserverInterface { const GET_FIELDS = [ - "keys" => 1, - "lists" => 1, - "optout_email" => 1 + 'keys' => 1, + 'lists' => 1, + 'optout_email' => 1 ]; private $sailthruCookie; - private $sailthruClient; + private $clientManager; private $sailthruSettings; private $subscriber; @@ -31,7 +31,7 @@ public function __construct( Subscriber $subscriber ) { $this->sailthruCookie = $sailthruCookie; - $this->sailthruClient = $clientManager; + $this->clientManager = $clientManager; $this->sailthruSettings = $sailthruSettings; $this->subscriber = $subscriber; } @@ -42,18 +42,18 @@ public function execute(Observer $observer) $customer = $observer->getData('customer'); $storeId = $customer->getStore()->getId(); $newsletterList = $this->sailthruSettings->getNewsletterList($storeId); - $this->sailthruClient = $this->sailthruClient->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $sid = $customer->getData('sailthru_id'); $email = $customer->getEmail(); $data = [ - "id" => $sid ?: $email, - "fields" => $this::GET_FIELDS + 'id' => $sid ? : $email, + 'fields' => $this::GET_FIELDS ]; try { - $this->sailthruClient->_eventType = 'CustomerLogin'; - $response = $this->sailthruClient->apiGet('user', $data); + $client->_eventType = 'CustomerLogin'; + $response = $client->apiGet('user', $data); $shouldUpdateSubscriptionStatus = $this->shouldUpdateSubscriptionStatus($newsletterList, $response); if ($shouldUpdateSubscriptionStatus) { $this->subscriber->loadByEmail($customer->getEmail()); @@ -65,9 +65,9 @@ public function execute(Observer $observer) $customer->updateData($customerData); $customer->save(); } - $this->sailthruCookie->set($response["keys"]["cookie"]); + $this->sailthruCookie->set($response['keys']['cookie']); } catch (\Exception $e) { - $this->sailthruClient->logger($e); + $client->logger($e); } } diff --git a/Observer/Frontend/CustomerRegistered.php b/Observer/Frontend/CustomerRegistered.php index 8d7f91c..e26ddec 100644 --- a/Observer/Frontend/CustomerRegistered.php +++ b/Observer/Frontend/CustomerRegistered.php @@ -4,9 +4,6 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; -use Magento\Framework\Module\Manager; -use Magento\Newsletter\Model\Subscriber; -use Magento\Store\Model\StoreManagerInterface; use Sailthru\MageSail\Helper\ClientManager; use Sailthru\MageSail\Helper\Settings as SailthruSettings; use Sailthru\MageSail\Cookie\Hid as SailthruCookie; @@ -14,8 +11,10 @@ class CustomerRegistered implements ObserverInterface { - - private $sailthruClient, $sailthruSettings, $sailthruCookie, $sailthruVars; + private $clientManager; + private $sailthruSettings; + private $sailthruCookie; + private $sailthruVars; public function __construct( ClientManager $clientManager, @@ -23,7 +22,7 @@ public function __construct( SailthruCookie $sailthruCookie, VarHelper $sailthruVars ) { - $this->sailthruClient = $clientManager; + $this->clientManager = $clientManager; $this->sailthruSettings = $sailthruSettings; $this->sailthruCookie = $sailthruCookie; $this->sailthruVars = $sailthruVars; @@ -33,7 +32,7 @@ public function execute(Observer $observer) { $customer = $observer->getData('customer'); $storeId = $customer->getStoreId(); - $this->sailthruClient = $this->sailthruClient->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $email = $customer->getEmail(); $selectedCase = $this->sailthruSettings->getSelectCase($storeId); $varKeys = $this->sailthruVars->getVarKeys($selectedCase); @@ -54,11 +53,11 @@ public function execute(Observer $observer) $data["lists"] = [ $list => 1 ]; } try { - $this->sailthruClient->_eventType = 'CustomerRegister'; - $response = $this->sailthruClient->apiPost('user', $data); - $this->sailthruCookie->set($response["keys"]["cookie"]); + $client->_eventType = 'CustomerRegister'; + $response = $client->apiPost('user', $data); + $this->sailthruCookie->set($response['keys']['cookie']); } catch (\Sailthru_Client_Exception $e) { - $this->sailthruClient->logger($e); + $client->logger($e); } } } diff --git a/Observer/OrderSave.php b/Observer/OrderSave.php index 1e592c6..28665db 100644 --- a/Observer/OrderSave.php +++ b/Observer/OrderSave.php @@ -19,7 +19,7 @@ class OrderSave implements ObserverInterface { private $productHelper; /** @var ClientManager */ - private $sailthruClient; + private $clientManager; /** @var SailthruSettings */ private $sailthruSettings; @@ -33,7 +33,7 @@ class OrderSave implements ObserverInterface { /** @var SailthruOrder */ private $sailthruOrder; - /** @var Logger */ + /** @var Logger */ private $logger; public function __construct( @@ -46,7 +46,7 @@ public function __construct( Logger $logger ) { $this->productHelper = $productHelper; - $this->sailthruClient = $clientManager; + $this->clientManager = $clientManager; $this->sailthruSettings = $sailthruSettings; $this->sailthruCookie = $sailthruCookie; $this->sailthruProduct = $sailthruProduct; @@ -59,10 +59,10 @@ public function execute(Observer $observer) /** @var Order $order */ $order = $observer->getOrder(); $storeId = $order->getStoreId(); - $this->sailthruClient = $this->sailthruClient->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $orderData = $this->build($order); try { - $this->sailthruClient->apiPost("purchase", $orderData); + $client->apiPost('purchase', $orderData); } catch (\Sailthru_Client_Exception $e) { $this->logger->err("Error sync'ing purchase #{$order->getIncrementId()} - ({$e->getCode()}) {$e->getMessage()}"); } @@ -90,8 +90,8 @@ protected function processItems(Order $order) { /** @var \Magento\Sales\Model\Order\Item[] $items */ $items = $order->getAllVisibleItems(); - $bundleIds = $this->getIdsOfType($items, "bundle"); - $configurableIds = $this->getIdsOfType($items, "configurable"); + $bundleIds = $this->getIdsOfType($items, 'bundle'); + $configurableIds = $this->getIdsOfType($items, 'configurable'); $storeId = $order->getStoreId(); $data = []; @@ -226,4 +226,4 @@ function(Item $item) { ); return $itemIds; } -} \ No newline at end of file +} diff --git a/Plugin/AddressIntercept.php b/Plugin/AddressIntercept.php index 3adb429..2d07780 100644 --- a/Plugin/AddressIntercept.php +++ b/Plugin/AddressIntercept.php @@ -9,38 +9,36 @@ class AddressIntercept { - public function __construct( ClientManager $clientManager, SailthruSettings $sailthruSettings, SailthruCustomer $sailthruCustomer ) { - $this->client = $clientManager; + $this->clientManager = $clientManager; $this->sailthruSettings = $sailthruSettings; $this->sailthruCustomer = $sailthruCustomer; } public function afterSave(Address $subject, Address $addressResult) { - $customerId = $addressResult->getCustomerId(); $billing = $addressResult->getDataModel()->isDefaultBilling(); if ($billing) { $customer = $addressResult->getCustomer(); - $sid = $customer->getData('sailthru_id'); - $email = $customer->getEmail(); - $addressVars = $this->sailthruCustomer->getAddressVars($addressResult); + $sid = $customer->getData('sailthru_id'); + $email = $customer->getEmail(); + $addressVars = $this->sailthruCustomer->getAddressVars($addressResult); $data = [ - 'id' => $sid ? $sid : $email, + 'id' => $sid ? $sid : $email, 'vars' => $addressVars, ]; try { - $this->client = $this->client->getClient(true, $customer->getStore()->getId()); - $this->client->_eventType = 'CustomerAddressUpdate'; - $this->client->apiPost('user', $data); + $client = $this->clientManager->getClient($customer->getStore()->getId()); + $client->_eventType = 'CustomerAddressUpdate'; + $client->apiPost('user', $data); } catch (\Sailthru_Client_Exception $e) { - $this->client->logger($e->getMessage()); + $client->logger($e->getMessage()); } catch (\Exception $e) { - $this->client->logger($e->getMessage()); + $client->logger($e->getMessage()); } finally { return $addressResult; } diff --git a/Plugin/CartIntercept.php b/Plugin/CartIntercept.php index 42d04d1..6470aaa 100644 --- a/Plugin/CartIntercept.php +++ b/Plugin/CartIntercept.php @@ -17,7 +17,6 @@ class CartIntercept { - public function __construct( ClientManager $clientManager, SailthruSettings $sailthruSettings, @@ -30,7 +29,7 @@ public function __construct( Configurable $configProduct, SwatchModel $swatchModel ) { - $this->client = $clientManager; + $this->clientManager = $clientManager; $this->sailthruSettings = $sailthruSettings; $this->sailthruCookie = $sailthruCookie; $this->productRepo = $productRepo; @@ -56,37 +55,37 @@ public function _gate(Cart $cart) return $cart; } } + public function sendCart(Cart $cart, $storeId) { $customer = $cart->getCustomerSession()->getCustomer(); $email = $customer->getEmail(); - $this->client = $this->client->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); if ($email || $anonymousEmail = $this->isAnonymousReady($storeId)) { $items = $this->_getItems($cart); $data = [ - 'email' => $email, - 'items' => $items, - 'incomplete' => 1, - 'message_id' => $this->sailthruCookie->getBid(), - ]; - $email = $email ? $email : $anonymousEmail; + 'email' => $email, + 'items' => $items, + 'incomplete' => 1, + 'message_id' => $this->sailthruCookie->getBid(), + ]; try { - $this->client->_eventType = "CartUpdate"; - $items = $this->_getItems($cart); - if(!$this->isLoEnabled($storeId)) { + $client->_eventType = 'CartUpdate'; + if (!$this->isLoEnabled($storeId)) { $data['reminder_time'] = $this->sailthruSettings->getAbandonedTime($storeId); $data['reminder_template'] = $this->sailthruSettings->getAbandonedTemplate($storeId); } - $this->client->apiPost("purchase", $data); + $client->apiPost('purchase', $data); } catch (\Sailthru_Client_Exception $e) { - $this->client->logger($e); + $client->logger($e); } catch (\Exception $e) { - $this->client->logger($e); + $client->logger($e); throw $e; } finally { return $cart; } } + return $cart; } @@ -118,20 +117,22 @@ public function afterUpdateItems(Cart $cardModel, $cart) public function isAnonymousReady($storeId = null) { if ($this->sailthruSettings->canAbandonAnonymous($storeId) && $hid = $this->sailthruCookie->get()) { - $response = $this->client->getUserByKey($hid, 'cookie', ['keys' => 1]); - if (array_key_exists("keys", $response)) { - $email = $response["keys"]["email"]; + $response = $this->clientManager->getClient($storeId)->getUserByKey($hid, 'cookie', ['keys' => 1]); + if (array_key_exists('keys', $response)) { + $email = $response['keys']['email']; + return $email; } } + return false; } /** * Prepare data on items in cart or order. * - * @param Cart $cart - * + * @param Cart $cart + * * @return array|false */ public function _getItems(Cart $cart) @@ -159,20 +160,18 @@ public function _getItems(Cart $cart) $_item['id'] = null; } if ($_item['id']) { - $_item['qty'] = (int) $item->getQty(); + $_item['qty'] = (int)$item->getQty(); $_item['url'] = $item->getProduct()->getProductUrl(); - $_item['image']=$this->productHelper->getSmallImageUrl($product); + $_item['image'] = $this->productHelper->getSmallImageUrl($product); $current_price = null; - $price_used = "reg"; $reg_price = $product->getPrice(); $special_price = $product->getSpecialPrice(); $special_from = $product->getSpecialFromDate(); $special_to = $product->getSpecialToDate(); if ($special_price && - ($special_from === null || (strtotime($special_from) < strtotime("Today"))) && - ($special_to === null || (strtotime($special_to) > strtotime("Today")))) { + ($special_from === null || (strtotime($special_from) < strtotime('Today'))) && + ($special_to === null || (strtotime($special_to) > strtotime('Today')))) { $current_price = $special_price; - $price_used = "special"; } else { $current_price = $reg_price; } @@ -183,26 +182,31 @@ public function _getItems(Cart $cart) $data[] = $_item; } } + return $data; } catch (\Exception $e) { - $this->client->logger($e); + $this->clientManager->getClient()->logger($e); + return false; } } /** * Get product meta keywords + * * @param Product $product + * * @return string */ public function _getTags(Product $product) { return $product->getData('meta_keyword'); } - + /** * * @param array $options + * * @return array */ public function _getVars($options) @@ -212,6 +216,7 @@ public function _getVars($options) foreach ($data as $attribute) { $vars[$attribute['label']] = $attribute['value']; } + return $vars; } } diff --git a/Plugin/ProductIntercept.php b/Plugin/ProductIntercept.php index 0aef229..56c3cb1 100644 --- a/Plugin/ProductIntercept.php +++ b/Plugin/ProductIntercept.php @@ -85,7 +85,7 @@ private function sendMultipleRequests(Product $product, $productResult) */ public function sendRequest($productResult, $storeId = null) { - $client = $this->clientManager->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $data = $this->getProductData($productResult, $storeId); if ($data) { try { @@ -221,7 +221,7 @@ public function getProductData(Product $product, $storeId = null) return $data; } catch (\Exception $e) { - $this->clientManager->getClient()->logger($e->getMessage()); + $this->clientManager->getClient($storeId)->logger($e->getMessage()); return false; } diff --git a/Plugin/SubscribeIntercept.php b/Plugin/SubscribeIntercept.php index 1a13424..85913c3 100644 --- a/Plugin/SubscribeIntercept.php +++ b/Plugin/SubscribeIntercept.php @@ -2,10 +2,8 @@ namespace Sailthru\MageSail\Plugin; -use Magento\Framework\Exception\LocalizedException; use Magento\Newsletter\Model\Subscriber; use Magento\Store\Model\StoreManagerInterface; -use Psr\Log\LoggerInterface; use Sailthru\MageSail\Helper\ClientManager; use Sailthru\MageSail\Helper\ScopeResolver; use Sailthru\MageSail\Helper\Settings as SailthruSettings; @@ -17,7 +15,7 @@ class SubscribeIntercept Subscriber::STATUS_UNSUBSCRIBED, Subscriber::STATUS_SUBSCRIBED ]; - + /** @var ClientManager */ private $clientManager; @@ -109,7 +107,7 @@ public function updateSailthruSubscription(Subscriber $subscriber) ]; } - $client = $this->clientManager->getClient(true, $storeId); + $client = $this->clientManager->getClient($storeId); $client->_eventType = $isSubscribed ? 'CustomerSubscribe' : 'CustomerUnsubscribe'; try { $client->apiPost('user', $data); diff --git a/composer.json b/composer.json index b4d6fcc..5a88212 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ "magento/module-catalog": "^101.*", "magento/module-customer": "^100.1.*" }, - "version": "2.0.2", + "version": "2.0.3", "autoload": { "files": [ "registration.php" ], "psr-4": { "Sailthru\\MageSail\\": "" } diff --git a/etc/module.xml b/etc/module.xml index 004fcc4..6e5f62a 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -5,7 +5,7 @@ */ --> - +