Completed
Push — master ( 5c8e7a...62162d )
by MusikAnimal
22s
created

RfXVoteCalculatorController::resultAction()   D

Complexity

Conditions 14
Paths 78

Size

Total Lines 131
Code Lines 84

Duplication

Lines 18
Ratio 13.74 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 18
loc 131
rs 4.9516
cc 14
eloc 84
nc 78
nop 2

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 the code that powers the RfX Vote Calculator page of XTools.
4
 */
5
6
namespace AppBundle\Controller;
7
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\CssSelector\Exception\InternalErrorException;
10
use Symfony\Component\Debug\Exception\ContextErrorException;
11
use Symfony\Component\HttpFoundation\Request;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
13
use Xtools\ProjectRepository;
14
use Xtools\PagesRepository;
15
use Xtools\RFX;
16
use Xtools\User;
17
18
/**
19
 * Controller for the RfX Vote Calculator.
20
 */
21
class RfXVoteCalculatorController extends Controller
22
{
23
24
    /**
25
     * Get the tool's shortname.
26
     *
27
     * @return string
28
     */
29
    public function getToolShortname()
30
    {
31
        return 'rfxvote';
32
    }
33
34
    /**
35
     * Renders the index page for RfXVoteCalculator
36
     *
37
     * @Route("/rfxvote", name="rfxvote")
38
     * @Route("/rfxvote", name="RfXVoteCalculator")
39
     *
40
     * @return Response
41
     */
42
    public function indexAction()
43
    {
44
        // Grab the request object, grab the values out of it.
45
        $request = Request::createFromGlobals();
46
47
        $projectQuery = $request->query->get('project');
48
        $username = $request->query->get('username');
49
50
        if ($projectQuery != '' && $username != '') {
51
            $routeParams = [ 'project' => $projectQuery, 'username' => $username ];
52
            return $this->redirectToRoute(
53
                'rfxvoteResult',
54
                $routeParams
55
            );
56
        } elseif ($projectQuery != '') {
57
            return $this->redirectToRoute(
58
                'rfxvoteResult',
59
                [
60
                    'project' => $projectQuery
61
                ]
62
            );
63
        }
64
65
        // Instantiate the project if we can, or use the default.
66
        $project = (!empty($projectQuery))
67
            ? ProjectRepository::getProject($projectQuery, $this->container)
68
            : ProjectRepository::getDefaultProject($this->container);
69
70
        return $this->render(
71
            'rfxVoteCalculator/index.html.twig',
72
            [
73
                'xtPageTitle' => 'tool-rfxvote',
74
                'xtSubtitle' => 'tool-rfxvote-desc',
75
                'xtPage' => 'rfxvote',
76
                'project' => $project,
77
            ]
78
        );
79
    }
80
81
    /**
82
     * Result View of RfXVoteCalculator
83
     *
84
     * @param string $project  The project we're working on
85
     * @param string $username Username of the user we're analysing.
86
     *
87
     * @Route("/rfxvote/{project}/{username}", name="rfxvoteResult")
88
     *
89
     * @return Response
90
     */
91
    public function resultAction($project, $username)
92
    {
93
        $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...
94
95
        $projectData = ProjectRepository::getProject($project, $this->container);
96
        $projectRepo = $projectData->getRepository();
97
        $userData = new User($username);
98
        $pagesRepo = new PagesRepository();
99
        $pagesRepo->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...
100
101
        $dbName = $projectData->getDatabaseName();
102
103
        $rfxParam = $this->getParameter('rfx');
104
105 View Code Duplication
        if (!$projectData->exists() || $rfxParam == null) {
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...
106
            $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...
107
            return $this->redirectToRoute('rfxvote');
108
        }
109
110
        $namespaces = $projectData->getNamespaces();
111
112
        if (!isset($rfxParam[$projectData->getDomain()])) {
113
            $this->addFlash('notice', ['invalid-project-cant-use', $project]);
0 ignored issues
show
Documentation introduced by
array('invalid-project-cant-use', $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('rfxvote');
115
        }
116
117
        $pageTypes = $rfxParam[$projectData->getDomain()]['pages'];
118
        $namespace
119
            = $rfxParam[$projectData->getDomain()]['rfx_namespace'] !== null
120
            ? $rfxParam[$projectData->getDomain()]['rfx_namespace'] : 4;
121
122
        $finalData = [];
123
124
        // We should probably figure out a better way to do this...
125
        $ignoredPages = '';
126
127 View Code Duplication
        if (isset($rfxParam[$projectData->getDomain()]['excluded_title'])) {
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
            $titlesExcluded
129
                = $rfxParam[$projectData->getDomain()]['excluded_title'];
130
            foreach ($titlesExcluded as $ignoredPage) {
131
                $ignoredPages .= "AND p.page_title != \"$ignoredPage\"\r\n";
132
            }
133
        }
134
135 View Code Duplication
        if (isset($rfxParam[$projectData->getDomain()]['excluded_regex'])) {
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...
136
            $titlesExcluded
137
                = $rfxParam[$projectData->getDomain()]['excluded_regex'];
138
            foreach ($titlesExcluded as $ignoredPage) {
139
                $ignoredPages .= "AND p.page_title NOT LIKE \"%$ignoredPage%\"\r\n";
140
            }
141
        }
142
143
        foreach ($pageTypes as $type) {
144
            $type = explode(':', $type, 2)[1];
145
146
            $type = str_replace(' ', '_', $type);
147
148
            $pageTable = $projectRepo->getTableName($dbName, 'page');
149
            $revisionTable
150
                = $projectRepo->getTableName($dbName, 'revision');
151
152
            $sql = "SELECT DISTINCT p.page_namespace, p.page_title
153
                    FROM $pageTable p
154
                    RIGHT JOIN $revisionTable r on p.page_id=r.rev_page
155
                    WHERE p.page_namespace = :namespace
156
                    AND r.rev_user_text = :username
157
                    And p.page_title LIKE \"$type/%\"
158
                    AND p.page_title NOT LIKE \"%$type/$username%\"
159
                    $ignoredPages";
160
161
            $sth = $conn->prepare($sql);
162
            $sth->bindParam('namespace', $namespace);
163
            $sth->bindParam('username', $username);
164
165
            $sth->execute();
166
167
            $titles = [];
168
169
            while ($row = $sth->fetch()) {
170
                $titles[] = $namespaces[$row['page_namespace']] .
171
                    ':' .$row['page_title'];
172
            }
173
174
            // Chunking... it's possible to make a URI too long
175
            $titleArray = array_chunk($titles, 20);
176
177
            foreach ($titleArray as $titlesWorked) {
178
                $pageData = $pagesRepo->getPagesWikitext($projectData, $titlesWorked);
179
180
                foreach ($pageData as $title => $text) {
181
                    $type = str_replace('_', ' ', $type);
182
                    $rfx = new RFX(
183
                        $text,
184
                        $rfxParam[$projectData->getDomain()]['sections'],
185
                        $namespaces[2],
186
                        $rfxParam[$projectData->getDomain()]['date_regexp'],
187
                        $username
188
                    );
189
                    $section = $rfx->getUserSectionFound();
190
                    if ($section == '') {
191
                        // Skip over ones where the user didn't !vote.
192
                        continue;
193
                    }
194
                    // Todo: i18n-ize this
195
                    $finalData[$type][$section][$title]['Support']
196
                        = sizeof($rfx->getSection('support'));
197
                    $finalData[$type][$section][$title]['Oppose']
198
                        = sizeof($rfx->getSection('oppose'));
199
                    $finalData[$type][$section][$title]['Neutral']
200
                        = sizeof($rfx->getSection('neutral'));
201
                    $finalData[$type][$section][$title]['Date']
202
                        = $rfx->getEndDate();
203
                    $finalData[$type][$section][$title]['name']
204
                        = explode('/', $title)[1];
205
206
                    unset($rfx);
207
                }
208
            }
209
        }
210
211
        return $this->render(
212
            'rfxVoteCalculator/result.html.twig',
213
            [
214
                'xtPage' => 'rfxvote',
215
                'xtTitle' => $username,
216
                'user' => $userData,
217
                'project' => $projectData,
218
                'data'=> $finalData,
219
            ]
220
        );
221
    }
222
}
223