Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Ga.php
Go to the documentation of this file.
1 <?php
8 
10 
18 {
24  protected $_googleAnalyticsData = null;
25 
30 
34  private $cookieHelper;
35 
43  public function __construct(
44  \Magento\Framework\View\Element\Template\Context $context,
45  \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $salesOrderCollection,
46  \Magento\GoogleAnalytics\Helper\Data $googleAnalyticsData,
47  array $data = [],
48  \Magento\Cookie\Helper\Cookie $cookieHelper = null
49  ) {
50  $this->_googleAnalyticsData = $googleAnalyticsData;
51  $this->_salesOrderCollection = $salesOrderCollection;
52  $this->cookieHelper = $cookieHelper ?: ObjectManager::getInstance()->get(\Magento\Cookie\Helper\Cookie::class);
53  parent::__construct($context, $data);
54  }
55 
62  public function getConfig($path)
63  {
64  return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
65  }
66 
72  public function getPageName()
73  {
74  return $this->_getData('page_name');
75  }
76 
87  public function getPageTrackingCode($accountId)
88  {
89  $anonymizeIp = "";
90  if ($this->_googleAnalyticsData->isAnonymizedIpActive()) {
91  $anonymizeIp = "\nga('set', 'anonymizeIp', true);";
92  }
93 
94  return "\nga('create', '" . $this->escapeHtmlAttr($accountId, false)
95  . "', 'auto');{$anonymizeIp}\nga('send', 'pageview'{$this->getOptPageUrl()});\n";
96  }
97 
108  public function getOrdersTrackingCode()
109  {
110  $orderIds = $this->getOrderIds();
111  if (empty($orderIds) || !is_array($orderIds)) {
112  return;
113  }
114 
115  $collection = $this->_salesOrderCollection->create();
116  $collection->addFieldToFilter('entity_id', ['in' => $orderIds]);
117  $result = [];
118 
119  $result[] = "ga('require', 'ec', 'ec.js');";
120 
121  foreach ($collection as $order) {
122  $result[] = "ga('set', 'currencyCode', '" . $order->getOrderCurrencyCode() . "');";
123  foreach ($order->getAllVisibleItems() as $item) {
124  $result[] = sprintf(
125  "ga('ec:addProduct', {
126  'id': '%s',
127  'name': '%s',
128  'price': '%s',
129  'quantity': %s
130  });",
131  $this->escapeJsQuote($item->getSku()),
132  $this->escapeJsQuote($item->getName()),
133  $item->getPrice(),
134  $item->getQtyOrdered()
135  );
136  }
137 
138  $result[] = sprintf(
139  "ga('ec:setAction', 'purchase', {
140  'id': '%s',
141  'affiliation': '%s',
142  'revenue': '%s',
143  'tax': '%s',
144  'shipping': '%s'
145  });",
146  $order->getIncrementId(),
147  $this->escapeJsQuote($this->_storeManager->getStore()->getFrontendName()),
148  $order->getGrandTotal(),
149  $order->getTaxAmount(),
150  $order->getShippingAmount()
151  );
152 
153  $result[] = "ga('send', 'pageview');";
154  }
155  return implode("\n", $result);
156  }
157 
163  protected function _toHtml()
164  {
165  if (!$this->_googleAnalyticsData->isGoogleAnalyticsAvailable()) {
166  return '';
167  }
168 
169  return parent::_toHtml();
170  }
171 
179  {
180  return $this->cookieHelper->isCookieRestrictionModeEnabled();
181  }
182 
189  public function getCurrentWebsiteId()
190  {
191  return $this->_storeManager->getWebsite()->getId();
192  }
193 
204  public function getPageTrackingData($accountId)
205  {
206  return [
207  'optPageUrl' => $this->getOptPageUrl(),
208  'isAnonymizedIpActive' => $this->_googleAnalyticsData->isAnonymizedIpActive(),
209  'accountId' => $this->escapeHtmlAttr($accountId, false)
210  ];
211  }
212 
223  public function getOrdersTrackingData()
224  {
225  $result = [];
226  $orderIds = $this->getOrderIds();
227  if (empty($orderIds) || !is_array($orderIds)) {
228  return $result;
229  }
230 
231  $collection = $this->_salesOrderCollection->create();
232  $collection->addFieldToFilter('entity_id', ['in' => $orderIds]);
233 
234  foreach ($collection as $order) {
235  foreach ($order->getAllVisibleItems() as $item) {
236  $result['products'][] = [
237  'id' => $this->escapeJsQuote($item->getSku()),
238  'name' => $this->escapeJsQuote($item->getName()),
239  'price' => $item->getPrice(),
240  'quantity' => $item->getQtyOrdered(),
241  ];
242  }
243  $result['orders'][] = [
244  'id' => $order->getIncrementId(),
245  'affiliation' => $this->escapeJsQuote($this->_storeManager->getStore()->getFrontendName()),
246  'revenue' => $order->getGrandTotal(),
247  'tax' => $order->getTaxAmount(),
248  'shipping' => $order->getShippingAmount(),
249  ];
250  $result['currency'] = $order->getOrderCurrencyCode();
251  }
252  return $result;
253  }
254 
260  private function getOptPageUrl()
261  {
262  $optPageURL = '';
263  $pageName = trim($this->getPageName());
264  if ($pageName && substr($pageName, 0, 1) == '/' && strlen($pageName) > 1) {
265  $optPageURL = ", '" . $this->escapeHtmlAttr($pageName, false) . "'";
266  }
267  return $optPageURL;
268  }
269 }
$order
Definition: order.php:55
getPageTrackingData($accountId)
Definition: Ga.php:204
getPageTrackingCode($accountId)
Definition: Ga.php:87
escapeHtmlAttr($string, $escapeSingleQuote=true)
$orderIds
Definition: results.phtml:9
__construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $salesOrderCollection, \Magento\GoogleAnalytics\Helper\Data $googleAnalyticsData, array $data=[], \Magento\Cookie\Helper\Cookie $cookieHelper=null)
Definition: Ga.php:43