Advertisement
ales_cankar

Untitled

Mar 22nd, 2023
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 32.67 KB | None | 0 0
  1. <?php
  2.  
  3. namespace WeltPixel\GoogleTagManager\Helper;
  4.  
  5. /**
  6.  * @SuppressWarnings(PHPMD.TooManyFields)
  7.  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  8.  */
  9. class Data extends \Magento\Framework\App\Helper\AbstractHelper
  10. {
  11.     const CACHE_ID_CATEGORIES = 'weltpixel_gtm_cached_categories';
  12.  
  13.     /**
  14.      * @var array
  15.      */
  16.     protected $_gtmOptions;
  17.  
  18.     /**
  19.      * @var array
  20.      */
  21.     protected $_brandOptions;
  22.  
  23.     /**
  24.      * @var \Magento\Framework\View\Element\BlockFactory
  25.      */
  26.     protected $blockFactory;
  27.  
  28.     /**
  29.      * @var \Magento\Framework\Registry
  30.      */
  31.     protected $registry;
  32.  
  33.     /**
  34.      * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
  35.      */
  36.     protected $categoryCollectionFactory;
  37.  
  38.     /**
  39.      * @var array
  40.      */
  41.     protected $storeCategories;
  42.  
  43.     /**
  44.      * @var \Magento\Catalog\Model\ResourceModel\Category
  45.      */
  46.     protected $resourceCategory;
  47.  
  48.     /**
  49.      * @var \Magento\Framework\Escaper $escaper
  50.      */
  51.     protected $escaper;
  52.  
  53.     /**
  54.      * @var \Magento\Store\Model\StoreManagerInterface
  55.      */
  56.     protected $storeManager;
  57.  
  58.     /**
  59.      * @var \Magento\Checkout\Model\Session
  60.      */
  61.     protected $checkoutSession;
  62.  
  63.     /**
  64.      * @var \Magento\Sales\Api\OrderRepositoryInterface
  65.      */
  66.     protected $orderRepository;
  67.  
  68.     /**
  69.      * @var \Magento\Checkout\Model\Session\SuccessValidator
  70.      */
  71.     protected $checkoutSuccessValidator;
  72.  
  73.     /**
  74.      * @var \WeltPixel\GoogleTagManager\Model\Storage
  75.      */
  76.     protected $storage;
  77.  
  78.     /**
  79.      * \Magento\Cookie\Helper\Cookie
  80.      */
  81.     protected $cookieHelper;
  82.  
  83.     /**
  84.      * @var \Magento\Framework\App\CacheInterface
  85.      */
  86.     protected $cache;
  87.     /**
  88.      * @var  \Magento\Framework\App\Cache\StateInterface
  89.      */
  90.     protected $cacheState;
  91.  
  92.     protected const XML_PATH_DEV_MOVE_JS_TO_BOTTOM = 'dev/js/move_script_to_bottom';
  93.  
  94.     /**
  95.      * Data constructor.
  96.      * @param \Magento\Framework\App\Helper\Context $context
  97.      * @param \Magento\Framework\View\Element\BlockFactory $blockFactory
  98.      * @param \Magento\Framework\Registry $registry
  99.      * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
  100.      * @param \Magento\Catalog\Model\ResourceModel\Category $resourceCategory
  101.      * @param \Magento\Framework\Escaper $escaper
  102.      * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  103.      * @param \Magento\Checkout\Model\Session $checkoutSession
  104.      * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
  105.      * @param \Magento\Checkout\Model\Session\SuccessValidator $checkoutSuccessValidator
  106.      * @param \WeltPixel\GoogleTagManager\Model\Storage $storage
  107.      * @param \Magento\Cookie\Helper\Cookie $cookieHelper
  108.      * @param \Magento\Framework\App\CacheInterface $cache
  109.      * @param \Magento\Framework\App\Cache\StateInterface $cacheState
  110.      */
  111.     public function __construct(
  112.         \Magento\Framework\App\Helper\Context $context,
  113.         \Magento\Framework\View\Element\BlockFactory $blockFactory,
  114.         \Magento\Framework\Registry $registry,
  115.         \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
  116.         \Magento\Catalog\Model\ResourceModel\Category $resourceCategory,
  117.         \Magento\Framework\Escaper $escaper,
  118.         \Magento\Store\Model\StoreManagerInterface $storeManager,
  119.         \Magento\Checkout\Model\Session $checkoutSession,
  120.         \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
  121.         \Magento\Checkout\Model\Session\SuccessValidator $checkoutSuccessValidator,
  122.         \WeltPixel\GoogleTagManager\Model\Storage $storage,
  123.         \Magento\Cookie\Helper\Cookie $cookieHelper,
  124.         \Magento\Framework\App\CacheInterface $cache,
  125.         \Magento\Framework\App\Cache\StateInterface $cacheState
  126.     ) {
  127.         parent::__construct($context);
  128.         $this->_gtmOptions = $this->scopeConfig->getValue('weltpixel_googletagmanager', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
  129.         $this->blockFactory = $blockFactory;
  130.         $this->registry = $registry;
  131.         $this->categoryCollectionFactory = $categoryCollectionFactory;
  132.         $this->resourceCategory = $resourceCategory;
  133.         $this->escaper = $escaper;
  134.         $this->storeCategories = [];
  135.         $this->storeManager = $storeManager;
  136.         $this->checkoutSession = $checkoutSession;
  137.         $this->orderRepository = $orderRepository;
  138.         $this->checkoutSuccessValidator = $checkoutSuccessValidator;
  139.         $this->storage = $storage;
  140.         $this->cookieHelper = $cookieHelper;
  141.         $this->cache = $cache;
  142.         $this->cacheState = $cacheState;
  143.     }
  144.  
  145.     /**
  146.      * Get all categories id, name for the current store view
  147.      */
  148.     private function _populateStoreCategories()
  149.     {
  150.         if (!$this->isEnabled() || !empty($this->storeCategories)) {
  151.             return;
  152.         }
  153.  
  154.         $rootCategoryId = $this->storeManager->getStore()->getRootCategoryId();
  155.         $storeId = $this->storeManager->getStore()->getStoreId();
  156.  
  157.         $isWpGtmCacheEnabled = $this->cacheState->isEnabled(\WeltPixel\GoogleTagManager\Model\Cache\Type::TYPE_IDENTIFIER);
  158.         $cacheKey = self::CACHE_ID_CATEGORIES . '-' . $rootCategoryId . '-' . $storeId;
  159.         if ($isWpGtmCacheEnabled) {
  160.             $this->_eventManager->dispatch('weltpixel_googletagmanager_cachekey_after', ['cache_key' => $cacheKey]);
  161.             $cachedCategoriesData = $this->cache->load($cacheKey);
  162.             if ($cachedCategoriesData) {
  163.                 $this->storeCategories = json_decode($cachedCategoriesData, true);
  164.                 return;
  165.             }
  166.         }
  167.         $categories = $this->categoryCollectionFactory->create()
  168.             ->setStoreId($storeId)
  169.             ->addAttributeToFilter('path', ['like' => "1/{$rootCategoryId}%"])
  170.             ->addAttributeToSelect('name');
  171.         foreach ($categories as $categ) {
  172.             $this->storeCategories[$categ->getData('entity_id')] = [
  173.                 'name' => $categ->getData('name'),
  174.                 'path' => $categ->getData('path')
  175.             ];
  176.         }
  177.         if ($isWpGtmCacheEnabled) {
  178.             $cachedCategories = json_encode($this->storeCategories);
  179.             $this->cache->save($cachedCategories, $cacheKey, [\WeltPixel\GoogleTagManager\Model\Cache\Type::CACHE_TAG]);
  180.         }
  181.     }
  182.  
  183.     /**
  184.      * @return boolean
  185.      */
  186.     public function isEnabled()
  187.     {
  188.         return !$this->cookieHelper->isUserNotAllowSaveCookie() && $this->_gtmOptions['general']['enable'];
  189.     }
  190.  
  191.     /**
  192.      * @return boolean
  193.      */
  194.     public function isProductClickTrackingEnabled()
  195.     {
  196.         return ($this->isProductClickTrackingOnlyForGtmEnabled()) ||
  197.             (!$this->cookieHelper->isUserNotAllowSaveCookie() && $this->scopeConfig->getValue('weltpixel_ga4/general/product_click_tracking', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
  198.     }
  199.  
  200.     /**
  201.      * @return boolean
  202.      */
  203.     public function isProductClickTrackingOnlyForGtmEnabled()
  204.     {
  205.         if (!isset($this->_gtmOptions['general']['product_click_tracking'])) {
  206.             return false;
  207.         }
  208.         return (!$this->cookieHelper->isUserNotAllowSaveCookie() && $this->_gtmOptions['general']['product_click_tracking']);
  209.     }
  210.  
  211.     /**
  212.      * @return bool
  213.      */
  214.     public function isCookieRestrictionModeEnabled()
  215.     {
  216.         return $this->scopeConfig->getValue(\Magento\Cookie\Helper\Cookie::XML_PATH_COOKIE_RESTRICTION, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
  217.     }
  218.  
  219.     /**
  220.      * @return string
  221.      */
  222.     public function getBrandAttribute()
  223.     {
  224.         return $this->_gtmOptions['general']['brand_attribute'];
  225.     }
  226.  
  227.     /**
  228.      * @return boolean
  229.      */
  230.     public function trackPromotions()
  231.     {
  232.         return $this->_gtmOptions['general']['promotion_tracking'];
  233.     }
  234.  
  235.     /**
  236.      * @return int
  237.      */
  238.     public function getPersistentStorageExpiryTime()
  239.     {
  240.         return $this->_gtmOptions['general']['persistentlayer_expiry'];
  241.     }
  242.  
  243.     /**
  244.      * @return boolean
  245.      */
  246.     public function excludeTaxFromTransaction()
  247.     {
  248.         return $this->_gtmOptions['general']['exclude_tax_from_transaction'];
  249.     }
  250.  
  251.     /**
  252.      * @return boolean
  253.      */
  254.     public function excludeShippingFromTransaction()
  255.     {
  256.         return $this->_gtmOptions['general']['exclude_shipping_from_transaction'];
  257.     }
  258.  
  259.     /**
  260.      * @return boolean
  261.      */
  262.     public function excludeShippingFromTransactionIncludingTax()
  263.     {
  264.         return $this->_gtmOptions['general']['exclude_shipping_from_transaction_including_tax'];
  265.     }
  266.  
  267.     /**
  268.      * return child or parent string
  269.      * @return string
  270.      */
  271.     public function getParentOrChildIdUsage()
  272.     {
  273.         return $this->_gtmOptions['general']['parent_vs_child'];
  274.     }
  275.  
  276.     /**
  277.      * @return bool
  278.      */
  279.     public function getSecureCookiesFlag()
  280.     {
  281.         return $this->_gtmOptions['general']['secure_cookies'];
  282.     }
  283.  
  284.     /**
  285.      * @return int
  286.      */
  287.     public function getImpressionChunkSize()
  288.     {
  289.         return $this->_gtmOptions['general']['impression_chunk_size'];
  290.     }
  291.  
  292.     /**
  293.      * @return string
  294.      */
  295.     public function getGtmCodeSnippet()
  296.     {
  297.         return trim($this->_gtmOptions['general']['gtm_code'] ?? '');
  298.     }
  299.  
  300.     /**
  301.      * @return string
  302.      */
  303.     public function getGtmCodeSnippetForHead()
  304.     {
  305.         $gtmCodeSnippet = $this->getGtmCodeSnippet();
  306.         return $gtmCodeSnippet;
  307.     }
  308.  
  309.     /**
  310.      * @return string
  311.      */
  312.     public function getGtmNonJsCodeSnippet()
  313.     {
  314.         return trim($this->_gtmOptions['general']['gtm_nonjs_code'] ?? '');
  315.     }
  316.  
  317.     /**
  318.      * @return string
  319.      */
  320.     public function getCustomSuccessPagePaths()
  321.     {
  322.         return trim($this->_gtmOptions['general']['success_page_paths'] ?? '');
  323.     }
  324.  
  325.     /**
  326.      * @return string
  327.      */
  328.     public function getDataLayerScript()
  329.     {
  330.         $script = '';
  331.  
  332.         if (!($block = $this->createBlock('Core', 'datalayer.phtml'))) {
  333.             return $script;
  334.         }
  335.  
  336.         $block->setNameInLayout('wp.gtm.datalayer.scripts');
  337.  
  338.         $this->addDefaultInformation();
  339.         $this->addCategoryPageInformation();
  340.         $this->addSearchResultPageInformation();
  341.         $this->addProductPageInformation();
  342.         $this->addCartPageInformation();
  343.         $this->addCheckoutInformation();
  344.         $this->addOrderInformation();
  345.  
  346.         $html = $block->toHtml();
  347.  
  348.         return $html;
  349.     }
  350.  
  351.     /**
  352.      * @param $blockName
  353.      * @param $template
  354.      * @return bool
  355.      */
  356.     protected function createBlock($blockName, $template)
  357.     {
  358.         if ($block = $this->blockFactory->createBlock('\WeltPixel\GoogleTagManager\Block\\' . $blockName)
  359.             ->setTemplate('WeltPixel_GoogleTagManager::' . $template)
  360.         ) {
  361.             return $block;
  362.         }
  363.  
  364.         return false;
  365.     }
  366.  
  367.     /**
  368.      * Set default gtm options based on configuration
  369.      */
  370.     public function addDefaultInformation()
  371.     {
  372.         if (!$this->isAdWordsRemarketingEnabled()) {
  373.             return;
  374.         }
  375.  
  376.         if ($this->isAdWordsRemarketingEnabled()) {
  377.             $actionName = $this->_request->getFullActionName();
  378.             $remarketingData = [];
  379.             switch ($actionName) {
  380.                 case 'cms_index_index':
  381.                     $remarketingData['ecomm_pagetype'] = \WeltPixel\GoogleTagManager\Model\Api\Remarketing::ECOMM_PAGETYPE_HOME;
  382.                     break;
  383.                 case 'checkout_index_index':
  384.                 case 'firecheckout_index_index':
  385.                     $remarketingData['ecomm_pagetype'] = \WeltPixel\GoogleTagManager\Model\Api\Remarketing::ECOMM_PAGETYPE_CART;
  386.                     break;
  387.                 default:
  388.                     $remarketingData['ecomm_pagetype'] = \WeltPixel\GoogleTagManager\Model\Api\Remarketing::ECOMM_PAGETYPE_OTHER;
  389.                     break;
  390.             }
  391.             $this->storage->setData('google_tag_params', $remarketingData);
  392.         }
  393.     }
  394.  
  395.     /**
  396.      * Set category page product impressions
  397.      */
  398.     public function addCategoryPageInformation()
  399.     {
  400.         $currentCategory = $this->getCurrentCategory();
  401.  
  402.         if (!empty($currentCategory)) {
  403.             $categoryBlock = $this->createBlock('Category', 'category.phtml');
  404.  
  405.             if ($categoryBlock) {
  406.                 $categoryBlock->setCurrentCategory($currentCategory);
  407.                 $categoryBlock->toHtml();
  408.             }
  409.         }
  410.     }
  411.  
  412.     /**
  413.      * @return mixed
  414.      */
  415.     public function getCurrentCategory()
  416.     {
  417.         return $this->registry->registry('current_category');
  418.     }
  419.  
  420.     /**
  421.      * Set search result page product impressions
  422.      */
  423.     public function addSearchResultPageInformation()
  424.     {
  425.         $moduleName = $this->_request->getModuleName();
  426.         $controllerName = $this->_request->getControllerName();
  427.         $listPrefix = '';
  428.         if ($controllerName == 'advanced') {
  429.             $listPrefix = __('Advanced');
  430.         }
  431.  
  432.         if ($moduleName == 'catalogsearch') {
  433.             $searchBlock = $this->createBlock('Search', 'search.phtml');
  434.             if ($searchBlock) {
  435.                 $searchBlock->setListPrefix($listPrefix);
  436.                 return $searchBlock->toHtml();
  437.             }
  438.         }
  439.     }
  440.  
  441.     /**
  442.      * Set product page detail infromation
  443.      */
  444.     public function addProductPageInformation()
  445.     {
  446.         $currentProduct = $this->getCurrentProduct();
  447.  
  448.         if (!empty($currentProduct)) {
  449.             $productBlock = $this->createBlock('Product', 'product.phtml');
  450.  
  451.             if ($productBlock) {
  452.                 $productBlock->setCurrentProduct($currentProduct);
  453.                 $productBlock->toHtml();
  454.             }
  455.         }
  456.     }
  457.  
  458.     /**
  459.      * @return mixed
  460.      */
  461.     public function getCurrentProduct()
  462.     {
  463.         return $this->registry->registry('current_product');
  464.     }
  465.  
  466.     /**
  467.      * Set crossell productImpressions
  468.      */
  469.     public function addCartPageInformation()
  470.     {
  471.         $requestPath = $this->_request->getModuleName() .
  472.             DIRECTORY_SEPARATOR . $this->_request->getControllerName() .
  473.             DIRECTORY_SEPARATOR . $this->_request->getActionName();
  474.  
  475.         if ($requestPath == 'checkout/cart/index') {
  476.             $cartBlock = $this->createBlock('Cart', 'cart.phtml');
  477.  
  478.             if ($cartBlock) {
  479.                 $quote = $this->checkoutSession->getQuote();
  480.                 $cartBlock->setQuote($quote);
  481.                 $cartBlock->toHtml();
  482.             }
  483.         }
  484.     }
  485.  
  486.     public function addCheckoutInformation()
  487.     {
  488.         $requestPath = $this->_request->getModuleName() .
  489.             DIRECTORY_SEPARATOR . $this->_request->getControllerName() .
  490.             DIRECTORY_SEPARATOR . $this->_request->getActionName();
  491.  
  492.         if ($requestPath == 'checkout/index/index' || $requestPath == 'firecheckout/index/index') {
  493.             $checkoutBlock = $this->createBlock('Checkout', 'checkout.phtml');
  494.  
  495.             if ($checkoutBlock) {
  496.                 $quote = $this->checkoutSession->getQuote();
  497.                 $checkoutBlock->setQuote($quote);
  498.                 $checkoutBlock->toHtml();
  499.             }
  500.         }
  501.     }
  502.  
  503.     /**
  504.      * Set purchase details
  505.      */
  506.     public function addOrderInformation()
  507.     {
  508.         $lastOrderId = $this->checkoutSession->getLastOrderId();
  509.         $requestPath = $this->_request->getModuleName() .
  510.             DIRECTORY_SEPARATOR . $this->_request->getControllerName() .
  511.             DIRECTORY_SEPARATOR . $this->_request->getActionName();
  512.  
  513.         $requestPathDynamic = $this->_request->getModuleName() .
  514.             DIRECTORY_SEPARATOR . $this->_request->getControllerName() .
  515.             DIRECTORY_SEPARATOR . '*';
  516.  
  517.         $successPagePaths = [
  518.             'checkout/onepage/success'
  519.         ];
  520.  
  521.         $customSuccessPagePaths = trim($this->getCustomSuccessPagePaths());
  522.  
  523.         if (strlen($customSuccessPagePaths)) {
  524.             $successPagePaths = array_merge($successPagePaths, explode(",", $customSuccessPagePaths));
  525.         }
  526.  
  527.         if (!$lastOrderId) {
  528.             return;
  529.         }
  530.  
  531.         if (!in_array($requestPath, $successPagePaths) && !in_array($requestPathDynamic, $successPagePaths)) {
  532.             return;
  533.         }
  534.  
  535.         $orderBlock = $this->createBlock('Order', 'order.phtml');
  536.         if ($orderBlock) {
  537.             $order = $this->orderRepository->get($lastOrderId);
  538.             $orderBlock->setOrder($order);
  539.             $orderBlock->toHtml();
  540.         }
  541.     }
  542.  
  543.     /**
  544.      * @return string
  545.      */
  546.     public function getAffiliationName()
  547.     {
  548.         return $this->storeManager->getWebsite()->getName() . ' - ' .
  549.         $this->storeManager->getGroup()->getName() . ' - ' .
  550.         $this->storeManager->getStore()->getName();
  551.     }
  552.  
  553.     /**
  554.      * @param int $qty
  555.      * @param \Magento\Catalog\Model\Product $product
  556.      * @return array
  557.      */
  558.     public function addToCartPushData($qty, $product)
  559.     {
  560.         $result = [];
  561.  
  562.         $result['event'] = 'addToCart';
  563.         $result['eventLabel'] = html_entity_decode($product->getName());
  564.         $result['ecommerce'] = [];
  565.         $result['ecommerce']['currencyCode'] = $this->getCurrencyCode();
  566.         $result['ecommerce']['add'] = [];
  567.         $result['ecommerce']['add']['products'] = [];
  568.  
  569.         $productData = [];
  570.         $productData['name'] = html_entity_decode($product->getName());
  571.         $productData['id'] = $this->getGtmProductId($product);
  572.  
  573.         $productData['price'] = number_format($product->getPriceInfo()->getPrice('final_price')->getValue(), 2, '.', '');
  574.         if ($this->isBrandEnabled()) {
  575.             $productData['brand'] = $this->getGtmBrand($product);
  576.         }
  577.  
  578.         $categoryName = $this->getGtmCategoryFromCategoryIds($product->getCategoryIds());
  579.         $productData['category'] = $categoryName;
  580.         $productData['list'] = $categoryName;
  581.         $productData['quantity'] = (double)$qty;
  582.  
  583.         $result['ecommerce']['add']['products'][] = $productData;
  584.  
  585.         return $result;
  586.     }
  587.  
  588.     /**
  589.      * @param array $currentAddToCartData
  590.      * @param array $addToCartPushData
  591.      * @return array
  592.      */
  593.     public function mergeAddToCartPushData($currentAddToCartData, $addToCartPushData)
  594.     {
  595.         if (!is_array($currentAddToCartData)) {
  596.             $currentAddToCartData = $addToCartPushData;
  597.         } else {
  598.             $currentAddToCartData['eventLabel'] = $currentAddToCartData['eventLabel'] . ', ' . $addToCartPushData['eventLabel'];
  599.             $currentAddToCartData['ecommerce']['add']['products'][] = $addToCartPushData['ecommerce']['add']['products'][0];
  600.         }
  601.  
  602.         return $currentAddToCartData;
  603.     }
  604.  
  605.     /**
  606.      * @return string
  607.      */
  608.     public function getCurrencyCode()
  609.     {
  610.         return $this->storeManager->getStore()->getCurrentCurrencyCode();
  611.     }
  612.  
  613.     /**
  614.      * Returns the product id or sku based on the backend settings
  615.      * @param \Magento\Catalog\Model\Product $product
  616.      * @return string
  617.      */
  618.     public function getGtmProductId($product)
  619.     {
  620.         $idOption = $this->_gtmOptions['general']['id_selection'];
  621.         $gtmProductId = '';
  622.  
  623.         switch ($idOption) {
  624.             case 'sku':
  625.                 $gtmProductId = $product->getData('sku');
  626.                 break;
  627.             case 'id':
  628.             default:
  629.                 $gtmProductId = $product->getId();
  630.                 break;
  631.         }
  632.  
  633.         return $gtmProductId;
  634.     }
  635.  
  636.     /**
  637.      * Get the product id or sku for order item
  638.      * @param \Magento\Sales\Model\Order\Item $item
  639.      * @return string
  640.      */
  641.     public function getGtmOrderItemId($item)
  642.     {
  643.         $idOption = $this->_gtmOptions['general']['id_selection'];
  644.         $gtmProductId = '';
  645.  
  646.         switch ($idOption) {
  647.             case 'sku':
  648.                 $gtmProductId = $item->getProduct()->getData('sku');//$item->getSku();
  649.                 break;
  650.             case 'id':
  651.             default:
  652.                 $gtmProductId = $item->getProductId();
  653.                 break;
  654.         }
  655.  
  656.         return $gtmProductId;
  657.     }
  658.  
  659.     /**
  660.      * @return boolean
  661.      */
  662.     public function isBrandEnabled()
  663.     {
  664.         return $this->_gtmOptions['general']['enable_brand'];
  665.     }
  666.  
  667.     /**
  668.      * @param \Magento\Catalog\Model\Product $product
  669.      * @return string
  670.      */
  671.     public function getGtmBrand($product)
  672.     {
  673.         $gtmBrand = '';
  674.         if ($this->isBrandEnabled()) {
  675.             $brandAttribute = $this->_gtmOptions['general']['brand_attribute'];
  676.             $brandOptions = $this->getBrandOptions($product, $brandAttribute);
  677.  
  678.             $frontendValue =  $product->getData($brandAttribute);
  679.             if (is_array($frontendValue)) {
  680.                 $result = [];
  681.                 foreach ($frontendValue as $value) {
  682.                     $result[] = ($brandOptions[$value]) ? $brandOptions[$value] : null;
  683.                 }
  684.                 $gtmBrand = implode(',', array_filter($result));
  685.             } elseif (isset($brandOptions[$frontendValue])) {
  686.                 $gtmBrand = $brandOptions[$frontendValue];
  687.             }
  688.         }
  689.  
  690.         return $gtmBrand;
  691.     }
  692.  
  693.     /**
  694.      * @param  \Magento\Catalog\Model\Product $product
  695.      * @param string $brand
  696.      * @return array
  697.      */
  698.     protected function getBrandOptions($product, $brand) {
  699.         if (empty($this->_brandOptions)) {
  700.             try {
  701.                 $options = $product->getResource()->getAttribute($brand)->getSource()->getAllOptions();
  702.                 foreach ($options as $option) {
  703.                     $this->_brandOptions[$option['value']] = $option['label'];
  704.                 }
  705.             } catch (Exception $ex) {
  706.             }
  707.         }
  708.  
  709.         return $this->_brandOptions;
  710.     }
  711.  
  712.     /**
  713.      * @return string
  714.      */
  715.     public function getOrderTotalCalculation()
  716.     {
  717.         return $this->_gtmOptions['general']['order_total_calculation'];
  718.     }
  719.  
  720.     /**
  721.      * Returns category tree path
  722.      * @param array $categoryIds
  723.      * @return string
  724.      */
  725.     public function getGtmCategoryFromCategoryIds($categoryIds)
  726.     {
  727.         if (!count($categoryIds)) {
  728.             return '';
  729.         }
  730.         if (empty($this->storeCategories)) {
  731.             $this->_populateStoreCategories();
  732.         }
  733.         $categoryId = $categoryIds[0];
  734.         $categoryPath = '';
  735.         if (isset($this->storeCategories[$categoryId])) {
  736.             $categoryPath = $this->storeCategories[$categoryId]['path'];
  737.         }
  738.         return $this->_buildCategoryPath($categoryPath);
  739.     }
  740.  
  741.     /**
  742.      * @param string $categoryPath
  743.      * @return string
  744.      */
  745.     private function _buildCategoryPath($categoryPath)
  746.     {
  747.         $categIds = explode('/', $categoryPath);
  748.         $ignoreCategories = 2;
  749.         if (count($categIds) < 3) {
  750.             $ignoreCategories = 1;
  751.         }
  752.         /* first 2 categories can be ignored, or 1st if root category */
  753.         $categoriIds = array_slice($categIds, $ignoreCategories);
  754.         $categoriesWithNames = [];
  755.  
  756.         foreach ($categoriIds as $categoriId) {
  757.             if (isset($this->storeCategories[$categoriId])) {
  758.                 $categoriesWithNames[] = $this->storeCategories[$categoriId]['name'];
  759.             }
  760.         }
  761.  
  762.         return implode('/', $categoriesWithNames);
  763.     }
  764.  
  765.     /**
  766.      * @param int $qty
  767.      * @param \Magento\Catalog\Model\Product $product
  768.      * @return array
  769.      */
  770.     public function removeFromCartPushData($qty, $product)
  771.     {
  772.         $result = [];
  773.  
  774.         $result['event'] = 'removeFromCart';
  775.         $result['eventLabel'] = html_entity_decode($product->getName());
  776.         $result['ecommerce'] = [];
  777.         $result['ecommerce']['currencyCode'] = $this->getCurrencyCode();
  778.         $result['ecommerce']['remove'] = [];
  779.         $result['ecommerce']['remove']['products'] = [];
  780.  
  781.         $productData = [];
  782.         $productData['name'] = html_entity_decode($product->getName());
  783.         $productData['id'] = $this->getGtmProductId($product);
  784.         $productData['price'] = number_format($product->getPriceInfo()->getPrice('final_price')->getValue(), 2, '.', '');
  785.         if ($this->isBrandEnabled()) {
  786.             $productData['brand'] = $this->getGtmBrand($product);
  787.         }
  788.  
  789.         $productData['category'] = $this->getGtmCategoryFromCategoryIds($product->getCategoryIds());
  790.         $productData['quantity'] = (double)$qty;
  791.  
  792.         $result['ecommerce']['remove']['products'][] = $productData;
  793.  
  794.         return $result;
  795.     }
  796.  
  797.     /**
  798.      * @param \Magento\Catalog\Model\Product $product
  799.      * @return array
  800.      */
  801.     public function addToWishListPushData($product)
  802.     {
  803.         $result = [];
  804.  
  805.         $result['event'] = 'addToWishlist';
  806.         $result['eventLabel'] = html_entity_decode($product->getName());
  807.         $result['ecommerce'] = [];
  808.         $result['ecommerce']['currencyCode'] = $this->getCurrencyCode();
  809.         $result['ecommerce']['add'] = [];
  810.         $result['ecommerce']['add']['products'] = [];
  811.  
  812.         $productData = [];
  813.         $productData['name'] = html_entity_decode($product->getName());
  814.         $productData['id'] = $this->getGtmProductId($product);
  815.         $productData['price'] = number_format($product->getPriceInfo()->getPrice('final_price')->getValue(), 2, '.', '');
  816.         if ($this->isBrandEnabled()) {
  817.             $productData['brand'] = $this->getGtmBrand($product);
  818.         }
  819.  
  820.         $productData['category'] = $this->getGtmCategoryFromCategoryIds($product->getCategoryIds());
  821.  
  822.         $result['ecommerce']['add']['products'][] = $productData;
  823.  
  824.         return $result;
  825.     }
  826.  
  827.     /**
  828.      * @param \Magento\Catalog\Model\Product $product
  829.      * @return array
  830.      */
  831.     public function addToComparePushData($product)
  832.     {
  833.         $result = [];
  834.  
  835.         $result['event'] = 'addToCompare';
  836.         $result['eventLabel'] = html_entity_decode($product->getName());
  837.         $result['ecommerce'] = [];
  838.         $result['ecommerce']['currencyCode'] = $this->getCurrencyCode();
  839.         $result['ecommerce']['add'] = [];
  840.         $result['ecommerce']['add']['products'] = [];
  841.  
  842.         $productData = [];
  843.         $productData['name'] = html_entity_decode($product->getName());
  844.         $productData['id'] = $this->getGtmProductId($product);
  845.         $productData['price'] = number_format($product->getPriceInfo()->getPrice('final_price')->getValue(), 2, '.', '');
  846.         if ($this->isBrandEnabled()) {
  847.             $productData['brand'] = $this->getGtmBrand($product);
  848.         }
  849.  
  850.         $productData['category'] = $this->getGtmCategoryFromCategoryIds($product->getCategoryIds());
  851.  
  852.         $result['ecommerce']['add']['products'][] = $productData;
  853.  
  854.         return $result;
  855.     }
  856.  
  857.     /**
  858.      * @param int $step
  859.      * @param string $checkoutOption
  860.      * @return array
  861.      */
  862.     public function addCheckoutStepPushData($step, $checkoutOption)
  863.     {
  864.         $checkoutStepResult = [];
  865.  
  866.         $checkoutStepResult['event'] = 'checkout';
  867.         $checkoutStepResult['eventLabel'] = 'Checkout';
  868.         $checkoutStepResult['ecommerce'] = [];
  869.         $checkoutStepResult['ecommerce']['currencyCode'] = $this->getCurrencyCode();
  870.         $checkoutStepResult['ecommerce']['checkout']['actionField'] =  [
  871.             'step' => $step,
  872.             'option' => $checkoutOption
  873.         ];
  874.  
  875.         $products = [];
  876.         $checkoutBlock = $this->createBlock('Checkout', 'checkout.phtml');
  877.  
  878.         if ($checkoutBlock) {
  879.             $quote = $this->checkoutSession->getQuote();
  880.             $checkoutBlock->setQuote($quote);
  881.             $products = $checkoutBlock->getProducts();
  882.         }
  883.  
  884.         $checkoutStepResult['ecommerce']['checkout']['products'] = $products;
  885.  
  886.         $checkoutOptionResult['event'] = 'checkoutOption';
  887.         $checkoutOptionResult['eventLabel'] = 'Checkout Steps';
  888.         $checkoutOptionResult['ecommerce'] = [];
  889.         $checkoutOptionResult['ecommerce']['currencyCode'] = $this->getCurrencyCode();
  890.         $checkoutOptionResult['ecommerce']['checkout_option'] = [];
  891.         $optionData = [];
  892.         $optionData['step'] = $step;
  893.         $optionData['option'] = $checkoutOption;
  894.         $checkoutOptionResult['ecommerce']['checkout_option']['actionField'] = $optionData;
  895.  
  896.         $result = [];
  897.         $result[] = $checkoutStepResult;
  898.         $result[] = $checkoutOptionResult;
  899.  
  900.         return $result;
  901.     }
  902.  
  903.     /**
  904.      * @return boolean
  905.      */
  906.     public function isCustomDimensionCustomerIdEnabled()
  907.     {
  908.         return $this->_gtmOptions['general']['custom_dimension_customerid'];
  909.     }
  910.  
  911.     /**
  912.      * @return boolean
  913.      */
  914.     public function isCustomDimensionCustomerGroupEnabled()
  915.     {
  916.         return $this->_gtmOptions['general']['custom_dimension_customergroup'];
  917.     }
  918.  
  919.     /**
  920.      * @return boolean
  921.      */
  922.     public function isAdWordConversionTrackingEnabled()
  923.     {
  924.         return $this->_gtmOptions['adwords_conversion_tracking']['enable'];
  925.     }
  926.  
  927.     /**
  928.      * @return boolean
  929.      */
  930.     public function isAdWordsRemarketingEnabled()
  931.     {
  932.         return $this->_gtmOptions['adwords_remarketing']['enable'];
  933.     }
  934.  
  935.     /**
  936.      * @param \Magento\Catalog\Model\Product $product
  937.      * @param int $index
  938.      * @param string $list
  939.      * @param string $listId
  940.      * @return string
  941.      */
  942.     public function addProductClick($product, $index = 0, $list = '', $listId = '')
  943.     {
  944.         $productClickBlock = $this->createBlock('Core', 'product_click.phtml');
  945.         $html = '';
  946.  
  947.         if ($this->isProductClickTrackingOnlyForGtmEnabled()) {
  948.             if ($productClickBlock) {
  949.                 $productClickBlock->setProduct($product);
  950.                 $productClickBlock->setIndex($index);
  951.  
  952.                 /**
  953.                  * If a list value is set use that one, if nothing add one
  954.                  */
  955.                 if (!$list) {
  956.                     $currentCategory = $this->getCurrentCategory();
  957.                     if (!empty($currentCategory)) {
  958.                         $list = $this->getGtmCategory($currentCategory);
  959.                     } else {
  960.                         /* Check if it is from a listing from search or advanced search*/
  961.                         $requestPath = $this->_request->getModuleName() .
  962.                             DIRECTORY_SEPARATOR . $this->_request->getControllerName() .
  963.                             DIRECTORY_SEPARATOR . $this->_request->getActionName();
  964.                         switch ($requestPath) {
  965.                             case 'catalogsearch/advanced/result':
  966.                                 $list = __('Advanced Search Result');
  967.                                 break;
  968.                             case 'catalogsearch/result/index':
  969.                                 $list = __('Search Result');
  970.                                 break;
  971.                         }
  972.                     }
  973.                 }
  974.                 $productClickBlock->setList($list);
  975.                 $html = trim($productClickBlock->toHtml());
  976.             }
  977.  
  978.             if (!empty($html)) {
  979.                 $eventCallBack = ", 'eventCallback': function() { document.location = '" .
  980.                     $this->escaper->escapeHtml($product->getUrlModel()->getUrl($product)) . "';return false; }});";
  981.                 $html = substr(rtrim($html, ");"), 0, -1);
  982.                 $html .= $eventCallBack;
  983.             }
  984.         }
  985.  
  986.         $htmlObject = new \Magento\Framework\DataObject(['html' => $html]);
  987.         $this->_eventManager->dispatch('weltpixel_googletagmanager_afterproductclick', [
  988.             'html' => $htmlObject,
  989.             'product' => $product,
  990.             'index' => $index,
  991.             'list' => $list,
  992.             'listId' => $listId,
  993.         ]);
  994.         $html = $htmlObject->getHtml();
  995.  
  996.         if (!empty($html)) {
  997.             $html = 'onclick="' . $html . '"';
  998.         }
  999.  
  1000.         return $html;
  1001.     }
  1002.  
  1003.     /**
  1004.      * Returns category tree path
  1005.      * @param \Magento\Catalog\Model\Category $category
  1006.      * @return string
  1007.      */
  1008.     public function getGtmCategory($category)
  1009.     {
  1010.         $categoryPath = $category->getData('path');
  1011.         $this->_populateStoreCategories();
  1012.  
  1013.         return $this->_buildCategoryPath($categoryPath);
  1014.     }
  1015.  
  1016.     /**
  1017.      * @return string
  1018.      */
  1019.     public function getDimensionsActionUrl()
  1020.     {
  1021.         return $this->storeManager->getStore()->getBaseUrl() . 'weltpixel_gtm/index/dimensions';
  1022.     }
  1023.  
  1024.     /**
  1025.      * @return bool
  1026.      */
  1027.     public function isDevMoveJsBottomEnabled()
  1028.     {
  1029.         return $this->scopeConfig->isSetFlag(self::XML_PATH_DEV_MOVE_JS_TO_BOTTOM, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
  1030.     }
  1031. }
  1032.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement