Completed
Push — master ( 458768...717411 )
by Sam
03:06
created

EditCounterController::generalStatsAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 75
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 75
rs 9
c 0
b 0
f 0
cc 1
eloc 15
nc 1
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 AppBundle\Helper\ApiHelper;
6
use AppBundle\Helper\AutomatedEditsHelper;
7
use AppBundle\Helper\LabsHelper;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\Request;
11
use Xtools\EditCounter;
12
use Xtools\EditCounterRepository;
13
use Xtools\Project;
14
use Xtools\ProjectRepository;
15
use Xtools\User;
16
use Xtools\UserRepository;
17
18
class EditCounterController extends Controller
19
{
20
21
    /** @var ApiHelper */
22
    protected $apiHelper;
23
24
    /** @var LabsHelper */
25
    protected $labsHelper;
26
27
    /**
28
     * Every action in this controller calls this first.
29
     * @param string|boolean $project
30
     */
31
    public function init($project = false, $username = false)
0 ignored issues
show
Unused Code introduced by
The parameter $username is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
32
    {
33
        $this->labsHelper = $this->get('app.labs_helper');
34
        $this->apiHelper = $this->get('app.api_helper');
35
        $this->labsHelper->checkEnabled("ec");
36
        if ($project) {
37
            $this->labsHelper->databasePrepare($project);
38
        }
39
    }
40
41
    /**
42
     * @Route("/ec", name="ec")
43
     * @Route("/ec", name="EditCounter")
44
     * @Route("/ec/", name="EditCounterSlash")
45
     * @Route("/ec/index.php", name="EditCounterIndexPhp")
46
     * @Route("/ec/{project}", name="EditCounterProject")
47
     */
48
    public function indexAction(Request $request, $project = null)
49
    {
50
        $queryProject = $request->query->get('project');
51
        $username = $request->query->get('username');
52
53
        if (($project || $queryProject) && $username) {
54
            $routeParams = [ 'project'=>($project ?: $queryProject), 'username' => $username ];
55
            return $this->redirectToRoute("EditCounterResult", $routeParams);
56
        } elseif (!$project && $queryProject) {
57
            return $this->redirectToRoute("EditCounterProject", [ 'project'=>$queryProject ]);
58
        }
59
60
        $this->init($project);
61
62
        // Otherwise fall through.
63
        return $this->render('editCounter/index.html.twig', [
64
            "xtPageTitle" => "tool-ec",
65
            "xtSubtitle" => "tool-ec-desc",
66
            'xtPage' => "ec",
67
            'project' => $project,
68
        ]);
69
    }
70
71
    /**
72
     * @Route("/ec/{project}/{username}", name="EditCounterResult")
73
     */
74
    public function resultAction(Request $request, $project, $username)
75
    {
76
        $project = 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...
77
        $user = UserRepository::getUser($username, $this->container());
0 ignored issues
show
Bug introduced by
The method container() does not exist on AppBundle\Controller\EditCounterController. Did you maybe mean setContainer()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
78
79
        // Don't continue if the user doesn't exist.
80
        if ($user->existsOnProject($project)) {
81
            $request->getSession()->getFlashBag()->set('notice', 'user-not-found');
82
            return $this->redirectToRoute('ec');
83
        }
84
85
        //$automatedEditsSummary = $automatedEditsHelper->getEditsSummary($user->getId());
1 ignored issue
show
Unused Code Comprehensibility introduced by
67% 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...
86
87
        // Give it all to the template.
88
        return $this->render('editCounter/result.html.twig', [
89
            'xtTitle' => $username,
90
            'xtPage' => 'ec',
91
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
92
            'is_labs' => $this->labsHelper->isLabs(),
93
            'user' => $user,
94
            'project' => $project,
95
96
            // Automated edits.
97
            //'auto_edits' => $automatedEditsSummary,
1 ignored issue
show
Unused Code Comprehensibility introduced by
67% 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...
98
        ]);
99
    }
100
101
    /**
102
     * @Route("/ec-generalstats/{project}/{username}", name="EditCounterGeneralStats")
103
     */
104
    public function generalStatsAction($project, $username)
105
    {
106
        // Set up project and user.
107
        $project = 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...
108
        $user = UserRepository::getUser($username, $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...
109
110
        // Get an edit-counter.
111
        $editCounterRepo = new EditCounterRepository();
112
        $editCounterRepo->setContainer($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...
113
        $editCounter = new EditCounter($project, $user);
114
        $editCounter->setRepository($editCounterRepo);
115
116
//        $revisionCounts = $this->editCounterHelper->getRevisionCounts($user->getId($project));
1 ignored issue
show
Unused Code Comprehensibility introduced by
61% 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...
117
//        $pageCounts = $this->editCounterHelper->getPageCounts($username, $revisionCounts['total']);
118
//        $logCounts = $this->editCounterHelper->getLogCounts($user->getId($project));
119
//        $automatedEditsSummary = $automatedEditsHelper->getEditsSummary($user->getId($project));
120
//        $topProjectsEditCounts = $this->editCounterHelper->getTopProjectsEditCounts($project->getUrl(), 
121
//            $user->getUsername());
122
123
        // Render view.
124
        $isSubRequest = $this->get('request_stack')->getParentRequest() !== null;
125
        return $this->render('editCounter/general_stats.html.twig', [
126
            'xtPage' => 'ec',
127
            'is_sub_request' => $isSubRequest,
128
            'is_labs' => $editCounterRepo->isLabs(),
129
            'project' => $project,
130
            'user' => $user,
131
            'ec' => $editCounter,
132
133
            // Revision counts.
1 ignored issue
show
Unused Code Comprehensibility introduced by
61% 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...
134
//            'deleted_edits' => $revisionCounts['deleted'],
135
//            'total_edits' => $revisionCounts['total'],
136
//            'live_edits' => $revisionCounts['live'],
137
//            'first_rev' => $revisionCounts['first'],
138
//            'latest_rev' => $revisionCounts['last'],
139
//            'days' => $revisionCounts['days'],
140
//            'avg_per_day' => $revisionCounts['avg_per_day'],
141
//            'rev_24h' => $revisionCounts['24h'],
142
//            'rev_7d' => $revisionCounts['7d'],
143
//            'rev_30d' => $revisionCounts['30d'],
144
//            'rev_365d' => $revisionCounts['365d'],
145
//            'rev_small' => $revisionCounts['small'],
146
//            'rev_large' => $revisionCounts['large'],
147
//            'with_comments' => $revisionCounts['with_comments'],
148
//            'without_comments' => $revisionCounts['live'] - $revisionCounts['with_comments'],
149
//            'minor_edits' => $revisionCounts['minor_edits'],
150
//            'nonminor_edits' => $revisionCounts['live'] - $revisionCounts['minor_edits'],
151
//            'auto_edits_total' => array_sum($automatedEditsSummary),
152
//
153
//            // Page counts.
154
//            'uniquePages' => $pageCounts['unique'],
155
//            'pagesCreated' => $pageCounts['created'],
156
//            'pagesMoved' => $pageCounts['moved'],
157
//            'editsPerPage' => $pageCounts['edits_per_page'],
158
//
159
//            // Log counts (keys are 'log name'-'action').
160
//            'pagesThanked' => $logCounts['thanks-thank'],
161
//            'pagesApproved' => $logCounts['review-approve'], // Merged -a, -i, and -ia approvals.
162
//            'pagesPatrolled' => $logCounts['patrol-patrol'],
163
//            'usersBlocked' => $logCounts['block-block'],
164
//            'usersUnblocked' => $logCounts['block-unblock'],
165
//            'pagesProtected' => $logCounts['protect-protect'],
166
//            'pagesUnprotected' => $logCounts['protect-unprotect'],
167
//            'pagesDeleted' => $logCounts['delete-delete'],
168
//            'pagesDeletedRevision' => $logCounts['delete-revision'],
169
//            'pagesRestored' => $logCounts['delete-restore'],
170
//            'pagesImported' => $logCounts['import-import'],
171
//            'files_uploaded' => $logCounts['upload-upload'],
172
//            'files_modified' => $logCounts['upload-overwrite'],
173
//            'files_uploaded_commons' => $logCounts['files_uploaded_commons'],
174
//
175
//            // Other projects.
176
//            'top_projects_edit_counts' => $topProjectsEditCounts,
177
        ]);
178
    }
179
180
    /**
181
     * @Route("/ec-namespacetotals/{project}/{username}", name="EditCounterNamespaceTotals")
182
     */
183
    public function namespaceTotalsAction($project, $username)
184
    {
185
        $this->init($project);
186
        $username = ucfirst($username);
0 ignored issues
show
Unused Code introduced by
$username is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
187
        $isSubRequest = $this->get('request_stack')->getParentRequest() !== null;
188
189
        return $this->render('editCounter/namespace_totals.html.twig', [
190
            'xtTitle' => 'tool_ec',
191
            'xtPage' => 'ec',
192
            'is_sub_request' => $isSubRequest,
193
            'namespaces' => $this->apiHelper->namespaces($project),
194
            'namespace_totals' => $namespaceTotals,
0 ignored issues
show
Bug introduced by
The variable $namespaceTotals does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
195
            'namespace_total' => array_sum($namespaceTotals),
196
        ]);
197
    }
198
199
    /**
200
     * @Route("/ec-timecard/{project}/{username}", name="EditCounterTimeCard")
201
     */
202 View Code Duplication
    public function timecardAction($project, $username)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
203
    {
204
        $this->init($project);
205
        $this->labsHelper->databasePrepare($project);
206
        $username = ucfirst($username);
207
        $isSubRequest = $this->get('request_stack')->getParentRequest() !== null;
208
        $datasets = $this->editCounterHelper->getTimeCard($username);
0 ignored issues
show
Bug introduced by
The property editCounterHelper does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
209
        return $this->render('editCounter/timecard.html.twig', [
210
            'xtTitle' => 'tool_ec',
211
            'xtPage' => 'ec',
212
            'is_sub_request' => $isSubRequest,
213
            'datasets' => $datasets,
214
        ]);
215
    }
216
217
    /**
218
     * @Route("/ec-yearcounts/{project}/{username}", name="EditCounterYearCounts")
219
     */
220 View Code Duplication
    public function yearcountsAction($project, $username)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
221
    {
222
        $this->init($project);
223
        $this->labsHelper->databasePrepare($project);
224
        $username = ucfirst($username);
225
        $isSubRequest = $this->container->get('request_stack')->getParentRequest() !== null;
226
        $yearcounts = $this->editCounterHelper->getYearCounts($username);
227
        return $this->render('editCounter/yearcounts.html.twig', [
228
            'xtTitle' => 'tool_ec',
229
            'xtPage' => 'ec',
230
            'is_sub_request' => $isSubRequest,
231
            'namespaces' => $this->apiHelper->namespaces($project),
232
            'yearcounts' => $yearcounts,
233
        ]);
234
    }
235
236
    /**
237
     * @Route("/ec-monthcounts/{project}/{username}", name="EditCounterMonthCounts")
238
     */
239 View Code Duplication
    public function monthcountsAction($project, $username)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
240
    {
241
        $this->init($project);
242
        $this->labsHelper->databasePrepare($project);
243
        $username = ucfirst($username);
244
        $monthlyTotalsByNamespace = $this->editCounterHelper->getMonthCounts($username);
245
        $isSubRequest = $this->container->get('request_stack')->getParentRequest() !== null;
246
        return $this->render('editCounter/monthcounts.html.twig', [
247
            'xtTitle' => 'tool_ec',
248
            'xtPage' => 'ec',
249
            'is_sub_request' => $isSubRequest,
250
            'month_counts' => $monthlyTotalsByNamespace,
251
            'namespaces' => $this->apiHelper->namespaces($project),
252
        ]);
253
    }
254
255
    /**
256
     * @Route("/ec-latestglobal/{project}/{username}", name="EditCounterLatestGlobal")
257
     */
258
    public function latestglobalAction($project, $username)
259
    {
260
        $this->init($project);
261
        $info = $this->labsHelper->databasePrepare($project);
262
        $username = ucfirst($username);
263
264
        $topProjectsEditCounts = $this->editCounterHelper->getTopProjectsEditCounts(
265
            $info['url'],
266
            $username
267
        );
268
        $recentGlobalContribs = $this->editCounterHelper->getRecentGlobalContribs(
269
            $username,
270
            array_keys($topProjectsEditCounts)
271
        );
272
273
        $isSubRequest = $this->container->get('request_stack')->getParentRequest() !== null;
274
        return $this->render('editCounter/latest_global.html.twig', [
275
            'xtTitle' => 'tool_ec',
276
            'xtPage' => 'ec',
277
            'is_sub_request' => $isSubRequest,
278
            'latest_global_contribs' => $recentGlobalContribs,
279
            'username' => $username,
280
            'project' => $project,
281
            'namespaces' => $this->apiHelper->namespaces($project),
282
        ]);
283
    }
284
}
285