Completed
Push — master ( 0058c9...b0ad91 )
by
unknown
02:49
created

PagesController::resultAction()   F

Complexity

Conditions 15
Paths 668

Size

Total Lines 126
Code Lines 82

Duplication

Lines 26
Ratio 20.63 %

Importance

Changes 0
Metric Value
dl 26
loc 126
rs 2.4166
c 0
b 0
f 0
cc 15
eloc 82
nc 668
nop 4

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
 * This file contains only the PagesController class.
4
 */
5
6
namespace AppBundle\Controller;
7
8
use DateTime;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
10
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
11
use Symfony\Component\HttpFoundation\RedirectResponse;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\HttpFoundation\Response;
14
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
15
use Xtools\ProjectRepository;
16
use Xtools\UserRepository;
17
use Xtools\Page;
18
use Xtools\Edit;
19
20
/**
21
 * This controller serves the Pages tool.
22
 */
23
class PagesController extends Controller
24
{
25
26
    /**
27
     * Get the tool's shortname.
28
     * @return string
29
     */
30
    public function getToolShortname()
31
    {
32
        return 'pages';
33
    }
34
35
    /**
36
     * Display the form.
37
     * @Route("/pages", name="pages")
38
     * @Route("/pages", name="Pages")
39
     * @Route("/pages/", name="PagesSlash")
40
     * @Route("/pages/index.php", name="PagesIndexPhp")
41
     * @Route("/pages/{project}", name="PagesProject")
42
     * @param string $project The project domain name.
43
     * @return Response
44
     */
45
    public function indexAction($project = null)
46
    {
47
        // Grab the request object, grab the values out of it.
48
        $request = Request::createFromGlobals();
49
50
        $projectQuery = $request->query->get('project');
51
        $username = $request->query->get('username', $request->query->get('user'));
52
        $namespace = $request->query->get('namespace');
53
        $redirects = $request->query->get('redirects');
54
55
        // if values for required parameters are present, redirect to result action
56
        if ($projectQuery != "" && $username != "" && $namespace != "" && $redirects != "") {
57
            return $this->redirectToRoute("PagesResult", [
58
                'project'=>$projectQuery,
59
                'username' => $username,
60
                'namespace'=>$namespace,
61
                'redirects'=>$redirects,
62
            ]);
63 View Code Duplication
        } elseif ($projectQuery != "" && $username != "" && $namespace != "") {
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...
64
            return $this->redirectToRoute("PagesResult", [
65
                'project'=>$projectQuery,
66
                'username' => $username,
67
                'namespace'=>$namespace,
68
            ]);
69
        } elseif ($projectQuery != "" && $username != "" && $redirects != "") {
70
            return $this->redirectToRoute("PagesResult", [
71
                'project'=>$projectQuery,
72
                'username' => $username,
73
                'redirects'=>$redirects,
74
            ]);
75
        } elseif ($projectQuery != "" && $username != "") {
76
            return $this->redirectToRoute("PagesResult", [
77
                'project'=>$projectQuery,
78
                'username' => $username,
79
            ]);
80
        } elseif ($projectQuery != "") {
81
            return $this->redirectToRoute("PagesProject", [ 'project'=>$projectQuery ]);
82
        }
83
84
        // set default wiki so we can populate the namespace selector
85
        if (!$project) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $project of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
86
            $project = $this->getParameter('default_project');
87
        }
88
89
        $projectData = ProjectRepository::getProject($project, $this->container);
90
91
        $namespaces = null;
92
93
        if ($projectData->exists()) {
94
            $namespaces = $projectData->getNamespaces();
95
        }
96
97
        // Otherwise fall through.
98
        return $this->render('pages/index.html.twig', [
99
            'xtPageTitle' => 'tool-pages',
100
            'xtSubtitle' => 'tool-pages-desc',
101
            'xtPage' => 'pages',
102
            'project' => $projectData,
103
            'namespaces' => $namespaces,
104
        ]);
105
    }
106
107
    /**
108
     * Display the results.
109
     * @Route("/pages/{project}/{username}/{namespace}/{redirects}", name="PagesResult")
110
     * @param string $project The project domain name.
111
     * @param string $username The username.
112
     * @param string $namespace The ID of the namespace.
113
     * @param string $redirects Whether to follow redirects or not.
114
     * @return RedirectResponse|Response
115
     */
116
    public function resultAction($project, $username, $namespace = '0', $redirects = 'noredirects')
117
    {
118
        $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...
119
        $username = $user->getUsername(); // use normalized user name
120
121
        $projectData = ProjectRepository::getProject($project, $this->container);
122
        $projectRepo = $projectData->getRepository();
123
124
        // If the project exists, actually populate the values
125 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...
126
            $this->addFlash('notice', ['invalid-project', $project]);
0 ignored issues
show
Documentation introduced by
array('invalid-project', $project) 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...
127
            return $this->redirectToRoute('pages');
128
        }
