Completed
Push — master ( e3e8c6...010637 )
by MusikAnimal
12s
created

ArticleInfoController::resultAction()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 51
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 51
rs 8.6588
c 0
b 0
f 0
cc 6
eloc 31
nc 10
nop 2

How to fix   Long Method   

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 only the ArticleInfoController class.
4
 */
5
6
namespace AppBundle\Controller;
7
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
9
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\Process\Process;
14
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
15
use Xtools\ProjectRepository;
16
use Xtools\Page;
17
use Xtools\PagesRepository;
18
use Xtools\ArticleInfo;
19
20
/**
21
 * This controller serves the search form and results for the ArticleInfo tool
22
 */
23
class ArticleInfoController extends XtoolsController
24
{
25
    /**
26
     * Get the tool's shortname.
27
     * @return string
28
     * @codeCoverageIgnore
29
     */
30
    public function getToolShortname()
31
    {
32
        return 'articleinfo';
33
    }
34
35
    /**
36
     * The search form.
37
     * @Route("/articleinfo", name="articleinfo")
38
     * @Route("/articleinfo", name="articleInfo")
39
     * @Route("/articleinfo/", name="articleInfoSlash")
40
     * @Route("/articleinfo/index.php", name="articleInfoIndexPhp")
41
     * @Route("/articleinfo/{project}", name="ArticleInfoProject")
42
     * @param Request $request The HTTP request.
43
     * @return Response
44
     */
45
    public function indexAction(Request $request)
46
    {
47
        $params = $this->parseQueryParams($request);
48
49
        if (isset($params['project']) && isset($params['article'])) {
50
            return $this->redirectToRoute('ArticleInfoResult', $params);
51
        }
52
53
        // Convert the given project (or default project) into a Project instance.
54
        $params['project'] = $this->getProjectFromQuery($params);
55
56
        return $this->render('articleInfo/index.html.twig', [
57
            'xtPage' => 'articleinfo',
58
            'xtPageTitle' => 'tool-articleinfo',
59
            'xtSubtitle' => 'tool-articleinfo-desc',
60
            'project' => $params['project'],
61
        ]);
62
    }
63
64
    /**
65
     * Generate ArticleInfo gadget script for use on-wiki. This automatically points the
66
     * script to this installation's API. Pass ?uglify=1 to uglify the code.
67
     *
68
     * @Route("/articleinfo-gadget.js", name="ArticleInfoGadget")
69
     * @link https://www.mediawiki.org/wiki/XTools#ArticleInfo_gadget
70
     *
71
     * @param Request $request The HTTP request
72
     * @return Response
73
     * @codeCoverageIgnore
74
     */
75
    public function gadgetAction(Request $request)
76
    {
77
        $rendered = $this->renderView('articleInfo/articleinfo.js.twig');
78
79
        // SUPER hacky, but it works and is safe.
80
        if ($request->query->get('uglify') != '') {
81
            // $ and " need to be escaped.
82
            $rendered = str_replace('$', '\$', trim($rendered));
83
            $rendered = str_replace('"', '\"', trim($rendered));
84
85
            // Uglify temporary file.
86
            $tmpFile = sys_get_temp_dir() . '/xtools_articleinfo_gadget.js';
87
            $script = "echo \"$rendered\" | tee $tmpFile >/dev/null && ";
88
            $script .= $this->get('kernel')->getRootDir() .
89
                "/Resources/node_modules/uglify-es/bin/uglifyjs $tmpFile --mangle " .
90
                "&& rm $tmpFile >/dev/null";
91
            $process = new Process($script);
92
            $process->run();
93
94
            // Check for errors.
95
            $errorOutput = $process->getErrorOutput();
96
            if ($errorOutput != '') {
97
                $response = new \Symfony\Component\HttpFoundation\Response(
98
                    "Error generating uglified JS. The server said:\n\n$errorOutput"
99
                );
100
                return $response;
101
            }
102
103
            // Remove escaping.
104
            $rendered = str_replace('\$', '$', trim($process->getOutput()));
105
            $rendered = str_replace('\"', '"', trim($rendered));
106
107
            // Add comment after uglifying since it removes comments.
108
            $rendered = "/**\n * This code was automatically generated and should not " .
109
                "be manually edited.\n * For updates, please copy and paste from " .
110
                $this->generateUrl('ArticleInfoGadget', ['uglify' => 1], UrlGeneratorInterface::ABSOLUTE_URL) .
111
                "\n * Released under GPL v3 license.\n */\n" . $rendered;
112
        }
113
114
        $response = new \Symfony\Component\HttpFoundation\Response($rendered);
115
        $response->headers->set('Content-Type', 'text/javascript');
116
        return $response;
117
    }
118
119
    /**
120
     * Display the results.
121
     * @Route("/articleinfo/{project}/{article}", name="ArticleInfoResult", requirements={"article"=".+"})
122
     * @param Request $request The HTTP request.
123
     * @param string $article
124
     * @return Response
125
     * @codeCoverageIgnore
126
     */
127
    public function resultAction(Request $request, $article)
128
    {
129
        // In this case only the project is validated.
130
        $ret = $this->validateProjectAndUser($request);
131
        if ($ret instanceof RedirectResponse) {
0 ignored issues
show
Bug introduced by
The class AppBundle\Controller\RedirectResponse does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
132
            return $ret;
133
        } else {
134
            $project = $ret[0];
135
        }
136
137
        $page = $this->getAndValidatePage($project, $article);
138
        if ($page instanceof RedirectResponse) {
0 ignored issues
show
Bug introduced by
The class AppBundle\Controller\RedirectResponse does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
139
            return $page;
140
        }
141
142
        $articleInfo = new ArticleInfo($page, $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...
143
        $articleInfo->prepareData();
144
145
        $numRevisions = $articleInfo->getNumRevisions();
0 ignored issues
show
Unused Code introduced by
$numRevisions is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
146
        $maxRevisions = $this->container->getParameter('app.max_page_revisions');
147
148
        // Show message if we hit the max revisions.
149
        if ($articleInfo->tooManyRevisions()) {
150
            // FIXME: i18n number_format?
151
            $this->addFlash('notice', ['too-many-revisions', number_format($maxRevisions), $maxRevisions]);
0 ignored issues
show
Documentation introduced by
array('too-many-revision...isions), $maxRevisions) is of type array<integer,*,{"0":"st...,"1":"string","2":"*"}>, 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...
152
        }
153
154
        $ret = [
155
            'xtPage' => 'articleinfo',
156
            'xtTitle' => $page->getTitle(),
0 ignored issues
show
Bug introduced by
The method getTitle does only exist in Xtools\Page, but not in Symfony\Component\HttpFoundation\RedirectResponse.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
157
            'project' => $project,
158
            'editorlimit' => $request->query->get('editorlimit', 20),
159
            'botlimit' => $request->query->get('botlimit', 10),
160
            'pageviewsOffset' => 60,
161
            'ai' => $articleInfo,
162
            'page' => $page,
163
        ];
164
165
        // Output the relevant format template.
166
        $format = $request->query->get('format', 'html');
167
        if ($format == '') {
168
            // The default above doesn't work when the 'format' parameter is blank.
169
            $format = 'html';
170
        }
171
        $response = $this->render("articleInfo/result.$format.twig", $ret);
172
        if ($format == 'wikitext') {
173
            $response->headers->set('Content-Type', 'text/plain');
174
        }
175
176
        return $response;
177
    }
178
}
179