Created
October 30, 2019 01:42
-
-
Save sdeering/e331cee224e7d3e1f21697a7a17c9230 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Send Google analytics tracking event. | |
* | |
* @param mixed $action | |
* Event action. | |
*/ | |
public function sendGoogleTrackingEvent($action) { | |
if (!$this->isProduction()) return; | |
$googleAnalyticsUA = 'UA-XXXXXXXX-XX'; | |
// phpcs:disable | |
$data = [ | |
'v' => 1, | |
't' => 'event', | |
'tid' => $googleAnalyticsUA, | |
'cid' => \Drupal::service('uuid')->generate(), | |
'ec' => 'Category name', | |
'ea' => 'Action name, | |
'el' => 'Label name', | |
'uip' => \Drupal::request()->getClientIp(), | |
'ua' => $_SERVER['HTTP_USER_AGENT'], | |
]; | |
// phpcs:enable | |
$url = 'https://www.google-analytics.com/collect'; | |
$content = http_build_query($data); | |
$content = utf8_encode($content); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: application/x-www-form-urlencoded']); | |
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); | |
curl_setopt($ch, CURLOPT_POST, TRUE); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $content); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
curl_exec($ch); | |
curl_close($ch); | |
} | |
/** | |
* Check if app is running in production. | |
*/ | |
public function isProduction() { | |
return (strpos($_SERVER['HTTP_HOST'], 'production.com') !== FALSE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment