Completed
Push — master ( b7c59e...e15cd8 )
by Sam
04:11
created

AppExtension::functionLoggedInUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace AppBundle\Twig;
4
5
class AppExtension extends Extension
6
{
7
8
    public function getName()
9
    {
10
        return 'app_extension';
11
    }
12
13
    /*********************************** FUNCTIONS ***********************************/
14
15
    public function getFunctions()
16
    {
17
        $options = ['is_safe' => ['html']];
18
        return [
19
            new \Twig_SimpleFunction('request_time', [ $this, 'requestTime' ], $options),
20
            new \Twig_SimpleFunction('memory_usage', [ $this, 'requestMemory' ], $options),
21
            new \Twig_SimpleFunction('year', [ $this, 'generateYear' ], $options),
22
            new \Twig_SimpleFunction('msgPrintExists', [ $this, 'intuitionMessagePrintExists' ], $options),
23
            new \Twig_SimpleFunction('msgExists', [ $this, 'intuitionMessageExists' ], $options),
24
            new \Twig_SimpleFunction('msg', [ $this, 'intuitionMessage' ], $options),
25
            new \Twig_SimpleFunction('lang', [ $this, 'getLang' ], $options),
26
            new \Twig_SimpleFunction('langName', [ $this, 'getLangName' ], $options),
27
            new \Twig_SimpleFunction('allLangs', [ $this, 'getAllLangs' ]),
28
            new \Twig_SimpleFunction('isRTL', [ $this, 'intuitionIsRTL' ]),
29
            new \Twig_SimpleFunction('isRTLLang', [ $this, 'intuitionIsRTLLang' ]),
30
            new \Twig_SimpleFunction('shortHash', [ $this, 'gitShortHash' ]),
31
            new \Twig_SimpleFunction('hash', [ $this, 'gitHash' ]),
32
            new \Twig_SimpleFunction('enabled', [ $this, 'tabEnabled' ]),
33
            new \Twig_SimpleFunction('tools', [ $this, 'allTools' ]),
34
            new \Twig_SimpleFunction('color', [ $this, 'getColorList' ]),
35
            new \Twig_SimpleFunction('chartColor', [ $this, 'chartColor' ]),
36
            new \Twig_SimpleFunction('isWMFLabs', [ $this, 'isWMFLabs' ]),
37
            new \Twig_SimpleFunction('isSingleWiki', [ $this, 'isSingleWiki' ]),
38
            new \Twig_SimpleFunction('getReplagThreshold', [ $this, 'getReplagThreshold' ]),
39
            new \Twig_SimpleFunction('loadStylesheetsFromCDN', [ $this, 'loadStylesheetsFromCDN' ]),
40
            new \Twig_SimpleFunction('isWMFLabs', [ $this, 'isWMFLabs' ]),
41
            new \Twig_SimpleFunction('replag', [ $this, 'replag' ]),
42
            new \Twig_SimpleFunction('link', [ $this, 'link' ]),
43
            new \Twig_SimpleFunction('quote', [ $this, 'quote' ]),
44
            new \Twig_SimpleFunction('bugReportURL', [ $this, 'bugReportURL' ]),
45
            new \Twig_SimpleFunction('logged_in_user', [$this, 'functionLoggedInUser']),
46
        ];
47
    }
48
49
    public function requestTime($decimals = 3)
0 ignored issues
show
Coding Style introduced by
requestTime uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
50
    {
51
52
        return number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], $decimals);
53
    }
54
55
    public function requestMemory()
56
    {
57
        $mem = memory_get_usage(false);
58
        $div = pow(1024, 2);
59
        $mem = $mem / $div;
60
61
        return round($mem, 2);
62
    }
63
64
    public function generateYear()
65
    {
66
        return date('Y');
67
    }
68
69
    // TODO: refactor all intuition stuff so it can be used anywhere
70
    public function intuitionMessageExists($message = "")
71
    {
72
        return $this->getIntuition()->msgExists($message, [ "domain" => "xtools" ]);
73
    }
