Completed
Pull Request — master (#97)
by MusikAnimal
02:14
created

ArticleInfoController::containerInitialized()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
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 Controller
24
{
25
    /**
26
     * Get the tool's shortname.
27
     * @return string
28
     */
29
    public function getToolShortname()
30
    {
31
        return 'articleinfo';
32
    }
33
34
    /**
35
     * The search form.
36
     * @Route("/articleinfo", name="articleinfo")
37
     * @Route("/articleinfo", name="articleInfo")
38
     * @Route("/articleinfo/", name="articleInfoSlash")
39
     * @Route("/articleinfo/index.php", name="articleInfoIndexPhp")
40
     * @Route("/articleinfo/{project}", name="ArticleInfoProject")
41
     * @param Request $request The HTTP request.
42
     * @return Response
43
     */
44
    public function indexAction(Request $request)
45
    {
46
        $projectQuery = $request->query->get('project');
47
        $article = $request->query->get('article');
48
49 View Code Duplication
        if ($projectQuery != '' && $article != '') {
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...
50
            return $this->redirectToRoute('ArticleInfoResult', [ 'project'=>$projectQuery, 'article' => $article ]);
51
        } elseif ($article != '') {
52
            return $this->redirectToRoute('ArticleInfoProject', [ 'project'=>$projectQuery ]);
53
        }
54
55
        if ($projectQuery == '') {
56
            $projectQuery = $this->container->getParameter('default_project');
57
        }
58
59
        $project = ProjectRepository::getProject($projectQuery, $this->container);
60
61
        return $this->render('articleInfo/index.html.twig', [
62
            'xtPage' => 'articleinfo',
63
            'xtPageTitle' => 'tool-articleinfo',
64
            'xtSubtitle' => 'tool-articleinfo-desc',
65
            'project' => $project,
66
        ]);
67
    }
68
69
    /**
70
     * Generate ArticleInfo gadget script for use on-wiki. This automatically points the
71
     * script to this installation's API. Pass ?uglify=1 to uglify the code.
72
     *
73
     * @Route("/articleinfo-gadget.js", name="ArticleInfoGadget")
74
     * @link https://www.mediawiki.org/wiki/XTools#ArticleInfo_gadget
75
     *
76
     * @param Request $request The HTTP request
77
     * @return Response
78
     */
79
    public function gadgetAction(Request $request)
80
    {
81
        $rendered = $this->renderView('articleInfo/articleinfo.js.twig');
82
83
        // SUPER hacky, but it works and is safe.
84
        if ($request->query->get('uglify') != '') {
85
            // $ and " need to be escaped.
86
            $rendered = str_replace('$', '\$', trim($rendered));
87
            $rendered = str_replace('"', '\"', trim($rendered));
88
89
            // Uglify temporary file.
90
            $tmpFile = sys_get_temp_dir() . '/xtools_articleinfo_gadget.js';
91
            $script = "echo \"$rendered\" | tee $tmpFile >/dev/null && ";
92
            $script .= $this->get('kernel')->getRootDir() .
93
                "/Resources/node_modules/uglify-es/bin/uglifyjs $tmpFile --mangle " .
94
                "&& rm $tmpFile >/dev/null";
95
            $process = new Process($script);
96
            $process->run();
97
98
            // Check for errors.
99
            $errorOutput = $process->getErrorOutput();
100
            if ($errorOutput != '') {
101
                $response = new \Symfony\Component\HttpFoundation\Response(
102
                    "Error generating uglified JS. The server said:\n\n$errorOutput"
103
                );
104
                return $response;
105
            }
106
107
            // Remove escaping.
108
            $rendered = str_replace('\$', '$', trim($process->getOutput()));
109
            $rendered = str_replace('\"', '"', trim($rendered));
110
111
            // Add comment after uglifying since it removes comments.
112
            $rendered = "/**\n * This code was automatically generated and should not " .
113
                "be manually edited.\n * For updates, please copy and paste from " .
114
                $this->generateUrl('ArticleInfoGadget', ['uglify' => 1], UrlGeneratorInterface::ABSOLUTE_URL) .
115
                "\n * Released under GPL v3 license.\n */\n" . $rendered;
116
        }
117
118
        $response = new \Symfony\Component\HttpFoundation\Response($rendered);
119
        $response->headers->set('Content-Type', 'text/javascript');
120
        return $response;
121
    }
122
123
    /**
124
     * Display the results.
125
     * @Route("/articleinfo/{project}/{article}", name="ArticleInfoResult", requirements={"article"=".+"})
126
     * @param Request $request The HTTP request.
127
     * @return Response
128
     */
129
    public function resultAction(Request $request)
130
    {
131
        $projectQuery = $request->attributes->get('project');
132
        $project = ProjectRepository::getProject($projectQuery, $this->container);
133
        $this->projectRepo = $project->getRepository();
0 ignored issues
show
Bug introduced by
The property projectRepo does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
134 View Code Duplication
        if (!$project->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...
135
            $this->addFlash('notice', ['invalid-project', $projectQuery]);
0 ignored issues
show
Documentation introduced by
array('invalid-project', $projectQuery) is of type array<integer,*,{"0":"string","1":"*"}>, 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...
136
            return $this->redirectToRoute('articleInfo');
137
        }
138
        $this->dbName = $project->getDatabaseName();
0 ignored issues
show
Bug introduced by
The property dbName does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
139
140
        $pageQuery = $request->attributes->get('article');
141
        $page = new Page($project, $pageQuery);
142
        $pageRepo = new PagesRepository();
143
        $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...
144
        $page->setRepository($pageRepo);
145
146
        if (!$page->exists()) {
147
            $this->addFlash('notice', ['no-exist', str_replace('_', ' ', $pageQuery)]);
0 ignored issues
show
Documentation introduced by
array('no-exist', str_re...('_', ' ', $pageQuery)) is of type array<integer,*,{"0":"string","1":"*"}>, 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...
148
            return $this->redirectToRoute('articleInfo');
149
        }
150
151
        $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...
152
        $articleInfo->prepareData();
153
154
        $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...
155
        $maxRevisions = $this->container->getParameter('app.max_page_revisions');
156
157
        // Show message if we hit the max revisions.
158
        if ($articleInfo->tooManyRevisions()) {
159
            // FIXME: i18n number_format?
160
            $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...
161
        }
162
163
        $ret = [
164
            'xtPage' => 'articleinfo',
165
            'xtTitle' => $page->getTitle(),
166
            'project' => $project,
167
            'editorlimit' => $request->query->get('editorlimit', 20),
168
            'botlimit' => $request->query->get('botlimit', 10),
169
            'pageviewsOffset' => 60,
170
            'ai' => $articleInfo,
171
            'page' => $page,
172
        ];
173
174
        // Output the relevant format template.
175
        $format = $request->query->get('format', 'html');
176
        if ($format == '') {
177
            // The default above doesn't work when the 'format' parameter is blank.
178
            $format = 'html';
179
        }
180
        $response = $this->render("articleInfo/result.$format.twig", $ret);
181
        if ($format == 'wikitext') {
182
            $response->headers->set('Content-Type', 'text/plain');
183
        }
184
        return $response;
185
    }
186
}
187