Completed
Push — master ( e15cd8...6a18e3 )
by Sam
03:48
created

TopEditsController   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 245
Duplicated Lines 6.53 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 13
dl 16
loc 245
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
C indexAction() 0 57 13
A resultAction() 4 21 3
C namespaceTopEdits() 0 72 7
B singlePageTopEdits() 12 60 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace AppBundle\Controller;
4
5
use AppBundle\Helper\ApiHelper;
6
use AppBundle\Helper\LabsHelper;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\VarDumper\VarDumper;
11
use Xtools\Page;
12
use Xtools\PagesRepository;
13
use Xtools\Project;
14
use Xtools\ProjectRepository;
15
use Xtools\User;
16
use Xtools\UserRepository;
17
18
class TopEditsController extends Controller
19
{
20
21
    /** @var LabsHelper */
22
    private $lh;
23
24
    /**
25
     * @Route("/topedits", name="topedits")
26
     * @Route("/topedits", name="topEdits")
27
     * @Route("/topedits/", name="topEditsSlash")
28
     * @Route("/topedits/index.php", name="topEditsIndex")
29
     */
30
    public function indexAction(Request $request)
31
    {
32
        $this->lh = $this->get("app.labs_helper");
33
        $this->lh->checkEnabled("topedits");
34
35
        $projectName = $request->query->get('project');
36
        $username = $request->query->get('username');
37
        $namespace = $request->query->get('namespace');
38
        $article = $request->query->get('article');
39
40
        if ($projectName != "" && $username != "" && $namespace != "" && $article != "") {
41
            return $this->redirectToRoute("TopEditsResults", [
42
                'project'=>$projectName,
43
                'username' => $username,
44
                'namespace'=>$namespace,
45
                'article'=>$article,
46
            ]);
47
        } elseif ($projectName != "" && $username != "" && $namespace != "") {
48
            return $this->redirectToRoute("TopEditsResults", [
49
                'project'=>$projectName,
50
                'username' => $username,
51
                'namespace'=>$namespace,
52
            ]);
53
        } elseif ($projectName != "" && $username != "") {
54
            return $this->redirectToRoute("TopEditsResults", [
55
                'project' => $projectName,
56
                'username' => $username,
57
            ]);
58
        } elseif ($projectName != "") {
59
            return $this->redirectToRoute("TopEditsResults", [ 'project'=>$projectName ]);
60
        }
61
62
        // Set default project so we can populate the namespace selector.
63
        if (!$projectName) {
64
            $projectName = $this->container->getParameter('default_project');
65
        }
66
67
        $project = ProjectRepository::getProject($projectName, $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...
68
69
        // Default values for the variables to keep the template happy
70
        $domain = null;
71
        $namespaces = null;
72
73
        // If the project exists, actually populate the values
74
        if ($project->exists()) {
75
            $domain = $project->getDomain();
76
            $namespaces = $project->getNamespaces();
77
        }
78
79
        return $this->render('topedits/index.html.twig', [
80
            'xtPageTitle' => 'tool-topedits',
81
            'xtSubtitle' => 'tool-topedits-desc',
82
            'xtPage' => 'topedits',
83
            'domain' => $domain,
84
            'namespaces' => $namespaces,
85
        ]);
86
    }
87
88
    /**
89
     * @Route("/topedits/{project}/{username}/{namespace}/{article}", name="TopEditsResults",
90
     *     requirements={"article"=".+"})
91
     */
92
    public function resultAction($project, $username, $namespace = 0, $article = "")
93
    {
94
        /** @var LabsHelper $lh */
95
        $this->lh = $this->get('app.labs_helper');
96
        $this->lh->checkEnabled('topedits');
97
98
        $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...
99
100 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...
101
            $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...
102
            return $this->redirectToRoute("topedits");
103
        }
104
105
        $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...
106
107
        if ($article === "") {
108
            return $this->namespaceTopEdits($user, $projectData, $namespace);
109
        } else {
110
            return $this->singlePageTopEdits($user, $projectData, $namespace, $article);
111
        }
112
    }
113
114
    /**
115
     * List top edits by this user for all pages in a particular namespace.
116
     * @param User $user The User.
117
     * @param Project $project The project.
118
     * @param integer|string $namespaceId The namespace ID or 'all'
119
     * @return \Symfony\Component\HttpFoundation\Response
120
     */
121
    protected function namespaceTopEdits(User $user, Project $project, $namespaceId)
122
    {
123
        // Make sure they've opted in to see this data.
124
        if (!$project->userHasOptedIn($user)) {
125
            $this->addFlash('notice', ['not-opted-in']);
0 ignored issues
show
Documentation introduced by
array('not-opted-in') 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...
126
            $title = $project->userOptInPage($user);
127
            $url = $project->getUrl().$project->getArticlePath().$title;
128
            $anchor = "<a href='".urlencode($url).">$title</a>";
129
            return $this->redirectToRoute('topedits', [$anchor]);
130
        }
131
132
        // Get list of namespaces.
133
        $namespaces = $project->getNamespaces();
134
135
        // Get the basic data about the pages edited by this user.
136
        $params = ['username'=>$user->getUsername()];
137
        $nsClause = '';
138
        $namespaceMsg = 'all-namespaces';
139
        if (is_numeric($namespaceId)) {
140
            $nsClause = 'AND page_namespace = :namespace';
141
            $params['namespace'] = $namespaceId;
142
            $namespaceMsg = str_replace(' ', '_', strtolower($namespaces[$namespaceId]));
143
        }
144
        $revTable = $this->lh->getTable('revision', $project->getDatabaseName());
145
        $pageTable = $this->lh->getTable('page', $project->getDatabaseName());
146
        $query = "SELECT page_namespace, page_title, page_is_redirect, COUNT(page_title) AS count
147
                FROM $pageTable JOIN $revTable ON page_id = rev_page
148
                WHERE rev_user_text = :username $nsClause
149
                GROUP BY page_namespace, page_title
150
                ORDER BY count DESC
151
                LIMIT 100";
152
        $conn = $this->getDoctrine()->getManager('replicas')->getConnection();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method getConnection() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
153
        $editData = $conn->executeQuery($query, $params)->fetchAll();
154
155
        // Inform user if no revisions found.
156
        if (count($editData) === 0) {
157
            $this->addFlash("notice", ["no-contribs"]);
0 ignored issues
show
Documentation introduced by
array('no-contribs') 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...
158
        }
159
160
        // Get page info about these 100 pages, so we can use their display title.
161
        $titles = array_map(function ($e) use ($namespaces) {
162
            // If non-mainspace, prepend namespace to the titles.
163
            $ns = $e['page_namespace'];
164
            $nsTitle = $ns > 0 ? $namespaces[$e['page_namespace']] . ':' : '';
165
            return $nsTitle . $e['page_title'];
166
        }, $editData);
167
        /** @var ApiHelper $apiHelper */
168
        $apiHelper = $this->get('app.api_helper');
169
        $displayTitles = $apiHelper->displayTitles($project->getDomain(), $titles);
0 ignored issues
show
Security Bug introduced by
It seems like $project->getDomain() targeting Xtools\Project::getDomain() can also be of type false; however, AppBundle\Helper\ApiHelper::displayTitles() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
170
171
        // Put all together, and return the view.
172
        $edits = [];
173
        foreach ($editData as $editDatum) {
174
            // If non-mainspace, prepend namespace to the titles.
175
            $ns = $editDatum['page_namespace'];
176
            $nsTitle = $ns > 0 ? $namespaces[$editDatum['page_namespace']] . ':' : '';
177
            $pageTitle = $nsTitle . $editDatum['page_title'];
178
            $editDatum['displaytitle'] = $displayTitles[$pageTitle];
179
            // $editDatum['page_title'] is retained without the namespace
180
            //  so we can link to TopEdits for that page
181
            $editDatum['page_title_ns'] = $pageTitle;
182
            $edits[] = $editDatum;
183
        }
184
        return $this->render('topedits/result_namespace.html.twig', [
185
            'xtPage' => 'topedits',
186
            'project' => $project,
187
            'user' => $user,
188
            'namespace' => $namespaceId,
189
            'edits' => $edits,
190
            'content_title' => $namespaceMsg,
191
        ]);
192
    }
193
194
    /**
195
     * List top edits by this user for a particular page.
196
     * @param User $user The user.
197
     * @param Project $project The project.
198
     * @param int $namespaceId The ID of the namespace of the page.
199
     * @param string $pageName The title (without namespace) of the page.
200
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
201
     */
202
    protected function singlePageTopEdits(User $user, Project $project, $namespaceId, $pageName)
203
    {
204
        // Get the full page name (i.e. no namespace prefix if NS 0).
205
        $namespaces = $project->getNamespaces();
206
        $fullPageName = $namespaceId ? $namespaces[$namespaceId].':'.$pageName : $pageName;
207
        $page = new Page($project, $fullPageName);
208
        $pageRepo = new PagesRepository();
209
        $page->setRepository($pageRepo);
210
211
        if (!$page->exists()) {
212
            // Redirect if the page doesn't exist.
213
            $this->addFlash("notice", ["no-result", $pageName]);
0 ignored issues
show
Documentation introduced by
array('no-result', $pageName) 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...
214
            return $this->redirectToRoute("topedits");
215
        }
216
217
        // Get all revisions of this page by this user.
218
        $revTable = $this->lh->getTable('revision', $project->getDatabaseName());
219
        $query = "SELECT
220
                    revs.rev_id AS id,
221
                    revs.rev_timestamp AS timestamp,
222
                    (CAST(revs.rev_len AS SIGNED) - IFNULL(parentrevs.rev_len, 0)) AS length_change,
223
                    revs.rev_comment AS comment
224
                FROM $revTable AS revs
225
                    LEFT JOIN $revTable AS parentrevs ON (revs.rev_parent_id = parentrevs.rev_id)
226
                WHERE revs.rev_user_text IN (:username) AND revs.rev_page = :pageid
227
                ORDER BY revs.rev_timestamp DESC
228
            ";
229
        $params = ['username' => $user->getUsername(), 'pageid' => $page->getId()];
230
        $conn = $this->getDoctrine()->getManager('replicas')->getConnection();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method getConnection() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
231
        $revisionsData = $conn->executeQuery($query, $params)->fetchAll();
232
233
        // Loop through all revisions and format dates, find totals, etc.
234
        $totalAdded = 0;
235
        $totalRemoved = 0;
236
        $revisions = [];
237 View Code Duplication
        foreach ($revisionsData as $revision) {
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...
238
            if ($revision['length_change'] > 0) {
239
                $totalAdded += $revision['length_change'];
240
            } else {
241
                $totalRemoved += $revision['length_change'];
242
            }
243
            $time = strtotime($revision['timestamp']);
244
            $revision['timestamp'] = $time; // formatted via Twig helper
245
            $revision['year'] = date('Y', $time);
246
            $revision['month'] = date('m', $time);
247
            $revisions[] = $revision;
248
        }
249
250
        // Send all to the template.
251
        return $this->render('topedits/result_article.html.twig', [
252
            'xtPage' => 'topedits',
253
            'project' => $project,
254
            'user' => $user,
255
            'page' => $page,
256
            'total_added' => $totalAdded,
257
            'total_removed' => $totalRemoved,
258
            'revisions' => $revisions,
259
            'revision_count' => count($revisions),
260
        ]);
261
    }
262
}
263