Completed
Push — master ( 4a5166...6912d9 )
by Matthew
03:30 queued 13s
created

AdminScoreController::resultAction()   C

Complexity

Conditions 7
Paths 15

Size

Total Lines 148
Code Lines 83

Duplication

Lines 8
Ratio 5.41 %

Importance

Changes 0
Metric Value
dl 8
loc 148
rs 6.4589
c 0
b 0
f 0
cc 7
eloc 83
nc 15
nop 2

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
namespace AppBundle\Controller;
4
5
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
6
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
9
use DateTime;
10
use Xtools\ProjectRepository;
11
12
class AdminScoreController extends Controller
13
{
14
    /**
15
     * @Route("/adminscore", name="adminscore")
16
     * @Route("/adminscore", name="AdminScore")
17
     * @Route("/adminscore/", name="AdminScoreSlash")
18
     * @Route("/adminscore/index.php", name="AdminScoreIndexPhp")
19
     * @Route("/scottywong tools/adminscore.php", name="AdminScoreLegacy")
20
     * @Route("/adminscore/{project}", name="AdminScoreProject")
21
     */
22
    public function indexAction(Request $request, $project = null)
23
    {
24
        $lh = $this->get("app.labs_helper");
25
        $lh->checkEnabled("adminscore");
26
27
        $projectQuery = $request->query->get('project');
28
        $username = $request->query->get('username');
29
30
        if ($projectQuery != "" && $username != "") {
31
            return $this->redirectToRoute("AdminScoreResult", [ 'project'=>$projectQuery, 'username' => $username ]);
32
        } elseif ($projectQuery != "") {
33
            return $this->redirectToRoute("AdminScoreProject", [ 'project'=>$projectQuery ]);
34
        }
35
36
        // Otherwise fall through.
37
        return $this->render('adminscore/index.html.twig', [
38
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
39
            'xtPage' => 'adminscore',
40
            'xtPageTitle' => 'tool-adminscore',
41
            'xtSubtitle' => 'tool-adminscore-desc',
42
            "project" => $project,
43
        ]);
44
    }
45
46
    /**
47
     * @Route("/adminscore/{project}/{username}", name="AdminScoreResult")
48
     */
49
    public function resultAction($project, $username)
50
    {
51
52
        $lh = $this->get("app.labs_helper");
53
54
        $lh->checkEnabled("adminscore");
55
56
        $username = ucfirst($username);
57
58
        $projectData = ProjectRepository::getProject($project, $this->container);
1 ignored issue
show
Compatibility introduced by
$this->container of type object<Symfony\Component...ion\ContainerInterface> is not a sub-type of object<Symfony\Component...ncyInjection\Container>. It seems like you assume a concrete implementation of the interface Symfony\Component\Depend...tion\ContainerInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
59
60 View Code Duplication
        if (!$projectData->exists()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61
            $this->addFlash("notice", ["invalid-project", $project]);
0 ignored issues
show
Documentation introduced by
array('invalid-project', $project) is of type array<integer,?,{"0":"string","1":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
62
            return $this->redirectToRoute("adminscore");
63
        }
64
65
        $dbName = $projectData->getDatabaseName();
66
        $wikiName = $projectData->getDatabaseName();
67
        $url = $projectData->getUrl();
68
69
        $userTable = $lh->getTable("user", $dbName);
70
        $pageTable = $lh->getTable("page", $dbName);
71
        $loggingTable = $lh->getTable("logging", $dbName, "userindex");
72
        $revisionTable = $lh->getTable("revision", $dbName);
73
        $archiveTable = $lh->getTable("archive", $dbName);
74
75
        // MULTIPLIERS (to review)
76
        $ACCT_AGE_MULT = 1.25;   # 0 if = 365 jours
77
        $EDIT_COUNT_MULT = 1.25;     # 0 if = 10 000
1 ignored issue
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
78
        $USER_PAGE_MULT = 0.1;     # 0 if =
79
        $PATROLS_MULT = 1; # 0 if =
80
        $BLOCKS_MULT = 1.4;     # 0 if = 10
1 ignored issue
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
81
        $AFD_MULT = 1.15;
82
        $RECENT_ACTIVITY_MULT = 0.9;     # 0 if =
83
        $AIV_MULT = 1.15;
84
        $EDIT_SUMMARIES_MULT = 0.8;   # 0 if =
85
        $NAMESPACES_MULT = 1.0;     # 0 if =
86
        $PAGES_CREATED_LIVE_MULT = 1.4; # 0 if =
87
        $PAGES_CREATED_ARCHIVE_MULT = 1.4; # 0 if =
88
        $RPP_MULT = 1.15;     # 0 if =
89
        $USERRIGHTS_MULT = 0.75;   # 0 if =
90
91
        // Grab the connection to the replica database (which is separate from the above)
92
        $conn = $this->get('doctrine')->getManager("replicas")->getConnection();
93
94
        // Prepare the query and execute
95
        $resultQuery = $conn->prepare("
96
        SELECT 'id' AS source, user_id AS value FROM $userTable
97
            WHERE user_name = :username
98
        UNION
99
        SELECT 'account-age' AS source, user_registration AS value FROM $userTable
100
            WHERE user_name=:username
101
        UNION
102
        SELECT 'edit-count' AS source, user_editcount AS value FROM $userTable
103
            WHERE user_name=:username
104
        UNION
105
        SELECT 'user-page' AS source, page_len AS value FROM $pageTable
106
            WHERE page_namespace=2 AND page_title=:username
107
        UNION
108
        SELECT 'patrols' AS source, COUNT(*) AS value FROM $loggingTable
109
            WHERE log_type='patrol'
110
                AND log_action='patrol'
111
                AND log_namespace=0
112
                AND log_deleted=0 AND log_user_text=:username
113
        UNION
114
        SELECT 'blocks' AS source, COUNT(*) AS value FROM $loggingTable l
115
            INNER JOIN $userTable u ON l.log_user = u.user_id
116
            WHERE l.log_type='block' AND l.log_action='block'
117
            AND l.log_namespace=2 AND l.log_deleted=0 AND u.user_name=:username
118
        UNION
119
        SELECT 'afd' AS source, COUNT(*) AS value FROM $revisionTable
120
            WHERE rev_page LIKE 'Articles for deletion/%'
121
                AND rev_page NOT LIKE 'Articles_for_deletion/Log/%'
122
                AND rev_user_text=:username
123
        UNION
124
        SELECT 'recent-activity' AS source, COUNT(*) AS value FROM $revisionTable
125
            WHERE rev_user_text=:username AND rev_timestamp > (now()-INTERVAL 730 day) AND rev_timestamp < now()
126
        UNION
127
        SELECT 'aiv' AS source, COUNT(*) AS value FROM $revisionTable
128
            WHERE rev_page LIKE 'Administrator intervention against vandalism%' AND rev_user_text=:username
129
        UNION
130
        SELECT 'edit-summaries' AS source, COUNT(*) AS value FROM $revisionTable JOIN page ON rev_page=page_id
131
            WHERE page_namespace=0 AND rev_user_text=:username
132
        UNION
133
        SELECT 'namespaces' AS source, count(*) AS value FROM $revisionTable JOIN page ON rev_page=page_id
134
            WHERE rev_user_text=:username AND page_namespace=0
135
        UNION
136
        SELECT 'pages-created-live' AS source, COUNT(*) AS value FROM $revisionTable
137
            WHERE rev_user_text=:username AND rev_parent_id=0
138
        UNION
139
        SELECT 'pages-created-deleted' AS source, COUNT(*) AS value FROM $archiveTable
140
            WHERE ar_user_text=:username AND ar_parent_id=0
141
        UNION
142
        SELECT 'rpp' AS source, COUNT(*) AS value FROM $revisionTable
143
            WHERE rev_page LIKE 'Requests_for_page_protection%' AND rev_user_text=:username
144
        ");
145
146
        $resultQuery->bindParam("username", $username);
147
        $resultQuery->execute();
148
149
        // Fetch the result data
150
        $results = $resultQuery->fetchAll();
151
152
        $master = [];
153
        $total = 0;
154
155
        $id = 0;
156
157
        foreach ($results as $row) {
158
            $key = $row["source"];
159
            $value = $row["value"];
160
161
            if ($key == "acct_age") {
162
                $now = new DateTime();
163
                $date = new DateTime($value);
164
                $diff = $date->diff($now);
165
                $formula = 365*$diff->format("%y")+30*$diff->format("%m")+$diff->format("%d");
166
                $value = $formula-365;
167
            }
168
169
            if ($key == "id") {
170
                $id = $value;
171
            } else {
172
                $multiplierKey = strtoupper($row["source"] . "_MULT");
173
                $multiplier = ( isset($$multiplierKey) ? $$multiplierKey : 1 );
174
                $score = max(min($value * $multiplier, 100), -100);
175
                $master[$key]["mult"] = $multiplier;
176
                $master[$key]["value"] = $value;
177
                $master[$key]["score"] = $score;
178
                $total += $score;
179
            }
180
        }
181
182 View Code Duplication
        if ($id == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
            $this->addFlash("notice", [ "no-result", $username ]);
0 ignored issues
show
Documentation introduced by
array('no-result', $username) is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
184
            return $this->redirectToRoute("AdminScore", [ "project"=>$project ]);
185
        }
186
187
        return $this->render('adminscore/result.html.twig', [
188
            'xtPage' => 'adminscore',
189
            'xtTitle' => $username,
190
            'projectUrl' => $url,
191
            'username' => $username,
192
            'project' => $wikiName,
193
            'master' => $master,
194
            'total' => $total,
195
        ]);
196
    }
197
}
198