forked from gridonic/statamic-redirects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoRedirectsManager.php
More file actions
94 lines (79 loc) · 2.28 KB
/
AutoRedirectsManager.php
File metadata and controls
94 lines (79 loc) · 2.28 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
<?php
namespace Statamic\Addons\Redirects;
class AutoRedirectsManager extends RedirectsManager
{
/**
* Add or update the given redirect.
*
* @param AutoRedirect $redirect
*
* @return AutoRedirectsManager
*/
public function add(AutoRedirect $redirect)
{
if ($redirect->getFromUrl() === $redirect->getToUrl()) {
return $this;
}
$data = $redirect->toArray();
unset($data['from']);
// If the target is a redirect source, remove it.
if ($this->exists($redirect->getToUrl())) {
$this->remove($redirect->getToUrl());
}
// If the source is itself a target, optimize existing redirects to directly redirect to the new target.
collect($this->redirects)
->filter(function ($redirectData) use ($redirect) {
return $redirectData['to'] === $redirect->getFromUrl();
})
->each(function ($redirectData, $fromUrl) use ($redirect) {
$this->redirects[$fromUrl]['to'] = $redirect->getToUrl();
});
$this->redirects[$redirect->getFromUrl()] = $data;
return $this;
}
/**
* {@inheritdoc}
*/
public function remove($url)
{
parent::remove($url);
$this->redirectsLogger->removeAutoRedirect($url);
return $this;
}
/**
* Remove all redirects affected by the given content UUID.
*
* @param string $contentId
*
* @return AutoRedirectsManager
*/
public function removeRedirectsOfContentId($contentId)
{
collect($this->redirects)
->filter(function ($redirect) use ($contentId) {
return $redirect['content_id'] === $contentId;
})
->each(function ($redirect, $from) {
$this->remove($from);
});
return $this;
}
/**
* Get a redirect by URL.
*
* @param string $url
*
* @return AutoRedirect
*/
public function get($url)
{
if (!$this->exists($url)) {
return null;
}
$data = $this->redirects[$url];
return (new AutoRedirect())
->setFromUrl($url)
->setToUrl($data['to'])
->setContentId($data['content_id']);
}
}