Passed
Push — v3 ( 5261ad...9137a8 )
by Andrew
32:26 queued 04:55
created

TablesController::actionDashboard()   F

Complexity

Conditions 13
Paths 408

Size

Total Lines 77
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 1
Metric Value
eloc 51
c 7
b 0
f 1
dl 0
loc 77
rs 3.2722
cc 13
nc 408
nop 6

How to fix   Long Method    Complexity   

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 nystudio107\retour\helpers\Permission as PermissionHelper;
15
16
use Craft;
17
use craft\db\Query;
18
use craft\helpers\UrlHelper;
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 TablesController extends Controller
30
{
31
    // Constants
32
    // =========================================================================
33
34
    const HANDLED_MAP = [
35
        'handled' => 1,
36
        'nothandled' => 0,
37
    ];
38
39
    // Protected Properties
40
    // =========================================================================
41
42
    /**
43
     * @var    bool|array
44
     */
45
    protected $allowAnonymous = [
46
    ];
47
48
    // Public Methods
49
    // =========================================================================
50
51
    /**
52
     * Handle requests for the dashboard statistics table
53
     *
54
     * @param string $sort
55
     * @param int    $page
56
     * @param int    $per_page
57
     * @param string $filter
58
     * @param int    $siteId
59
     * @param string|null $handled
60
     *
61
     * @return Response
62
     * @throws ForbiddenHttpException
63
     */
64
    public function actionDashboard(
65
        string $sort = 'hitCount|desc',
66
        int $page = 1,
67
        int $per_page = 20,
68
        $filter = '',
69
        $siteId = 0,
70
        $handled = 'all'
71
    ): Response {
72
        PermissionHelper::controllerPermissionCheck('retour:dashboard');
73
        $data = [];
74
        $sortField = 'hitCount';
75
        $sortType = 'DESC';
76
        // Figure out the sorting type
77
        if ($sort !== '') {
78
            if (strpos($sort, '|') === false) {
79
                $sortField = $sort;
80
            } else {
81
                list($sortField, $sortType) = explode('|', $sort);
82
            }
83
        }
84
        // Query the db table
85
        $offset = ($page - 1) * $per_page;
86
        $query = (new Query())
87
            ->from(['{{%retour_stats}}'])
88
            ->offset($offset)
89
            ->limit($per_page)
90
            ->orderBy("{$sortField} {$sortType}");
91
        if ((int)$siteId !== 0) {
92
            $query->where(['siteId' => $siteId]);
93
        }
94
        if ($handled !== 'all') {
95
            $query->where(['handledByRetour' => self::HANDLED_MAP[$handled]]);
96
        }
97
        if ($filter !== '') {
98
            $query->where(['like', 'redirectSrcUrl', $filter]);
99
            $query->orWhere(['like', 'referrerUrl', $filter]);
100
        }
101
        $stats = $query->all();
102
        if ($stats) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stats of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
103
            // Add in the `addLink` field
104
            foreach ($stats as &$stat) {
105
                $stat['addLink'] = '';
106
                if (!$stat['handledByRetour']) {
107
                    $encodedUrl = urlencode('/'.ltrim($stat['redirectSrcUrl'], '/'));
108
                    $stat['addLink'] = UrlHelper::cpUrl('retour/add-redirect', [
109
                        'defaultUrl' => $encodedUrl
110
                    ]);
111
                }
112
            }
113
            // Format the data for the API
114
            $data['data'] = $stats;
115
            $query = (new Query())
116
                ->from(['{{%retour_stats}}']);
117
            if ((int)$siteId !== 0) {
118
                $query->where(['siteId' => $siteId]);
119
            }
120
            if ($handled !== 'all') {
121
                $query->where(['handledByRetour' => self::HANDLED_MAP[$handled]]);
122
            }
123
            if ($filter !== '') {
124
                $query->where(['like', 'redirectSrcUrl', $filter]);
125
                $query->orWhere(['like', 'referrerUrl', $filter]);
126
            }
127
            $count = $query->count();
128
            $data['links']['pagination'] = [
129
                'total' => $count,
130
                'per_page' => $per_page,
131
                'current_page' => $page,
132
                'last_page' => ceil($count / $per_page),
133
                'next_page_url' => null,
134
                'prev_page_url' => null,
135
                'from' => $offset + 1,
136
                'to' => $offset + ($count > $per_page ? $per_page : $count),
137
            ];
138
        }
139
140
        return $this->asJson($data);
141
    }
