-
Notifications
You must be signed in to change notification settings - Fork 1
/
RedirectsManager.php
100 lines (84 loc) · 2.29 KB
/
RedirectsManager.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
<?php
namespace Statamic\Addons\Redirects;
use Statamic\API\File;
use Statamic\API\YAML;
use Statamic\Events\Data\AddonSettingsSaved;
abstract class RedirectsManager
{
/**
* @var array
*/
protected $redirects;
/**
* Path to the YAML file storing the redirects.
*
* @var string
*/
protected $storagePath;
/**
* @var RedirectsLogger
*/
protected $redirectsLogger;
public function __construct($storagePath, RedirectsLogger $redirectsLogger)
{
$this->storagePath = $storagePath;
$this->redirectsLogger = $redirectsLogger;
$this->loadRedirects();
}
/**
* Remove a redirect identified by the given route.
*
* @param string $route
*
* @return $this
*/
public function remove($route)
{
unset($this->redirects[$route]);
return $this;
}
/**
* @return array
*/
public function all()
{
return collect($this->redirects)
->map(function ($data, $from) {
return $this->get($from);
})
->values()
->all();
}
/**
* Write all redirects to the filesystem.
*/
public function flush()
{
if ($this->redirects !== null) {
File::put($this->storagePath, YAML::dump($this->redirects));
// Emit an event that the redirects have been changed.
// Note: The "AddonSettingsSaved" event is semantically not 100% correct, as we did not change the addon's settings.
// However, it allows the Spock addon to detect changed redirect YAML files, as Spock is listening to this event by default.
event(new AddonSettingsSaved($this->storagePath, $this->redirects));
}
$this->redirectsLogger->flush();
}
/**
* Check if a redirect with the given route/url exists.
*
* @param string $route
*
* @return bool
*/
public function exists($route)
{
return isset($this->redirects[$route]);
}
abstract public function get($route);
protected function loadRedirects()
{
if ($this->redirects === null) {
$this->redirects = File::exists($this->storagePath) ? YAML::parse(File::get($this->storagePath)) : [];
}
}
}