-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRedirectsLogger.php
More file actions
143 lines (112 loc) · 2.84 KB
/
RedirectsLogger.php
File metadata and controls
143 lines (112 loc) · 2.84 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
namespace Statamic\Addons\Redirects;
use Statamic\API\File;
use Statamic\API\YAML;
class RedirectsLogger
{
/**
* The path where the logs are stored.
*
* @var string
*/
private $storagePath;
public function __construct($storagePath)
{
$this->storagePath = $storagePath;
}
/**
* @var array
*/
private $data = [
'404' => null,
'manual' => null,
'auto' => null,
];
public function log404($url)
{
$this->loadData('404');
$count = isset($this->data['404'][$url]) ? (int) $this->data['404'][$url] : 0;
$this->data['404'][$url] = ++$count;
return $this;
}
public function logManualRedirect($route)
{
$this->logRedirect('manual', $route);
return $this;
}
public function logAutoRedirect($fromUrl)
{
$this->logRedirect('auto', $fromUrl);
return $this;
}
public function remove404($url)
{
return $this->remove('404', $url);
}
public function removeManualRedirect($route)
{
return $this->remove('manual', $route);
}
public function removeAutoRedirect($url)
{
return $this->remove('auto', $url);
}
public function get404s()
{
$this->loadData('404');
return $this->data['404'];
}
public function getManualRedirects()
{
$this->loadData('manual');
return $this->data['manual'];
}
public function getAutoRedirects()
{
$this->loadData('auto');
return $this->data['auto'];
}
public function flush()
{
foreach ($this->data as $which => $data) {
if ($data !== null) {
File::put($this->getYamlFile($which), YAML::dump($data));
}
}
}
private function remove($which, $url)
{
$this->loadData($which);
if (isset($this->data[$which][$url])) {
unset($this->data[$which][$url]);
}
return $this;
}
private function logRedirect($which, $from)
{
$this->loadData($which);
$count = isset($this->data[$which][$from]) ? (int) $this->data[$which][$from] : 0;
$this->data[$which][$from] = ++$count;
}
private function loadData($which)
{
if ($this->data[$which] === null) {
$file = $this->getYamlFile($which);
$this->data[$which] = $this->parseYaml($file);
}
}
private function getYamlFile($which)
{
return $this->storagePath . 'log_' . $which . '.yaml';
}
private function parseYaml($file) {
if (!File::exists($file)) {
return [];
}
try {
return YAML::parse(File::get($file));
} catch (\Exception $e) {
throw new RedirectsLogParseException($file, $e);
}
}
}