Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Protected Member Functions | Protected Attributes
Ga Class Reference
Inheritance diagram for Ga:
Template AbstractBlock DataObject BlockInterface

Public Member Functions

 __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)
 
 getConfig ($path)
 
 getPageName ()
 
 getPageTrackingCode ($accountId)
 
 getOrdersTrackingCode ()
 
 isCookieRestrictionModeEnabled ()
 
 getCurrentWebsiteId ()
 
 getPageTrackingData ($accountId)
 
 getOrdersTrackingData ()
 
- Public Member Functions inherited from Template
 __construct (Template\Context $context, array $data=[])
 
 setTemplateContext ($templateContext)
 
 getTemplate ()
 
 setTemplate ($template)
 
 getTemplateFile ($template=null)
 
 getArea ()
 
 assign ($key, $value=null)
 
 fetchView ($fileName)
 
 getBaseUrl ()
 
 getObjectData (\Magento\Framework\DataObject $object, $key)
 
 getCacheKeyInfo ()
 
- Public Member Functions inherited from AbstractBlock
 __construct (\Magento\Framework\View\Element\Context $context, array $data=[])
 
 getJsLayout ()
 
 getRequest ()
 
 getParentBlock ()
 
 setLayout (\Magento\Framework\View\LayoutInterface $layout)
 
 getLayout ()
 
 setNameInLayout ($name)
 
 getChildNames ()
 
 setAttribute ($name, $value=null)
 
 setChild ($alias, $block)
 
 addChild ($alias, $block, $data=[])
 
 unsetChild ($alias)
 
 unsetCallChild ($alias, $callback, $result, $params)
 
 unsetChildren ()
 
 getChildBlock ($alias)
 
 getChildHtml ($alias='', $useCache=true)
 
 getChildChildHtml ($alias, $childChildAlias='', $useCache=true)
 
 getBlockHtml ($name)
 
 insert ($element, $siblingName=0, $after=true, $alias='')
 
 append ($element, $alias='')
 
 getGroupChildNames ($groupName)
 
 getChildData ($alias, $key='')
 
 getUiId ($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
 
 getJsId ($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
 
 getUrl ($route='', $params=[])
 
 getViewFileUrl ($fileId, array $params=[])
 
 formatDate ( $date=null, $format=\IntlDateFormatter::SHORT, $showTime=false, $timezone=null)
 
 formatTime ( $time=null, $format=\IntlDateFormatter::SHORT, $showDate=false)
 
 getModuleName ()
 
 escapeHtml ($data, $allowedTags=null)
 
 escapeJs ($string)
 
 escapeHtmlAttr ($string, $escapeSingleQuote=true)
 
 escapeCss ($string)
 
 stripTags ($data, $allowableTags=null, $allowHtmlEntities=false)
 
 escapeUrl ($string)
 
 escapeXssInUrl ($data)
 
 escapeQuote ($data, $addSlashes=false)
 
 escapeJsQuote ($data, $quote='\'')
 
 getNameInLayout ()
 
 getCacheKeyInfo ()
 
 getCacheKey ()
 
 getVar ($name, $module=null)
 
 isScopePrivate ()
 
- Public Member Functions inherited from DataObject
 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 
- Public Member Functions inherited from BlockInterface
 toHtml ()
 

Protected Member Functions

 _toHtml ()
 
- Protected Member Functions inherited from Template
 _construct ()
 
 _toHtml ()
 
 getRootDirectory ()
 
 getMediaDirectory ()
 
- Protected Member Functions inherited from AbstractBlock
 _construct ()
 
 _prepareLayout ()
 
 _beforeToHtml ()
 
 _afterToHtml ($html)
 
 _toHtml ()
 
 _getNotFoundUrl ($route='', $params=['_direct'=> 'core/index/notFound'])
 
 getCacheTags ()
 
 getCacheLifetime ()
 
 _loadCache ()
 
 _saveCache ($data)
 
 _getSidPlaceholder ($cacheKey=null)
 
- Protected Member Functions inherited from DataObject
 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_googleAnalyticsData = null
 
 $_salesOrderCollection
 
- Protected Attributes inherited from Template
 $_viewVars = []
 
 $_baseUrl
 
 $_jsUrl
 
 $_allowSymlinks
 
 $_filesystem
 
 $_template
 
 $templateEnginePool
 
 $_storeManager
 
 $_appState
 
 $directory
 
 $templateContext
 
 $pageConfig
 
 $resolver
 
 $validator
 
- Protected Attributes inherited from AbstractBlock
 $_design
 
 $_session
 
 $_sidResolver
 
 $_nameInLayout
 
 $_layout
 
 $jsLayout = []
 
 $_request
 
 $_urlBuilder
 
 $_eventManager
 
 $_frontController
 
 $_assetRepo
 
 $_viewConfig
 
 $_cacheState
 
 $_logger
 
 $_escaper
 
 $filterManager
 
 $_localeDate
 
 $inlineTranslation
 
 $_isScopePrivate = false
 
 $_scopeConfig
 
 $_cache
 
- Protected Attributes inherited from DataObject
 $_data = []
 

Additional Inherited Members

- Static Public Member Functions inherited from AbstractBlock
static extractModuleName ($className)
 
- Data Fields inherited from Template
const XML_PATH_TEMPLATE_ALLOW_SYMLINK = 'dev/template/allow_symlink'
 
- Data Fields inherited from AbstractBlock
const CACHE_GROUP = \Magento\Framework\App\Cache\Type\Block::TYPE_IDENTIFIER
 
const CACHE_KEY_PREFIX = 'BLOCK_'
 
- Static Protected Attributes inherited from DataObject
static $_underscoreCache = []
 

Detailed Description

GoogleAnalytics Page Block

@api

Since
100.0.2

Definition at line 17 of file Ga.php.

Constructor & Destructor Documentation

◆ __construct()

__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 
)
Parameters
\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 | null$cookieHelper

Definition at line 43 of file Ga.php.

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  }

