Passed
Push — master ( 1c0aa5...b7dbf0 )
by MusikAnimal
05:37
created

AdminScoreController::resultAction()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 139
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 80
nc 10
nop 1
dl 0
loc 139
ccs 0
cts 0
cp 0
crap 56
rs 6.4589
c 0
b 0
f 0

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
 * This file contains only the AdminScoreController class.
4
 */
5
6
namespace AppBundle\Controller;
7
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpFoundation\RedirectResponse;
13
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
14
use DateTime;
15
use Xtools\ProjectRepository;
16
use Xtools\UserRepository;
17
18
/**
19
 * The AdminScoreController serves the search form and results page of the AdminScore tool
20
 */
21
class AdminScoreController extends XtoolsController
22
{
23
24
    /**
25
     * Get the tool's shortname.
26
     * @return string
27
     * @codeCoverageIgnore
28
     */
29
    public function getToolShortname()
30
    {
31
        return 'adminscore';
32
    }
33
34
    /**
35
     * Display the AdminScore search form.
36
     * @Route("/adminscore", name="adminscore")
37
     * @Route("/adminscore", name="AdminScore")
38
     * @Route("/adminscore/", name="AdminScoreSlash")
39
     * @Route("/adminscore/index.php", name="AdminScoreIndexPhp")
40
     * @Route("/scottywong tools/adminscore.php", name="AdminScoreLegacy")
41
     * @Route("/adminscore/{project}", name="AdminScoreProject")
42
     * @param Request $request The HTTP request.
43
     * @return Response
44
     */
45
    public function indexAction(Request $request)
46
    {
47
        $params = $this->parseQueryParams($request);
48
49
        // Redirect if we have a project and user.
50
        if (isset($params['project']) && isset($params['username'])) {
51
            return $this->redirectToRoute('AdminScoreResult', $params);
52
        }
53
54
        // Convert the given project (or default project) into a Project instance.
55
        $params['project'] = $this->getProjectFromQuery($params);
56
57
        return $this->render('adminscore/index.html.twig', [
58
            'xtPage' => 'adminscore',
59
            'xtPageTitle' => 'tool-adminscore',
60
            'xtSubtitle' => 'tool-adminscore-desc',
61
            'project' => $params['project'],
62
        ]);
63
    }
64
65
    /**
66
     * Display the AdminScore results.
67
     * @Route("/adminscore/{project}/{username}", name="AdminScoreResult")
68
     * @param Request $request The HTTP request.
69
     * @return Response
70
     * @todo Move SQL to a model.
71
     * @codeCoverageIgnore
72
     */
73
    public function resultAction(Request $request)
74
    {
75
        // Second parameter causes it return a Redirect to the index if the user has too many edits.
76
        $ret = $this->validateProjectAndUser($request, 'adminscore');
77
        if ($ret instanceof RedirectResponse) {
0 ignored issues
show
introduced by
$ret is always a sub-type of Symfony\Component\HttpFoundation\RedirectResponse.
Loading history...
78
            return $ret;
79
        } else {
80
            list($projectData, $user) = $ret;
81
        }
82
83
        $dbName = $projectData->getDatabaseName();
84
        $projectRepo = $projectData->getRepository();
85
86
        $userTable = $projectRepo->getTableName($dbName, 'user');
87
        $pageTable = $projectRepo->getTableName($dbName, 'page');
88
        $loggingTable = $projectRepo->getTableName($dbName, 'logging', 'userindex');
89
        $revisionTable = $projectRepo->getTableName($dbName, 'revision');
90
        $archiveTable = $projectRepo->getTableName($dbName, 'archive');
91
92
        // MULTIPLIERS (to review)
93
        $multipliers = [
94
            'account-age-mult' => 1.25,             # 0 if = 365 jours
95
            'edit-count-mult' => 1.25,              # 0 if = 10 000
96
            'user-page-mult' => 0.1,                # 0 if =
97
            'patrols-mult' => 1,                    # 0 if =
98
            'blocks-mult' => 1.4,                   # 0 if = 10
99
            'afd-mult' => 1.15,
100
            'recent-activity-mult' => 0.9,          # 0 if =
101
            'aiv-mult' => 1.15,
102
            'edit-summaries-mult' => 0.8,           # 0 if =
103
            'namespaces-mult' => 1.0,               # 0 if =
104
            'pages-created-live-mult' => 1.4,       # 0 if =
105
            'pages-created-deleted-mult' => 1.4,    # 0 if =
106
            'rpp-mult' => 1.15,                     # 0 if =
107
            'user-rights-mult' => 0.75,             # 0 if =
108
        ];
109
110
        // Grab the connection to the replica database (which is separate from the above)
111
        $conn = $this->get('doctrine')->getManager("replicas")->getConnection();
112
113
        // Prepare the query and execute
114
        $resultQuery = $conn->prepare("
115
        SELECT 'account-age' AS source, user_registration AS value FROM $userTable
116
            WHERE user_name = :username
117
        UNION
118
        SELECT 'edit-count' AS source, user_editcount AS value FROM $userTable
119
            WHERE user_name = :username
120
        UNION
121
        SELECT 'user-page' AS source, page_len AS value FROM $pageTable
122
            WHERE page_namespace = 2 AND page_title = :username
123
        UNION
124
        SELECT 'patrols' AS source, COUNT(*) AS value FROM $loggingTable
125
            WHERE log_type = 'patrol'
126
                AND log_action = 'patrol'
127
                AND log_namespace = 0
128
                AND log_deleted = 0 AND log_user_text = :username
129
        UNION
130
        SELECT 'blocks' AS source, COUNT(*) AS value FROM $loggingTable l
131
            INNER JOIN $userTable u ON l.log_user = u.user_id
132
            WHERE l.log_type = 'block' AND l.log_action = 'block'
133
            AND l.log_namespace = 2 AND l.log_deleted = 0 AND u.user_name = :username
134
        UNION
135
        SELECT 'afd' AS source, COUNT(*) AS value FROM $revisionTable r
136
          INNER JOIN $pageTable p on p.page_id = r.rev_page
137
            WHERE p.page_title LIKE 'Articles_for_deletion/%'
138
                AND p.page_title NOT LIKE 'Articles_for_deletion/Log/%'
139
                AND r.rev_user_text = :username
140
        UNION
141
        SELECT 'recent-activity' AS source, COUNT(*) AS value FROM $revisionTable
142
            WHERE rev_user_text = :username AND rev_timestamp > (now()-INTERVAL 730 day) AND rev_timestamp < now()
143
        UNION
144
        SELECT 'aiv' AS source, COUNT(*) AS value FROM $revisionTable r
145
          INNER JOIN $pageTable p on p.page_id = r.rev_page
146
            WHERE p.page_title LIKE 'Administrator_intervention_against_vandalism%'
147
                AND r.rev_user_text = :username
148
        UNION
149
        SELECT 'edit-summaries' AS source, COUNT(*) AS value FROM $revisionTable JOIN $pageTable ON rev_page = page_id
150
            WHERE page_namespace = 0 AND rev_user_text = :username
151
        UNION
152
        SELECT 'namespaces' AS source, count(*) AS value FROM $revisionTable JOIN $pageTable ON rev_page = page_id
153
            WHERE rev_user_text = :username AND page_namespace = 0
154
        UNION
155
        SELECT 'pages-created-live' AS source, COUNT(*) AS value FROM $revisionTable
156
            WHERE rev_user_text = :username AND rev_parent_id = 0
157
        UNION
158
        SELECT 'pages-created-deleted' AS source, COUNT(*) AS value FROM $archiveTable
159
            WHERE ar_user_text = :username AND ar_parent_id = 0
160
        UNION
161
        SELECT 'rpp' AS source, COUNT(*) AS value FROM $revisionTable r
162
          INNER JOIN $pageTable p on p.page_id = r.rev_page
163
            WHERE p.page_title LIKE 'Requests_for_page_protection%'
164
                AND r.rev_user_text = :username;
165
        ");
166
167
        $username = $user->getUsername();
168
        $resultQuery->bindParam("username", $username);
169
        $resultQuery->execute();
170
171
        // Fetch the result data
172
        $results = $resultQuery->fetchAll();
173
174
        $master = [];
175
        $total = 0;
176
177
        foreach ($results as $row) {
178
            $key = $row['source'];
179
            $value = $row['value'];
180
181
            if ($key === 'account-age') {
182
                if ($value == null) {
183
                    $value = 0;
184
                } else {
185
                    $now = new DateTime();
186
                    $date = new DateTime($value);
187
                    $diff = $date->diff($now);
188
                    $formula = 365 * $diff->format('%y') + 30 * $diff->format('%m') + $diff->format('%d');
189
                    if ($formula < 365) {
190
                        $multipliers["account-age-mult"] = 0;
191
                    }
192
                    $value = $formula;
193
                }
194
            }
195
196
            $multiplierKey = $row['source'] . '-mult';
197
            $multiplier = isset($multipliers[$multiplierKey]) ? $multipliers[$multiplierKey] : 1;
198
            $score = max(min($value * $multiplier, 100), -100);
199
            $master[$key]['mult'] = $multiplier;
200
            $master[$key]['value'] = $value;
201
            $master[$key]['score'] = $score;
202
            $total += $score;
203
        }
204
205
        return $this->render('adminscore/result.html.twig', [
206
            'xtPage' => 'adminscore',
207
            'xtTitle' => $username,
208
            'project' => $projectData,
209
            'user' => $user,
210
            'master' => $master,
211
            'total' => $total,
212
        ]);
213
    }
214
}
215