74
75
    public function intuitionMessagePrintExists($message = "", $vars = [])
76
    {
77
        if (is_array($message)) {
78
            $vars = $message;
79
            $message = $message[0];
80
            $vars = array_slice($vars, 1);
81
        }
82
        if ($this->intuitionMessageExists($message)) {
83
            return $this->intuitionMessage($message, $vars);
84
        } else {
85
            return $message;
86
        }
87
    }
88
89
    public function intuitionMessage($message = "", $vars = [])
90
    {
91
        return $this->getIntuition()->msg($message, [ "domain" => "xtools", "variables" => $vars ]);
92
    }
93
94
    public function getLang()
95
    {
96
        return $this->getIntuition()->getLang();
97
    }
98
99
    public function getLangName()
100
    {
101
        return in_array($this->getIntuition()->getLangName(), $this->getAllLangs())
102
            ? $this->getIntuition()->getLangName()
103
            : 'English';
104
    }
105
106
    /**
107
     * Get all available languages in the i18n directory
108
     * @return array Associative array of langKey => langName
109
     */
110
    public function getAllLangs()
111
    {
112
        $messageFiles = glob($this->container->getParameter("kernel.root_dir") . '/../i18n/*.json');
113
114
        $languages = array_values(array_unique(array_map(
115
            function ($filename) {
116
                return basename($filename, '.json');
117
            },
118
            $messageFiles
119
        )));
120
121
        $availableLanguages = [];
122
123
        foreach ($languages as $lang) {
124
            $availableLanguages[$lang] = ucfirst($this->getIntuition()->getLangName($lang));
125
        }
126
        asort($availableLanguages);
127
128
        return $availableLanguages;
129
    }
130
131
    public function intuitionIsRTL()
132
    {
133
        return $this->getIntuition()->isRTL($this->getIntuition()->getLang());
134
    }
135
136
    public function intuitionIsRTLLang($lang)
137
    {
138
        return $this->getIntuition()->isRTL($lang);
139
    }
140
141
    public function gitShortHash()
142
    {
143
        return exec("git rev-parse --short HEAD");
144
    }
145
146
    public function gitHash()
147
    {
148
        return exec("git rev-parse HEAD");
149
    }
150
151 View Code Duplication
    public function tabEnabled($tool = "index")
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
152
    {
153
        $param = false;
154
        if ($this->container->hasParameter("enable.$tool")) {
155
            $param = boolval($this->container->getParameter("enable.$tool"));
156
        }
157
        return $param;
158
    }
159
160
    public function allTools()
161
    {
162
        $retVal = [];
163
        if ($this->container->hasParameter("tools")) {
164
            $retVal = $this->container->getParameter("tools");
165
        }
166
        return $retVal;
167
    }
168
169
    public static function getColorList($num = false)