Member Function Documentation

◆ _toHtml()

_toHtml ( )
protected

Render GA tracking scripts

Returns
string

Definition at line 163 of file Ga.php.

164  {
165  if (!$this->_googleAnalyticsData->isGoogleAnalyticsAvailable()) {
166  return '';
167  }
168 
169  return parent::_toHtml();
170  }

◆ getConfig()

getConfig (   $path)

Get config

Parameters
string$path
Returns
mixed

Definition at line 62 of file Ga.php.

63  {
64  return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
65  }

◆ getCurrentWebsiteId()

getCurrentWebsiteId ( )

Return current website id.

Returns
int
Since
100.2.0

Definition at line 189 of file Ga.php.

190  {
191  return $this->_storeManager->getWebsite()->getId();
192  }

◆ getOrdersTrackingCode()

getOrdersTrackingCode ( )

Render information about specified orders and their items

https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#transaction string|void deprecated 1067.

Definition at line 108 of file Ga.php.

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  }
$order
Definition: order.php:55
$orderIds
Definition: results.phtml:9

◆ getOrdersTrackingData()

getOrdersTrackingData ( )

Return information about order and items for GA tracking.

https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#transaction array 100.2.0

Definition at line 223 of file Ga.php.

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  }
$order
Definition: order.php:55
$orderIds
Definition: results.phtml:9

◆ getPageName()

getPageName ( )

Get a specific page name (may be customized via layout)

Returns
string|null

Definition at line 72 of file Ga.php.

73  {
74  return $this->_getData('page_name');
75  }

◆ getPageTrackingCode()

getPageTrackingCode (   $accountId)

Render regular page tracking javascript code The custom "page name" may be set from layout or somewhere else. It must start from slash.

Parameters
string$accountId
Returns
string https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference#gaObjectMethods deprecated 1066.

Definition at line 87 of file Ga.php.

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  }
escapeHtmlAttr($string, $escapeSingleQuote=true)

◆ getPageTrackingData()

getPageTrackingData (   $accountId)

Return information about page for GA tracking

https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference#gaObjectMethods string $accountId array 100.2.0

Definition at line 204 of file Ga.php.

205  {
206  return [
207  'optPageUrl' => $this->getOptPageUrl(),
208  'isAnonymizedIpActive' => $this->_googleAnalyticsData->isAnonymizedIpActive(),
209  'accountId' => $this->escapeHtmlAttr($accountId, false)
210  ];
211  }
escapeHtmlAttr($string, $escapeSingleQuote=true)

◆ isCookieRestrictionModeEnabled()

isCookieRestrictionModeEnabled ( )

Return cookie restriction mode value.

Returns
bool
Since
100.2.0

Definition at line 178 of file Ga.php.

179  {
180  return $this->cookieHelper->isCookieRestrictionModeEnabled();
181  }

Field Documentation

◆ $_googleAnalyticsData

$_googleAnalyticsData = null
protected

Definition at line 24 of file Ga.php.

◆ $_salesOrderCollection

$_salesOrderCollection
protected

Definition at line 29 of file Ga.php.


The documentation for this class was generated from the following file: