/
MeasurementProtocol.php
73 lines (58 loc) · 1.92 KB
/
MeasurementProtocol.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace baibaratsky\yii\google\analytics;
use TheIconic\Tracking\GoogleAnalytics\Analytics;
use yii\base\BaseObject;
/**
* Class MeasurementProtocol
* @package baibaratsky\yii\google\analytics
*/
class MeasurementProtocol extends BaseObject
{
/** @var string Tracking ID (UA-XXXX-Y) */
public $trackingId;
/** @var string Protocol version */
public $version = '1';
/** @var bool Use HTTPS instead of plain HTTP */
public $useSsl = false;
/** @var bool Override the IP address by the user’s */
public $overrideIp = true;
/** @var bool Anonymize the IP address of the sender */
public $anonymizeIp = false;
/** @var bool Use asynchronous requests (not waiting for a response) */
public $asyncMode = false;
/** @var bool Try to set ClientId automatically from `_ga` cookie */
public $autoSetClientId = false;
/**
* @return Analytics
*/
public function request()
{
$request = new Analytics($this->useSsl);
$request->setTrackingId($this->trackingId)
->setProtocolVersion($this->version)
->setAsyncRequest($this->asyncMode);
if ($this->overrideIp && isset(\Yii::$app->request->userIP)) {
$request->setIpOverride(\Yii::$app->request->userIP);
}
if ($this->anonymizeIp) {
$request->setAnonymizeIp(1);
}
if ($this->autoSetClientId) {
$clientId = $this->extractClientIdFromCookie();
if (!empty($clientId)) {
$request->setClientId($clientId);
}
}
return $request;
}
/**
* @return string
*/
protected function extractClientIdFromCookie()
{
$cookie = \Yii::$app->request->cookies->getValue('_ga', '');
$cookieParts = explode('.', $cookie);
$clientIdParts = array_slice($cookieParts, -2);
return implode('.', $clientIdParts);
}
}