Passed
Push — develop ( 7770ec...d3629d )
by Andrew
04:37
created

ChartsController::actionDashboard()   B

Complexity

Conditions 7
Paths 32

Size

Total Lines 61
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 61
rs 8.223
c 0
b 0
f 0
cc 7
nc 32
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Retour plugin for Craft CMS 3.x
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/
9
 * @copyright Copyright (c) 2018 nystudio107
10
 */
11
12
namespace nystudio107\retour\controllers;
13
14
use Craft;
15
use nystudio107\retour\helpers\Permission as PermissionHelper;
16
17
use craft\db\Query;
18
use craft\helpers\ArrayHelper;
19
use craft\web\Controller;
20
21
use yii\web\ForbiddenHttpException;
22
use yii\web\Response;
23
24
/**
25
 * @author    nystudio107
26
 * @package   Retour
27
 * @since     3.0.0
28
 */
29
class ChartsController extends Controller
30
{
31
    // Constants
32
    // =========================================================================
33
34
    // Protected Properties
35
    // =========================================================================
36
37
    /**
38
     * @var    bool|array
39
     */
40
    protected $allowAnonymous = [
41
    ];
42
43
    // Public Methods
44
    // =========================================================================
45
46
    /**
47
     * The Dashboard chart
48
     *
49
     * @param string $range
50
     *
51
     * @return Response
52
     * @throws ForbiddenHttpException
53
     */
54
    public function actionDashboard(string $range = 'day'): Response
55
    {
56
        PermissionHelper::controllerPermissionCheck('retour:dashboard');
57
        $data = [];
58
        $days = 1;
59
        switch ($range) {
60
            case 'day':
61
                $days = 1;
62
                break;
63
            case 'week':
64
                $days = 7;
65
                break;
66
            case 'month':
67
                $days = 30;
68
                break;
69
        }
70
        // Different dbs do it different ways
71
        $stats = null;
72
        $db = Craft::$app->getDb();
73
        if ($db->getIsMysql()) {
74
            // Query the db
75
            $stats = (new Query())
76
                ->from('{{%retour_stats}}')
77
                ->select([
78
                    "DATE_FORMAT(hitLastTime, '%Y-%m-%d') AS date_formatted",
79
                    'COUNT(redirectSrcUrl) AS cnt',
80
                    'COUNT(handledByRetour = 1 or null) as handled_cnt',
81
                ])
82
                ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
83
                ->orderBy('date_formatted ASC')
84
                ->groupBy('date_formatted')
85
                ->all();
86
        }
87
        if ($db->getIsPgsql()) {
88
            // Query the db
89
            $stats = (new Query())
90
                ->from('{{%retour_stats}}')
91
                ->select([
92
                    "to_char(\"hitLastTime\", 'yyyy-mm-dd') AS date_formatted",
93
                    "COUNT(\"redirectSrcUrl\") AS cnt",
94
                    "COUNT(CASE WHEN \"handledByRetour\" = true THEN 1 END) as handled_cnt",
95
                ])
96
                ->where("\"hitLastTime\" >= ( CURRENT_TIMESTAMP - INTERVAL '{$days} days' )")
97
                ->orderBy('date_formatted ASC')
98
                ->groupBy('date_formatted')
99
                ->all();
100
        }
101
        if ($stats) {
102
            $data[] = [
103
                'name' => '404 hits',
104
                'data' => array_merge(['0'], ArrayHelper::getColumn($stats, 'cnt')),
105
                'labels' => array_merge(['-'], ArrayHelper::getColumn($stats, 'date_formatted')),
106
            ];
107
            $data[] = [
108
                'name' => 'Handled 404 hits',
109
                'data' => array_merge(['0'], ArrayHelper::getColumn($stats, 'handled_cnt')),
110
                'labels' => array_merge(['-'], ArrayHelper::getColumn($stats, 'date_formatted')),
111
            ];
112
        }
113
114
        return $this->asJson($data);
115
    }
116
117
    /**
118
     * The Dashboard chart
119
     *
120
     * @param int $days
121
     *
122
     * @return Response
123
     */
124
    public function actionWidget($days = 1): Response
125
    {
126
        $data = [];
127
        // Query the db
128
        $stats = (new Query())
129
            ->from('{{%retour_stats}}')
130
            ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
131
            ->count();
132
        $handledStats = (new Query())
133
            ->from('{{%retour_stats}}')
134
            ->where("hitLastTime >= ( CURDATE() - INTERVAL '{$days}' DAY )")
135
            ->andWhere('handledByRetour is TRUE')
136
            ->count();
137
        if ($stats) {
138
            $data = [
139
                (int)$stats,
140
                (int)$handledStats,
141
            ];
142
        }
143
144
        return $this->asJson($data);
145
    }
146
147
    // Protected Methods
148
    // =========================================================================
149
}
150