129
        if (!$user->existsOnProject($projectData)) {
130
            $this->addFlash('notice', ['user-not-found']);
0 ignored issues
show
Documentation introduced by
array('user-not-found') is of type array<integer,string,{"0":"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...
131
            return $this->redirectToRoute('pages');
132
        }
133
134
        // what columns to show in namespace totals table
135
        $summaryColumns = ['namespace'];
136
        if ($redirects == 'onlyredirects') {
137
            // don't show redundant pages column if only getting data on redirects
138
            $summaryColumns[] = 'redirects';
139
        } elseif ($redirects == 'noredirects') {
140
            // don't show redundant redirects column if only getting data on non-redirects
141
            $summaryColumns[] = 'pages';
142
        } else {
143
            // order is important here
144
            $summaryColumns[] = 'pages';
145
            $summaryColumns[] = 'redirects';
146
        }
147
        $summaryColumns[] = 'deleted'; // always show deleted column
148
149
        $result = $user->getRepository()->getPagesCreated($projectData, $user, $namespace, $redirects);
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Xtools\Repository as the method getPagesCreated() does only exist in the following sub-classes of Xtools\Repository: Xtools\UserRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
150
151
        $hasPageAssessments = $projectRepo->isLabs() && $projectData->hasPageAssessments();
152
        $pagesByNamespaceByDate = [];
153
        $pageTitles = [];
154
        $countsByNamespace = [];
155
        $total = 0;
156
        $redirectTotal = 0;
157
        $deletedTotal = 0;
158
159
        foreach ($result as $row) {
160
            $datetime = DateTime::createFromFormat('YmdHis', $row['rev_timestamp']);
161
            $datetimeKey = $datetime->format('Ymdhi');
162
            $datetimeHuman = $datetime->format('Y-m-d H:i');
163
164
            $pageData = array_merge($row, [
165
                'raw_time' => $row['rev_timestamp'],
166
                'human_time' => $datetimeHuman,
167
                'page_title' => str_replace('_', ' ', $row['page_title'])
168
            ]);
169
170
            if ($hasPageAssessments) {
171
                $pageData['badge'] = $projectData->getAssessmentBadgeURL($pageData['pa_class']);
172
            }
173
174
            $pagesByNamespaceByDate[$row['namespace']][$datetimeKey][] = $pageData;
175
176
            $pageTitles[] = $row['page_title'];
177
178
            // Totals
179
            if (isset($countsByNamespace[$row['namespace']]['total'])) {
180
                $countsByNamespace[$row['namespace']]['total']++;
181
            } else {
182
                $countsByNamespace[$row['namespace']]['total'] = 1;
183
                $countsByNamespace[$row['namespace']]['redirect'] = 0;
184
                $countsByNamespace[$row['namespace']]['deleted'] = 0;
185
            }
186
            $total++;
187
188 View Code Duplication
            if ($row['page_is_redirect']) {
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...
189
                $redirectTotal++;
190
                // Redirects
191
                if (isset($countsByNamespace[$row['namespace']]['redirect'])) {
192
                    $countsByNamespace[$row['namespace']]['redirect']++;
193
                } else {
194
                    $countsByNamespace[$row['namespace']]['redirect'] = 1;
195
                }
196
            }
197
198 View Code Duplication
            if ($row['type'] === 'arc') {
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...
199
                $deletedTotal++;
200
                // Deleted
201
                if (isset($countsByNamespace[$row['namespace']]['deleted'])) {
202
                    $countsByNamespace[$row['namespace']]['deleted']++;
203
                } else {
204
                    $countsByNamespace[$row['namespace']]['deleted'] = 1;
205
                }
206
            }
207
        }
208
209 View Code Duplication
        if ($total < 1) {
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...
210
            $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...
211
            return $this->redirectToRoute('PagesProject', [ 'project' => $project ]);
212
        }
213
214
        ksort($pagesByNamespaceByDate);
215
        ksort($countsByNamespace);
216
217
        foreach (array_keys($pagesByNamespaceByDate) as $key) {
218
            krsort($pagesByNamespaceByDate[$key]);
219
        }
220
221
        // Retrieve the namespaces
222
        $namespaces = $projectData->getNamespaces();
223
224
        // Assign the values and display the template
225
        return $this->render('pages/result.html.twig', [
226
            'xtPage' => 'pages',
227
            'xtTitle' => $username,
228
            'project' => $projectData,
229
            'user' => $user,
230
            'namespace' => $namespace,
231
            'redirect' => $redirects,
232
            'summaryColumns' => $summaryColumns,
233
            'namespaces' => $namespaces,
234
            'pages' => $pagesByNamespaceByDate,
235
            'count' => $countsByNamespace,
236
            'total' => $total,
237
            'redirectTotal' => $redirectTotal,
238
            'deletedTotal' => $deletedTotal,
239
            'hasPageAssessments' => $hasPageAssessments,
240
        ]);
241
    }
242
}
243