-
Notifications
You must be signed in to change notification settings - Fork 34
/
Redirects.php
116 lines (99 loc) · 2.92 KB
/
Redirects.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
114
115
116
<?php
/**
*
* @author dolphiq
* @copyright Copyright (c) 2017 dolphiq
* @link https://dolphiq.nl/
*/
namespace dolphiq\redirect\services;
use Craft;
use craft\helpers\Db;
use dolphiq\redirect\elements\Redirect;
use yii\base\Component;
use yii\db\Expression;
/**
* Class Redirects service.
*
*/
class Redirects extends Component
{
// Public Methods
// =========================================================================
/**
* Returns the redirects defined in `config/redirects.php`
*
* @return array
*/
public function getConfigFileRedirects(): array
{
$path = Craft::$app->getPath()->getConfigPath() . DIRECTORY_SEPARATOR . 'redirects.php';
if (file_exists($path)) {
$routes = require $path;
if (is_array($routes)) {
// Check for any site-specific routes
$siteHandle = Craft::$app->getSites()->currentSite->handle;
if (
isset($routes[$siteHandle]) &&
is_array($routes[$siteHandle]) &&
!isset($routes[$siteHandle]['route']) &&
!isset($routes[$siteHandle]['template'])
) {
$localizedRoutes = $routes[$siteHandle];
unset($routes[$siteHandle]);
// Merge them so that the localized routes come first
$routes = array_merge($localizedRoutes, $routes);
}
return $routes;
}
}
return [];
}
/**
* Returns the routes defined in the CP.
*
* @return array
*/
public function getAllRedirectsForSite($siteId = null): array
{
$results = Redirect::find()->andWhere(Db::parseParam('elements_sites.siteId', $siteId))->all();
return $results;
}
/**
* Returns a redirect by its ID.
*
* @param int $redirectId
* @param int|null $siteId
*
* @return Redirect|null
*/
public function getRedirectById(int $redirectId, int $siteId = null)
{
/** @noinspection PhpIncompatibleReturnTypeInspection */
return Craft::$app->getElements()->getElementById($redirectId, Redirect::class, $siteId);
}
/**
* Register a hit to the redirect by its ID.
*
* @param int $redirectId
*
* @return bool
*/
public function registerHitById(int $redirectId, $destinationUrl = ''): bool
{
// simple update to keep it fast
if ($redirectId < 1) {
return false;
}
$res = \Yii::$app->db->createCommand()
->update(
'{{%dolphiq_redirects}}',
[
'hitAt' => new Expression('now()'),
'hitCount' => new Expression('{{hitCount}} + 1'),
],
['id' => $redirectId]
)
->execute();
return true;
}
}