Completed
Pull Request — master (#99)
by MusikAnimal
02:26
created

TopEditsController::resultAction()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 16

Duplication

Lines 4
Ratio 14.81 %

Importance

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