Completed
Push — master ( 9fe0d2...0e0f1f )
by Sam
03:08
created

TopEditsController::resultAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 4
Ratio 20 %

Importance

Changes 0
Metric Value
dl 4
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 4
1
<?php
2
/**
3
 * This file contains only the TopEditsController class.
4
 */
5
6
namespace AppBundle\Controller;
7
8
use AppBundle\Helper\ApiHelper;
9
use AppBundle\Helper\LabsHelper;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
12
use Symfony\Component\HttpFoundation\RedirectResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
use Xtools\Page;
16
use Xtools\PagesRepository;
17
use Xtools\Project;
18
use Xtools\ProjectRepository;
19
use Xtools\User;
20
use Xtools\UserRepository;
21
use Xtools\Edit;
22
23
/**
24
 * The Top Edits tool.
25
 */
26
class TopEditsController extends Controller
27
{
28
29
    /** @var LabsHelper The Labs helper, for WMF Labs installations. */
30
    private $lh;
31
32
    /**
33
     * Get the tool's shortname.
34
     * @return string
35
     */
36
    public function getToolShortname()
37
    {
38
        return 'topedits';
39
    }
40
41
    /**
42
     * Display the form.
43
     * @Route("/topedits", name="topedits")
44
     * @Route("/topedits", name="topEdits")
45
     * @Route("/topedits/", name="topEditsSlash")
46
     * @Route("/topedits/index.php", name="topEditsIndex")
47
     * @param Request $request
48
     * @return Response
49
     */
50
    public function indexAction(Request $request)
51
    {
52
        $this->lh = $this->get("app.labs_helper");
53
54
        $projectName = $request->query->get('project');
55
        $username = $request->query->get('username', $request->query->get('user'));
56
        $namespace = $request->query->get('namespace');
57
        $article = $request->query->get('article');
58
59
        if ($projectName != "" && $username != "" && $namespace != "" && $article != "") {
60
            return $this->redirectToRoute("TopEditsResults", [
61
                'project'=>$projectName,
62
                'username' => $username,
63
                'namespace'=>$namespace,
64
                'article'=>$article,
65
            ]);
66 View Code Duplication
        } elseif ($projectName != "" && $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...
67
            return $this->redirectToRoute("TopEditsResults", [
68
                'project'=>$projectName,
69
                'username' => $username,
70
                'namespace'=>$namespace,
71
            ]);
72
        } elseif ($projectName != "" && $username != "") {
73
            return $this->redirectToRoute("TopEditsResults", [
74
                'project' => $projectName,
75
                'username' => $username,
76
            ]);
77
        } elseif ($projectName != "") {
78
            return $this->redirectToRoute("TopEditsResults", [ 'project'=>$projectName ]);
79
        }
80
81
        // Set default project so we can populate the namespace selector.
82
        if (!$projectName) {
83
            $projectName = $this->container->getParameter('default_project');
84
        }
85
        $project = ProjectRepository::getProject($projectName, $this->container);
86
87
        return $this->render('topedits/index.html.twig', [
88
            'xtPageTitle' => 'tool-topedits',
89
            'xtSubtitle' => 'tool-topedits-desc',
90
            'xtPage' => 'topedits',
91
            'project' => $project,
92
        ]);
93
    }
94
95
    /**
96
     * Display the results.
97
     * @Route("/topedits/{project}/{username}/{namespace}/{article}", name="TopEditsResults",
98
     *     requirements={"article"=".+"})
99
     * @param string $project
100
     * @param string $username
101
     * @param int $namespace
102
     * @param string $article
103
     * @return RedirectResponse|Response
104
     */
105
    public function resultAction($project, $username, $namespace = 0, $article = "")
106
    {
107
        /** @var LabsHelper $lh */
108
        $this->lh = $this->get('app.labs_helper');
109
110
        $projectData = ProjectRepository::getProject($project, $this->container);
111
112 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...
113
            $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...
114
            return $this->redirectToRoute("topedits");
115
        }
116
117
        $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...
118
119
        if ($article === "") {
120
            return $this->namespaceTopEdits($user, $projectData, $namespace);
121
        } else {
122
            return $this->singlePageTopEdits($user, $projectData, $namespace, $article);
123
        }
124
    }
125
126
    /**
127
     * List top edits by this user for all pages in a particular namespace.
128
     * @param User $user The User.
129
     * @param Project $project The project.
130
     * @param integer|string $namespaceId The namespace ID or 'all'
131
     * @return \Symfony\Component\HttpFoundation\Response
132
     */
133
    protected function namespaceTopEdits(User $user, Project $project, $namespaceId)
