Completed
Pull Request — master (#104)
by MusikAnimal
02:18
created

TopEditsController   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 235
Duplicated Lines 6.81 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getToolShortname() 0 4 1
C indexAction() 0 53 14
B resultAction() 16 37 5
B namespaceTopEdits() 0 46 4
B singlePageTopEdits() 0 45 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
 * 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\TopEdits;
21
use Xtools\TopEditsRepository;
22
use Xtools\Edit;
23
24
/**
25
 * The Top Edits tool.
26
 */
27
class TopEditsController extends Controller
28
{
29
30
    /**
31
     * Get the tool's shortname.
32
     * @return string
33
     */
34
    public function getToolShortname()
35
    {
36
        return 'topedits';
37
    }
38
39
    /**
40
     * Display the form.
41
     * @Route("/topedits", name="topedits")
42
     * @Route("/topedits", name="TopEdits")
43
     * @Route("/topedits/", name="topEditsSlash")
44
     * @Route("/topedits/index.php", name="TopEditsIndex")
45
     * @Route("/topedits/{project}", name="TopEditsProject")
46
     * @param Request $request
47
     * @param string $project The project name.
48
     * @return Response
49
     */
50
    public function indexAction(Request $request, $project = null)
51
    {
52
        $project = $request->query->get('project') ?: $project;
53
        $username = $request->query->get('username', $request->query->get('user'));
54
        $namespace = $request->query->get('namespace');
55
        $article = $request->query->get('article');
56
57
        // Legacy XTools.
58
        $user = $request->query->get('user');
59
        if (empty($username) && isset($user)) {
60
            $username = $user;
61
        }
62
        $page = $request->query->get('page');
63
        if (empty($article) && isset($page)) {
64
            $article = $page;
65
        }
66
        $wiki = $request->query->get('wiki');
67
        $lang = $request->query->get('lang');
68
        if (isset($wiki) && isset($lang) && empty($project)) {
69
            $project = $lang.'.'.$wiki.'.org';
70
        }
71
72
        $redirectParams = [
73
            'project' => $project,
74
            'username' => $username,
75
        ];
76
        if ($article != '') {
77
            $redirectParams['article'] = $article;
78
        }
79
        if ($namespace != '') {
80
            $redirectParams['namespace'] = $namespace;
81
        }
82
83
        // Redirect if at minimum project and username are provided.
84
        if ($project != '' && $username != '') {
85
            return $this->redirectToRoute('TopEditsResults', $redirectParams);
86
        }
87
88
        // Set default project so we can populate the namespace selector.
89
        if (!$project) {
90
            $project = $this->container->getParameter('default_project');
91
        }
92
        $project = ProjectRepository::getProject($project, $this->container);
93
94
        return $this->render('topedits/index.html.twig', [
95
            'xtPageTitle' => 'tool-topedits',
96
            'xtSubtitle' => 'tool-topedits-desc',
97
            'xtPage' => 'topedits',
98
            'project' => $project,
99
            'namespace' => (int) $namespace,
100
            'article' => $article,
101
        ]);
102
    }
103
104
    /**
105
     * Display the results.
106
     * @Route("/topedits/{project}/{username}/{namespace}/{article}", name="TopEditsResults",
107
     *     requirements={"article"=".+"})
108
     * @param Request $request The HTTP request.
109
     * @param string $project
110
     * @param string $username
111
     * @param int $namespace
112
     * @param string $article
113
     * @return RedirectResponse|Response
114
     */
115
    public function resultAction(Request $request, $project, $username, $namespace = 0, $article = '')
116
    {
117
        $projectData = ProjectRepository::getProject($project, $this->container);
118
119
        if (!$projectData->exists()) {
120
            $this->addFlash('danger', ['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...
121
            return $this->redirectToRoute('topedits');
122
        }
123
124
        $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...
125
126
        // Don't continue if the user doesn't exist.
127 View Code Duplication
        if (!$user->existsOnProject($projectData)) {
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...
128
            $this->addFlash('danger', 'user-not-found');
129
            return $this->redirectToRoute('topedits', [
130
                'project' => $project,
131
                'namespace' => $namespace,
132
                'article' => $article,
133
            ]);
134
        }
135
136
        // Reject users with a crazy high edit count.
137 View Code Duplication
        if ($user->hasTooManyEdits($projectData)) {
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...
138
            $this->addFlash('danger', ['too-many-edits', number_format($user->maxEdits())]);
0 ignored issues
show
Documentation introduced by
array('too-many-edits', ...mat($user->maxEdits())) 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...
139
            return $this->redirectToRoute('topedits', [
140
                'project' => $project,
141
                'namespace' => $namespace,
142
                'article' => $article,
143
            ]);
144
        }
145
146
        if ($article === '') {
147
            return $this->namespaceTopEdits($request, $user, $projectData, $namespace);
148
        } else {
149
            return $this->singlePageTopEdits($user, $projectData, $namespace, $article);
150
        }
151
    }
152
153
    /**
154
     * List top edits by this user for all pages in a particular namespace.
155
     * @param Request $request The HTTP request.
156
     * @param User $user The User.
157
     * @param Project $project The project.
158
     * @param integer|string $namespace The namespace ID or 'all'
159
     * @return \Symfony\Component\HttpFoundation\Response
160
     */
161
    public function namespaceTopEdits(Request $request, User $user, Project $project, $namespace)
162
    {
163
        $isSubRequest = $request->get('htmlonly')
164
            || $this->container->get('request_stack')->getParentRequest() !== null;
165
166
        // Make sure they've opted in to see this data.
167
        if (!$project->userHasOptedIn($user)) {
168
            $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...
169
                ->getRepository()
170
                ->getPage($project, $project->userOptInPage($user));
171
172
            return $this->render('topedits/result_namespace.html.twig', [
173
                'xtPage' => 'topedits',
174
                'xtTitle' => $user->getUsername(),
175
                'project' => $project,
176
                'user' => $user,
177
                'namespace' => $namespace,
178
                'edits' => [],
179
                'content_title' => '',
180
                'opted_in_page' => $optedInPage,
181
                'is_sub_request' => $isSubRequest,
182
            ]);
183
        }
184
185
        /**
186
         * Max number of rows per namespace to show. `null` here will cause to
187
         * use the TopEdits default.
188
         * @var int
189
         */
190
        $limit = $isSubRequest ? 10 : null;
191
192
        $topEdits = new TopEdits($project, $user, $namespace, $limit);
193
        $topEditsRepo = new TopEditsRepository();
194
        $topEditsRepo->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...
195
        $topEdits->setRepository($topEditsRepo);
196
197
        return $this->render('topedits/result_namespace.html.twig', [
198
            'xtPage' => 'topedits',
199
            'xtTitle' => $user->getUsername(),
200
            'project' => $project,
201
            'user' => $user,
202
            'namespace' => $namespace,
203
            'te' => $topEdits,
204
            'is_sub_request' => $isSubRequest,
205
        ]);
206
    }
207
208
    /**
209
     * List top edits by this user for a particular page.
210
     * @param User $user The user.
211
     * @param Project $project The project.
212
     * @param int $namespaceId The ID of the namespace of the page.
213
     * @param string $pageName The title (without namespace) of the page.
214
     * @return RedirectResponse|\Symfony\Component\HttpFoundation\Response
215
     */
216
    protected function singlePageTopEdits(User $user, Project $project, $namespaceId, $pageName)
217
    {
218
        // Get the full page name (i.e. no namespace prefix if NS 0).
219
        $namespaces = $project->getNamespaces();
220
        $fullPageName = $namespaceId ? $namespaces[$namespaceId].':'.$pageName : $pageName;
221
        $page = new Page($project, $fullPageName);
222
        $pageRepo = new PagesRepository();
223
        $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...
224
        $page->setRepository($pageRepo);
225
226
        if (!$page->exists()) {
227
            // Redirect if the page doesn't exist.
228
            $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...
229
            return $this->redirectToRoute('topedits');
230
        }
231
232
        // Get all revisions of this page by this user.
233
        $revisionsData = $page->getRevisions($user);
234
235
        // Loop through all revisions and format dates, find totals, etc.
236
        $totalAdded = 0;
237
        $totalRemoved = 0;
238
        $revisions = [];
239
        foreach ($revisionsData as $revision) {
240
            if ($revision['length_change'] > 0) {
241
                $totalAdded += $revision['length_change'];
242
            } else {
243
                $totalRemoved += $revision['length_change'];
244
            }
245
            $revisions[] = new Edit($page, $revision);
246
        }
247
248
        // Send all to the template.
249
        return $this->render('topedits/result_article.html.twig', [
250
            'xtPage' => 'topedits',
251
            'xtTitle' => $user->getUsername() . ' - ' . $page->getTitle(),
252
            'project' => $project,
253
            'user' => $user,
254
            'page' => $page,
255
            'total_added' => $totalAdded,
256
            'total_removed' => $totalRemoved,
257
            'revisions' => $revisions,
258
            'revision_count' => count($revisions),
259
        ]);
260
    }
261
}
262