170
    {
171
        $colors = [
172
            0 => '#Cc0000',# '#FF005A', #red '#FF5555',
173
            1 => '#F7b7b7',
174
            2 => '#5c8d20',# '#008800', #green'#55FF55',
175
            3 => '#85eD82',
176
            4 => '#2E97E0', # blue
177
            5 => '#B9E3F9',
178
            6 => '#e1711d',  # orange
179
            7 => '#ffc04c',
180
            8 => '#FDFF98', # yellow
181
            9 => '#5555FF',
182
            10 => '#55FFFF',
183
            11 => '#0000C0',  #
184
            12 => '#008800',  # green
185
            13 => '#00C0C0',
186
            14 => '#FFAFAF',  # rosé
187
            15 => '#808080',  # gray
188
            16 => '#00C000',
189
            17 => '#404040',
190
            18 => '#C0C000',  # green
191
            19 => '#C000C0',
192
            100 => '#75A3D1',  # blue
193
            101 => '#A679D2',  # purple
194
            102 => '#660000',
195
            103 => '#000066',
196
            104 => '#FAFFAF',  # caramel
197
            105 => '#408345',
198
            106 => '#5c8d20',
199
            107 => '#e1711d',  # red
200
            108 => '#94ef2b',  # light green
201
            109 => '#756a4a',  # brown
202
            110 => '#6f1dab',
203
            111 => '#301e30',
204
            112 => '#5c9d96',
205
            113 => '#a8cd8c',  # earth green
206
            114 => '#f2b3f1',  # light purple
207
            115 => '#9b5828',
208
            118 => '#99FFFF',
209
            119 => '#99BBFF',
210
            120 => '#FF99FF',
211
            121 => '#CCFFFF',
212
            122 => '#CCFF00',
213
            123 => '#CCFFCC',
214
            200 => '#33FF00',
215
            201 => '#669900',
216
            202 => '#666666',
217
            203 => '#999999',
218
            204 => '#FFFFCC',
219
            205 => '#FF00CC',
220
            206 => '#FFFF00',
221
            207 => '#FFCC00',
222
            208 => '#FF0000',
223
            209 => '#FF6600',
224
            446 => '#06DCFB',
225
            447 => '#892EE4',
226
            460 => '#99FF66',
227
            461 => '#99CC66',  # green
228
            470 => '#CCCC33',  # ocker
229
            471 => '#CCFF33',
230
            480 => '#6699FF',
231
            481 => '#66FFFF',
232
            490 => '#995500',
233
            491 => '#998800',
234
            710 => '#FFCECE',
235
            711 => '#FFC8F2',
236
            828 => '#F7DE00',
237
            829 => '#BABA21',
238
            866 => '#FFFFFF',
239
            867 => '#FFCCFF',
240
            1198 => '#FF34B3',
241
            1199 => '#8B1C62',
242
243
            '#61a9f3',# blue
244
            '#f381b9',# pink
245
            '#61E3A9',
246
            '#D56DE2',
247
            '#85eD82',
248
            '#F7b7b7',
249
            '#CFDF49',
250
            '#88d8f2',
251
            '#07AF7B',# green
252
            '#B9E3F9',
253
            '#FFF3AD',
254
            '#EF606A',# red
255
            '#EC8833',
256
            '#FFF100',
257
            '#87C9A5',
258
            '#FFFB11',
259
            '#005EBC',
260
            '#9AEB67',
261
            '#FF4A26',
262
            '#FDFF98',
263
            '#6B7EFF',
264
            '#BCE02E',
265
            '#E0642E',
266
            '#E0D62E',
267
            '#02927F',
268
            '#FF005A',
269
            '#61a9f3', # blue' #FFFF55',
270
        ];
271
272
        if ($num === false) {
273
            return $colors;
274
        } elseif (isset($colors[$num])) {
275
            return $colors[$num];
276
        } else {
277
            // Default to grey.
278
            return '#CCC';
279
        }
280
    }
281
282
    /**
283
     * Get color-blind friendly colors for use in charts
284
     * @param  Integer $num Index of color
285
     * @return String RGBA color (so you can more easily adjust the opacity)
286
     */
287
    public function chartColor($num)
288
    {
289
        $colors = [
290
            'rgba(171, 212, 235, 1)',
291
            'rgba(178, 223, 138, 1)',
292
            'rgba(251, 154, 153, 1)',
293
            'rgba(253, 191, 111, 1)',
294
            'rgba(202, 178, 214, 1)',
295
            'rgba(207, 182, 128, 1)',
296
            'rgba(141, 211, 199, 1)',
297
            'rgba(252, 205, 229, 1)',
298
            'rgba(255, 247, 161, 1)',
299
            'rgba(217, 217, 217, 1)',
300
        ];
301
302
        return $colors[$num % count($colors)];
303
    }
304
305 View Code Duplication
    public function isSingleWiki()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
306
    {
307
        $param = true;
308
        if ($this->container->hasParameter("app.single_wiki")) {
309
            $param = boolval($this->container->getParameter("app.single_wiki"));
310
        }
311
        return $param;
312
    }
313
314
    public function getReplagThreshold()
315
    {
316
        $param = 30;
317
        if ($this->container->hasParameter("app.replag_threshold")) {
318
            $param = $this->container->getParameter("app.replag_threshold");
319
        };
320
        return $param;
321
    }