134
    {
135
        // Make sure they've opted in to see this data.
136
        if (!$project->userHasOptedIn($user)) {
137
            $optedInPage = $project
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 getPage() does only exist in the following sub-classes of Xtools\Repository: Xtools\ProjectRepository. 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...
138
                ->getRepository()
139
                ->getPage($project, $project->userOptInPage($user));
140
            return $this->render('topedits/result_namespace.html.twig', [
141
                'xtPage' => 'topedits',
142
                'project' => $project,
143
                'user' => $user,
144
                'namespace' => $namespaceId,
145
                'edits' => [],
146
                'content_title' => '',
147
                'opted_in_page' => $optedInPage,
148
            ]);
149
        }
150
151
        // Get list of namespaces.
152
        $namespaces = $project->getNamespaces();
153
154
        // Get the basic data about the pages edited by this user.
155
        $params = ['username'=>$user->getUsername()];
156
        $nsClause = '';
157
        $namespaceMsg = 'all-namespaces';
158
        if (is_numeric($namespaceId)) {
159
            $nsClause = 'AND page_namespace = :namespace';
160
            $params['namespace'] = $namespaceId;
161
            $namespaceMsg = str_replace(' ', '_', strtolower($namespaces[$namespaceId]));
162
        }
163
        $revTable = $this->lh->getTable('revision', $project->getDatabaseName());
164
        $pageTable = $this->lh->getTable('page', $project->getDatabaseName());
165
        $query = "SELECT page_namespace, page_title, page_is_redirect, COUNT(page_title) AS count
166
                FROM $pageTable JOIN $revTable ON page_id = rev_page
167
                WHERE rev_user_text = :username $nsClause
168
                GROUP BY page_namespace, page_title
169
                ORDER BY count DESC
170
                LIMIT 100";
171
        $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...
172
        $editData = $conn->executeQuery($query, $params)->fetchAll();
173
174
        // Inform user if no revisions found.
175
        if (count($editData) === 0) {
176
            $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...
177
        }
178
179
        // Get page info about these 100 pages, so we can use their display title.
180
        $titles = array_map(function ($e) use ($namespaces) {
181
            // If non-mainspace, prepend namespace to the titles.
182
            $ns = $e['page_namespace'];
183
            $nsTitle = $ns > 0 ? $namespaces[$e['page_namespace']] . ':' : '';
184
            return $nsTitle . $e['page_title'];
185
        }, $editData);
186
        /** @var ApiHelper $apiHelper */
187
        $apiHelper = $this->get('app.api_helper');
188
        $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...
189
190
        // Create page repo to be used in page objects
191
        $pageRepo = new PagesRepository();
192
        $pageRepo->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...
193
194
        // Put all together, and return the view.
195
        $edits = [];
196
        foreach ($editData as $editDatum) {
197
            // If non-mainspace, prepend namespace to the titles.
198
            $ns = $editDatum['page_namespace'];
199
            $nsTitle = $ns > 0 ? $namespaces[$editDatum['page_namespace']] . ':' : '';
200
            $pageTitle = $nsTitle . $editDatum['page_title'];
201
            $editDatum['displaytitle'] = $displayTitles[$pageTitle];
202
            // $editDatum['page_title'] is retained without the namespace
203
            //  so we can link to TopEdits for that page
204
            $editDatum['page_title_ns'] = $pageTitle;
205
            $edits[] = $editDatum;
206
        }
207
        return $this->render('topedits/result_namespace.html.twig', [
208
            'xtPage' => 'topedits',
209
            'project' => $project,
210
            'user' => $user,
211
            'namespace' => $namespaceId,
212
            'edits' => $edits,
213
            'content_title' => $namespaceMsg,
214
        ]);
215
    }
216
217
    /**
218
     * List top edits by this user for a particular page.
219
     * @param User $user The user.
220
     * @param Project $project The project.
221
     * @param int $namespaceId The ID of the namespace of the page.
222
     * @param string $pageName The title (without namespace) of the page.
223
     * @return RedirectResponse|\Symfony\Component\HttpFoundation\Response
224
     */
225
    protected function singlePageTopEdits(User $user, Project $project, $namespaceId, $pageName)
226
    {
227
        // Get the full page name (i.e. no namespace prefix if NS 0).
228
        $namespaces = $project->getNamespaces();
229
        $fullPageName = $namespaceId ? $namespaces[$namespaceId].':'.$pageName : $pageName;
230
        $page = new Page($project, $fullPageName);
231
        $pageRepo = new PagesRepository();
232
        $pageRepo->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...
233
        $page->setRepository($pageRepo);
234
235
        if (!$page->exists()) {
236
            // Redirect if the page doesn't exist.
237
            $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...
238
            return $this->redirectToRoute("topedits");
239
        }
240
241
        // Get all revisions of this page by this user.
242
        $revisionsData = $page->getRevisions($user);
243
244
        // Loop through all revisions and format dates, find totals, etc.
245
        $totalAdded = 0;
246
        $totalRemoved = 0;
247
        $revisions = [];
248 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...
249
            if ($revision['length_change'] > 0) {
250
                $totalAdded += $revision['length_change'];
251
            } else {
252
                $totalRemoved += $revision['length_change'];
253
            }
254
            $revisions[] = new Edit($page, $revision);
255
        }
256
257
        // Send all to the template.
258
        return $this->render('topedits/result_article.html.twig', [
259
            'xtPage' => 'topedits',
260
            'project' => $project,
261
            'user' => $user,
262
            'page' => $page,
263
            'total_added' => $totalAdded,
264
            'total_removed' => $totalRemoved,
265
            'revisions' => $revisions,
266
            'revision_count' => count($revisions),
267
        ]);
268
    }
269
}
270