This repository has been archived by the owner on Jul 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
TrackingCodeFile.php
113 lines (94 loc) · 2.71 KB
/
TrackingCodeFile.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* Copyright (C) Piwik PRO - All rights reserved.
*
* Using this code requires that you first get a license from Piwik PRO.
* Unauthorized copying of this file, via any medium is strictly prohibited.
*
* @link http://piwik.pro
*/
namespace Piwik\Plugins\CustomTrackerJs;
use Piwik\Plugins\CustomTrackerJs\Exception\AccessDeniedException;
use Piwik\Plugins\CustomTrackerJs\TrackingCode\Extension;
use Piwik\Plugins\CustomTrackerJs\TrackingCode\ExtensionCollection;
class TrackingCodeFile
{
/**
* @var string
*/
private $originalFile;
/**
* @var string
*/
private $copyFile;
/** @var ExtensionCollection */
private $extensionCollection;
public function __construct($originalFile, ExtensionCollection $extensionCollection)
{
$this->originalFile = $originalFile;
$this->copyFile = $originalFile . '._ct_bck';
$this->extensionCollection = $extensionCollection;
}
public function save()
{
if (!$this->hasAccess()) {
throw new AccessDeniedException("You have no access to piwik.js file");
}
if (!$this->hasCopy()) {
$this->createCopyOfTrackerFile();
}
file_put_contents($this->originalFile, $this->getContent());
}
private function getContent()
{
$contentTop = '';
$contentBottom = '';
foreach ($this->extensionCollection->asArray() as $extension) {
$content = $this->getSignatureWithContent($extension->getName(), $extension->getCode()) . PHP_EOL;
switch ($extension->getPosition()) {
case Extension::POSITION_TOP:
$contentTop .= $content;
break;
case Extension::POSITION_BOTTOM:
$contentBottom .= $content;
break;
}
}
return $contentTop . file_get_contents($this->copyFile) . $contentBottom;
}
/**
* @return bool
*/
private function hasAccess()
{
return is_readable($this->originalFile) && is_writable($this->originalFile);
}
/**
* @param string $name
* @param string $content
* @return string
*/
private function getSignatureWithContent($name, $content)
{
return sprintf(
"\n/* GENERATED: %s */\n%s\n/* END GENERATED: %s */\n",
$name,
$content,
$name
);
}
private function createCopyOfTrackerFile()
{
file_put_contents(
$this->copyFile,
file_get_contents($this->originalFile)
);
}
/**
* @return bool
*/
private function hasCopy()
{
return file_exists($this->copyFile);
}
}