322
323 View Code Duplication
    public function loadStylesheetsFromCDN()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
324
    {
325
        $param = false;
326
        if ($this->container->hasParameter("app.load_stylesheets_from_cdn")) {
327
            $param = boolval($this->container->getParameter("app.load_stylesheets_from_cdn"));
328
        }
329
        return $param;
330
    }
331
332 View Code Duplication
    public function isWMFLabs()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
333
    {
334
        $param = false;
335
        if ($this->container->hasParameter("app.is_labs")) {
336
            $param = boolval($this->container->getParameter("app.is_labs"));
337
        }
338
        return $param;
339
    }
340
341
    public function replag()
342
    {
343
        $retVal = 0;
344
345
        if ($this->isWMFLabs()) {
346
            $project = $this->container->get("request_stack")->getCurrentRequest()->get('project');
347
348
            if (!isset($project)) {
349
                $project = "enwiki";
350
            }
351
352
            $stmt = "SELECT lag FROM `heartbeat_p`.`heartbeat` h
353
            RIGHT JOIN `meta_p`.`wiki` w on concat(h.shard, \".labsdb\")=w.slice
354
            where dbname like :project or name like :project or url like :project limit 1";
355
356
            $conn = $this->container->get('doctrine')->getManager("replicas")->getConnection();
357
358
            // Prepare the query and execute
359
            $resultQuery = $conn->prepare($stmt);
360
            $resultQuery->bindParam("project", $project);
361
            $resultQuery->execute();
362
363
            if ($resultQuery->errorCode() == 0) {
364
                $results = $resultQuery->fetchAll();
365
366
                if (isset($results[0]["lag"])) {
367
                    $retVal = $results[0]["lag"];
368
                }
369
            }
370
        }
371
372
        return $retVal;
373
    }
374
375
    public function link($path = "/")
376
    {
377
        $base_path = $this->container->getParameter("app.base_path");
378
        $retVal = $path;
379
380
        if (isset($base_path)) {
381
            $retVal = "$base_path/$path";
382
        }
383
384
        $retVal = str_replace("//", "/", $retVal);
385
386
        return $retVal;
387
    }
388
389
    /**
390
     * Get a random quote for the footer
391
     * @return string
392
     */
393
    public function quote()
394
    {
395
        $quotes = $this->container->getParameter('quotes');
396
        $id = array_rand($quotes);
397
        return $quotes[$id];
398
    }
399
400
    /**
401
     * Get the currently logged in user's details.
402
     * @return string[]
403
     */
404
    public function functionLoggedInUser()
405
    {
406
        return $this->container->get('session')->get('logged_in_user');
407
    }
408
409
410
    /*********************************** FILTERS ***********************************/
411
412
    public function getFilters()
413
    {
414
        return [
415
            new \Twig_SimpleFilter('capitalize_first', [ $this, 'capitalizeFirst' ]),
416
            new \Twig_SimpleFilter('percent_format', [ $this, 'percentFormat' ]),
417
        ];
418
    }
419
420
    /**
421
     * Mysteriously missing Twig helper to capitalize only the first character.
422
     * E.g. used for table headings for translated messages
423
     * @param  string $str The string
424
     * @return string      The string, capitalized
425
     */
426
    public function capitalizeFirst($str)
427
    {
428
        return ucfirst($str);
429
    }
430
431
    /**
432
     * Format a given number or fraction as a percentage
433
     * @param  number  $numerator     Numerator or single fraction if denominator is ommitted
434
     * @param  number  [$denominator] Denominator
435
     * @param  integer [$precision]   Number of decimal places to show
436
     * @return string                 Formatted percentage
437
     */
438
    public function percentFormat($numerator, $denominator = null, $precision = 1)
439
    {
440
        if (!$denominator) {
441
            $quotient = $numerator;
442
        } else {
443
            $quotient = ( $numerator / $denominator ) * 100;
444
        }
445
446
        return round($quotient, $precision) . '%';
447
    }
448
}
449