ChartsController::actionWidget()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 39
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 39
rs 9.456
c 0
b 0
f 0
cc 4
nc 8
nop 1
1
<?php
2
/**
3
 * Retour plugin for Craft CMS
4
 *
5
 * Retour allows you to intelligently redirect legacy URLs, so that you don't
6
 * lose SEO value when rebuilding & restructuring a website
7
 *
8
 * @link      https://nystudio107.com/
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
9
 * @copyright Copyright (c) 2018 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
10
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
11
12
namespace nystudio107\retour\controllers;
13
14
use Craft;
15
use craft\db\Query;
16
use craft\helpers\ArrayHelper;
17
use craft\web\Controller;
18
use nystudio107\retour\helpers\Permission as PermissionHelper;
19
use yii\web\ForbiddenHttpException;
20
use yii\web\Response;
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
24
 * @package   Retour
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
25
 * @since     3.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
26
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
27
class ChartsController extends Controller
28
{
29
    // Constants
30
    // =========================================================================
31
32
    // Protected Properties
33
    // =========================================================================
34
35
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
36
     * @inheritdoc
37
     */
38
    protected array|bool|int $allowAnonymous = [
39
    ];
40
41
    // Public Methods
42
    // =========================================================================
43
44
    /**
45
     * The Dashboard chart
46
     *
47
     * @param string $range
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
48
     * @param int $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
49
     *
50
     * @return Response
51
     * @throws ForbiddenHttpException
52
     */
53
    public function actionDashboard(string $range = 'day', int $siteId = 0): Response
54
    {
55
        PermissionHelper::controllerPermissionCheck('retour:dashboard');
56
        $data = [];
57
        $days = 1;
58
        switch ($range) {
59
            case 'day':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
60
                $days = 1;
61
                break;
62
            case 'week':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
63
                $days = 7;
64
                break;
65
            case 'month':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 12
Loading history...
66
                $days = 30;
67
                break;
68
        }
69
        // Different dbs do it different ways
70
        $stats = null;
71
        $db = Craft::$app->getDb();
72
        if ($db->getIsMysql()) {
73
            // Query the db
74
            $query = (new Query())
75
                ->from('{{%retour_stats}}')
76
                ->select([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
77
                    "DATE_FORMAT(hitLastTime, '%Y-%m-%d') AS date_formatted",
78
                    'COUNT(redirectSrcUrl) AS cnt',
79
                    'COUNT(handledByRetour = 1 or null) as handled_cnt',
80
                ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
81
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )");
82
            if ((int)$siteId !== 0) {
83
                $query->andWhere(['siteId' => $siteId]);
84
            }
85
            $query
86
                ->orderBy('date_formatted ASC')
87
                ->groupBy('date_formatted');
88
            $stats = $query->all();
89
        }
90
        if ($db->getIsPgsql()) {
91
            // Query the db
92
            $query = (new Query())
93
                ->from('{{%retour_stats}}')
94
                ->select([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
95
                    "to_char(\"hitLastTime\", 'yyyy-mm-dd') AS date_formatted",
96
                    "COUNT(\"redirectSrcUrl\") AS cnt",
97
                    "COUNT(CASE WHEN \"handledByRetour\" = true THEN 1 END) as handled_cnt",
98
                ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
99
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )");
100
            if ((int)$siteId !== 0) {
101
                $query->andWhere(['siteId' => $siteId]);
102
            }
103
            $query
104
                ->orderBy('date_formatted ASC')
105
                ->groupBy('date_formatted');
106
            $stats = $query->all();
107
        }
108
        if ($stats) {
109
            $data[] = [
110
                'name' => '404 hits',
111
                'data' => array_merge(['0'], ArrayHelper::getColumn($stats, 'cnt')),
112
                'labels' => array_merge(['-'], ArrayHelper::getColumn($stats, 'date_formatted')),
113
            ];
114
            $data[] = [
115
                'name' => 'Handled 404 hits',
116
                'data' => array_merge(['0'], ArrayHelper::getColumn($stats, 'handled_cnt')),
117
                'labels' => array_merge(['-'], ArrayHelper::getColumn($stats, 'date_formatted')),
118
            ];
119
        }
120
121
        return $this->asJson($data);
122
    }
123
124
    /**
125
     * The Dashboard chart
126
     *
127
     * @param int $days
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
128
     *
129
     * @return Response
130
     */
131
    public function actionWidget(int $days = 1): Response
132
    {
133
        $data = [];
134
        // Different dbs do it different ways
135
        $stats = null;
136
        $handledStats = null;
137
        $db = Craft::$app->getDb();
138
        if ($db->getIsMysql()) {
139
            // Query the db
140
            $stats = (new Query())
141
                ->from('{{%retour_stats}}')
142
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
143
                ->count();
144
            $handledStats = (new Query())
145
                ->from('{{%retour_stats}}')
146
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
147
                ->andWhere('handledByRetour is TRUE')
148
                ->count();
149
        }
150
        if ($db->getIsPgsql()) {
151
            // Query the db
152
            $stats = (new Query())
153
                ->from('{{%retour_stats}}')
154
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
155
                ->count();
156
            $handledStats = (new Query())
157
                ->from('{{%retour_stats}}')
158
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
159
                ->andWhere('"handledByRetour" = TRUE')
160
                ->count();
161
        }
162
        if ($stats) {
163
            $data = [
164
                (int)$stats,
165
                (int)$handledStats,
166
            ];
167
        }
168
169
        return $this->asJson($data);
170
    }
171
172
    // Protected Methods
173
    // =========================================================================
174
}
175