Passed
Push — master ( 35c320...7deb12 )
by MusikAnimal
04:42
created

QuoteController::quoteAllAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 0
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains only the QuoteController 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\JsonResponse;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\Routing\Exception\InvalidParameterException;
14
15
/**
16
 * A quick note: This tool is referred to as "bash" in much of the legacy code base.  As such,
17
 * the terms "quote" and "bash" are used interchangeably here, so as to not break many conventions.
18
 *
19
 * This tool is intentionally disabled in the WMF installation.
20
 * @codeCoverageIgnore
21
 */
22
class QuoteController extends XtoolsController
23
{
24
25
    /**
26
     * Get the name of the tool's index route.
27
     * @return string
28
     * @codeCoverageIgnore
29
     */
30
    public function getIndexRoute()
31
    {
32
        return 'Quote';
33
    }
34
35
    /**
36
     * Method for rendering the Bash Main Form.
37
     * This method redirects if valid parameters are found, making it a
38
     * valid form endpoint as well.
39
     *
40
     * @param \Symfony\Component\HttpFoundation\Request $request Given by Symfony
41
     *
42
     * @Route("/bash",  name="Bash")
43
     * @Route("/quote", name="Quote")
44
     * @Route("/bash/base.php", name="BashBase")
45
     * @return \Symfony\Component\HttpFoundation\Response
46
     */
47
    public function indexAction(Request $request)
48
    {
49
        // Check to see if the quote is a param.  If so,
50
        // redirect to the proper route.
51
        if ($request->query->get('id') != '') {
52
            return $this->redirectToRoute(
53
                "quoteID",
54
                ["id"=>$request->query->get('id')]
55
            );
56
        }
57
58
        // Oterwise render the form.
59
        return $this->render(
60
            'quote/index.html.twig',
61
            [
62
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..'),
63
                'xtPage' => 'bash',
64
                'xtPageTitle' => 'tool-bash',
65
                'xtSubtitle' => 'tool-bash-desc',
66
            ]
67
        );
68
    }
69
70
    /**
71
     * Method for rendering a random quote.
72
     * This should redirect to the /quote/{id} path below
73
     *
74
     * @Route("/quote/random", name="QuoteRandom")
75
     * @Route("/bash/random",  name="BashRandom")
76
     *
77
     * @return RedirectResponse
0 ignored issues
show
Bug introduced by
The type AppBundle\Controller\RedirectResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
78
     */
79
    public function randomQuoteAction()
80
    {
81
        // Choose a random quote by ID.
82
        // if we can't find the quotes, return back to  the main form with
83
        // a flash notice.
84
        try {
85
            $id = rand(1, sizeof($this->getParameter("quotes")));
86
        } catch (InvalidParameterException $e) {
87
            $this->addFlash("notice", ["noquotes"]);
0 ignored issues
show
Bug introduced by
array('noquotes') of type array<integer,string> is incompatible with the type string expected by parameter $message of Symfony\Bundle\Framework...\Controller::addFlash(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

87
            $this->addFlash("notice", /** @scrutinizer ignore-type */ ["noquotes"]);
Loading history...
88
            return $this->redirectToRoute("quote");
89
        }
90
91
        return $this->redirectToRoute("quoteID", ["id"=>$id]);
92
    }
93
94
    /**
95
     * Method to show all quotes.
96
     *
97
     * @Route("/quote/all", name="QuoteAll")
98
     * @Route("/bash/all",  name="BashAll")
99
     *
100
     * @return Response
101
     */
102
    public function quoteAllAction()
103
    {
104
        // Load up an array of all the quotes.
105
        // if we can't find the quotes, return back to  the main form with
106
        // a flash notice.
107
        try {
108
            $quotes = $this->getParameter("quotes");
109
        } catch (InvalidParameterException $e) {
110
            $this->addFlash("notice", ["noquotes"]);
0 ignored issues
show
Bug introduced by
array('noquotes') of type array<integer,string> is incompatible with the type string expected by parameter $message of Symfony\Bundle\Framework...\Controller::addFlash(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

110
            $this->addFlash("notice", /** @scrutinizer ignore-type */ ["noquotes"]);
Loading history...
111
            return $this->redirectToRoute("quote");
112
        }
113
114
        // Render the page.
115
        return $this->render(
116
            'quote/all.html.twig',
117
            [
118
                'base_dir' => realpath(
119
                    $this->getParameter('kernel.root_dir') . '/..'
120
                ),
121
                'xtPage' => 'bash',
122
                'quotes' => $quotes,
123
            ]
124
        );
125
    }
126
127
    /**
128
     * Method to render a single quote.
129
     *
130
     * @param int $id ID of the quote
131
     *
132
     * @Route("/quote/{id}", name="QuoteID")
133
     * @Route("/bash/{id}",  name="BashID")
134
     *
135
     * @return Response
136
     */
137
    public function quoteAction($id)
138
    {
139
        // Get the singular quote.
140
        // if we can't find the quotes, return back to  the main form with
141
        // a flash notice.
142
        try {
143
            if (isset($this->getParameter("quotes")[$id])) {
144
                $text = $this->getParameter("quotes")[$id];
145
            } else {
146
                throw new InvalidParameterException("Quote doesn't exist");
147
            }
148
        } catch (InvalidParameterException $e) {
149
            $this->addFlash("notice", ["noquotes"]);
0 ignored issues
show
Bug introduced by
array('noquotes') of type array<integer,string> is incompatible with the type string expected by parameter $message of Symfony\Bundle\Framework...\Controller::addFlash(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

149
            $this->addFlash("notice", /** @scrutinizer ignore-type */ ["noquotes"]);
Loading history...
150
            return $this->redirectToRoute("quote");
151
        }
152
153
        // If the text is undefined, that quote doesn't exist.
154
        // Redirect back to the main form.
155
        if (!isset($text)) {
156
            $this->addFlash("notice", ["noquotes"]);
157
            return $this->redirectToRoute("quote");
158
        }
159
160
        // Show the quote.
161
        return $this->render(
162
            'quote/view.html.twig',
163
            [
164
                'base_dir' => realpath(
165
                    $this->getParameter('kernel.root_dir') . '/..'
166
                ),
167
                "xtPage" => "bash",
168
                "text" => $text,
169
                "id" => $id,
170
            ]
171
        );
172
    }
173
174
    /************************ API endpoints ************************/
175
176
    /**
177
     * Get random quote.
178
     * @Route("/api/quote/random", name="QuoteApiRandom")
179
     * @return Response
180
     * @codeCoverageIgnore
181
     */
182
    public function randomQuoteApiAction()
183
    {
184
        $this->recordApiUsage('quote/random');
185
186
        // Don't show if bash is turned off, but always show for Labs
187
        // (so quote is in footer but not in nav).
188
        $isLabs = $this->container->getParameter('app.is_labs');
189
        if (!$isLabs && !$this->container->getParameter('enable.bash')) {
190
            return '';
191
        }
192
        $quotes = $this->container->getParameter('quotes');
193
        $id = array_rand($quotes);
194
195
        return new JsonResponse(
196
            [$id => $quotes[$id]],
197
            Response::HTTP_OK
198
        );
199
    }
200
201
    /**
202
     * Get all quotes.
203
     * @Route("/api/quote/all", name="QuoteApiAll")
204
     * @return Response
205
     * @codeCoverageIgnore
206
     */
207
    public function allQuotesApiAction()
208
    {
209
        $this->recordApiUsage('quote/all');
210
211
        // Don't show if bash is turned off, but always show for Labs
212
        // (so quote is in footer but not in nav).
213
        $isLabs = $this->container->getParameter('app.is_labs');
214
        if (!$isLabs && !$this->container->getParameter('enable.bash')) {
215
            return '';
216
        }
217
        $quotes = $this->container->getParameter('quotes');
218
        $numberedQuotes = [];
219
220
        // Number the quotes, since they somehow have significance.
221
        foreach ($quotes as $index => $quote) {
222
            $numberedQuotes[(string)$index + 1] = $quote;
223
        }
224
225
        return new JsonResponse($numberedQuotes, Response::HTTP_OK);
226
    }
227
228
    /**
229
     * Get the quote with the given ID.
230
     * @Route("/api/quote/{id}", name="QuoteApiQuote", requirements={"id"="\d+"})
231
     * @param int $id
232
     * @return Response
233
     * @codeCoverageIgnore
234
     */
235
    public function singleQuotesApiAction($id)
236
    {
237
        $this->recordApiUsage('quote/id');
238
239
        // Don't show if bash is turned off, but always show for Labs
240
        // (so quote is in footer but not in nav).
241
        $isLabs = $this->container->getParameter('app.is_labs');
242
        if (!$isLabs && !$this->container->getParameter('enable.bash')) {
243
            return '';
244
        }
245
        $quotes = $this->container->getParameter('quotes');
246
247
        if (!isset($quotes[$id])) {
248
            return new JsonResponse(
249
                [
250
                    'error' => [
251
                        'code' => Response::HTTP_NOT_FOUND,
252
                        'message' => 'No quote found with ID '.$id,
253
                    ]
254
                ],
255
                Response::HTTP_NOT_FOUND
256
            );
257
        }
258
259
        return new JsonResponse([
260
            $id => $quotes[$id]
261
        ], Response::HTTP_OK);
262
    }
263
}
264