142
143
    /**
144
     * Handle requests for the dashboard redirects table
145
     *
146
     * @param string $sort
147
     * @param int    $page
148
     * @param int    $per_page
149
     * @param string $filter
150
     * @param null   $siteId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $siteId is correct as it would always require null to be passed?
Loading history...
151
     *
152
     * @return Response
153
     * @throws ForbiddenHttpException
154
     */
155
    public function actionRedirects(
156
        string $sort = 'hitCount|desc',
157
        int $page = 1,
158
        int $per_page = 20,
159
        $filter = '',
160
        $siteId = 0
161
    ): Response {
162
        PermissionHelper::controllerPermissionCheck('retour:redirects');
163
        $data = [];
164
        $sortField = 'hitCount';
165
        $sortType = 'DESC';
166
        // Figure out the sorting type
167
        if ($sort !== '') {
168
            if (strpos($sort, '|') === false) {
169
                $sortField = $sort;
170
            } else {
171
                list($sortField, $sortType) = explode('|', $sort);
172
            }
173
        }
174
        // Query the db table
175
        $offset = ($page - 1) * $per_page;
176
        $query = (new Query())
177
            ->from(['{{%retour_static_redirects}}'])
178
            ->offset($offset)
179
            ->limit($per_page)
180
            ->orderBy("{$sortField} {$sortType}");
181
        if ((int)$siteId !== 0) {
182
            $query->where(['siteId' => $siteId]);
183
        }
184
        if ($filter !== '') {
185
            $query->where(['like', 'redirectSrcUrl', $filter]);
186
            $query->orWhere(['like', 'redirectDestUrl', $filter]);
187
        }
188
        $redirects = $query->all();
189
        // Add in the `deleteLink` field and clean up the redirects
190
        foreach ($redirects as &$redirect) {
191
            // Make sure the destination URL is not a regex
192
            if ($redirect['redirectMatchType'] !== 'exactmatch') {
193
                if (preg_match("/\$\d+/", $redirect['redirectDestUrl'])) {
194
                    $redirect['redirectDestUrl'] = '';
195
                }
196
            }
197
            // Handle extracting the site name
198
            $redirect['siteName'] = Craft::t('retour', 'All Sites');
199
            if ($redirect['siteId']) {
200
                $sites = Craft::$app->getSites();
201
                $site = $sites->getSiteById($redirect['siteId']);
202
                if ($site) {
203
                    $redirect['siteName'] = $site->name;
204
                }
205
            }
206
207
            $redirect['editLink'] = UrlHelper::cpUrl('retour/edit-redirect/'.$redirect['id']);
208
        }
209
        // Format the data for the API
210
        if ($redirects) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $redirects of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
211
            $data['data'] = $redirects;
212
            $query = (new Query())
213
                ->from(['{{%retour_static_redirects}}']);
214
            if ((int)$siteId !== 0) {
215
                $query->where(['siteId' => $siteId]);
216
            }
217
            if ($filter !== '') {
218
                $query->where(['like', 'redirectSrcUrl', $filter]);
219
                $query->orWhere(['like', 'redirectDestUrl', $filter]);
220
            }
221
            $count = $query->count();
222
            $data['links']['pagination'] = [
223
                'total' => $count,
224
                'per_page' => $per_page,
225
                'current_page' => $page,
226
                'last_page' => ceil($count / $per_page),
227
                'next_page_url' => null,
228
                'prev_page_url' => null,
229
                'from' => $offset + 1,
230
                'to' => $offset + ($count > $per_page ? $per_page : $count),
231
            ];
232
        }
233
234
        return $this->asJson($data);
235
    }
236
237
    // Protected Methods
238
    // =========================================================================
239
}
240