Completed
Push — master ( 63e07d...12af8f )
by Lars
14:37 queued 01:07
created

Bootup   D

Complexity

Total Complexity 88

Size/Duplication

Total Lines 543
Duplicated Lines 5.16 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 68.36%

Importance

Changes 20
Bugs 11 Features 1
Metric Value
wmc 88
c 20
b 11
f 1
lcom 1
cbo 2
dl 28
loc 543
ccs 188
cts 275
cp 0.6836
rs 4.8718

13 Methods

Rating   Name   Duplication   Size   Complexity  
A initAll() 0 12 1
A initNormalizer() 0 4 1
A initUtf8Encode() 0 4 2
B initIconv() 0 18 6
D initMbstring() 0 80 13
B initExif() 6 12 6
B initIntl() 0 15 6
A initLocale() 0 23 2
F get_random_bytes() 0 178 29
A is_php() 0 10 2
C filterRequestUri() 0 43 7
B filterRequestInputs() 0 35 5
C filterString() 22 28 8

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Bootup often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Bootup, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * Copyright (C) 2013 Nicolas Grekas - [email protected]
5
 *
6
 * This library is free software; you can redistribute it and/or modify it
7
 * under the terms of the (at your option):
8
 * Apache License v2.0 (http://apache.org/licenses/LICENSE-2.0.txt), or
9
 * GNU General Public License v2.0 (http://gnu.org/licenses/gpl-2.0.txt).
10
 */
11
12
namespace voku\helper;
13
14
use voku\helper\shim\Intl;
15
use voku\helper\shim\Normalizer;
16
17
/**
18
 * Class Bootup
19
 *
20
 * this is a bootstrap for the polyfills (iconv / intl / mbstring / normalizer / xml)
21
 *
22
 * @package voku\helper
23
 */
24
class Bootup
25
{
26
  /**
27
   * bootstrap
28
   */
29 1
  public static function initAll()
30
  {
31 1
    ini_set('default_charset', 'UTF-8');
32
33 1
    self::initNormalizer();
34 1
    self::initUtf8Encode();
35 1
    self::initIconv();
36 1
    self::initMbstring();
37 1
    self::initExif();
38 1
    self::initIntl();
39 1
    self::initLocale();
40 1
  }
41
42
  /**
43
   * init Normalizer
44
   */
45 1
  protected static function initNormalizer()
46
  {
47 1
    require_once 'shim/Normalizer.php';
48 1
  }
49
50
  /**
51
   * init utf8_encode
52
   */
53 1
  protected static function initUtf8Encode()
54
  {
55 1
    function_exists('utf8_encode') or require __DIR__ . '/bootup/utf8_encode.php';
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
56 1
  }
57
58
  /**
59
   * init iconv
60
   */
61 1
  protected static function initIconv()
62
  {
63 1
    if (extension_loaded('iconv')) {
64 1
      if ('UTF-8' !== strtoupper(iconv_get_encoding('input_encoding'))) {
65 1
        iconv_set_encoding('input_encoding', 'UTF-8');
66 1
      }
67
68 1
      if ('UTF-8' !== strtoupper(iconv_get_encoding('internal_encoding'))) {
69 1
        iconv_set_encoding('internal_encoding', 'UTF-8');
70 1
      }
71
72 1
      if ('UTF-8' !== strtoupper(iconv_get_encoding('output_encoding'))) {
73 1
        iconv_set_encoding('output_encoding', 'UTF-8');
74 1
      }
75 1
    } elseif (!defined('ICONV_IMPL')) {
76
      require __DIR__ . '/bootup/iconv.php';
77
    }
78 1
  }
79
80
  /**
81
   * init mbstring
82
   */
83 1
  protected static function initMbstring()
84
  {
85 1
    if (extension_loaded('mbstring')) {
86
      if (
87
          (
88 1
              (int)ini_get('mbstring.encoding_translation')
89
              ||
90 1
              in_array(
91 1
                  strtolower(ini_get('mbstring.encoding_translation')),
92
                  array(
93 1
                      'on',
94 1
                      'yes',
95 1
                      'true',
96 1
                  ),
97
                  true
98 1
              )
99 1
          )
100 1
          &&
101
          !in_array(
102
              strtolower(ini_get('mbstring.http_input')),
103
              array(
104
                  'pass',
105
                  '8bit',
106
                  'utf-8',
107
              ),
108
              true
109
          )
110 1
      ) {
111
        user_error(
112
            'php.ini settings: Please disable mbstring.encoding_translation or set mbstring.http_input to "pass"',
113
            E_USER_WARNING
114
        );
115
      }
116
117 1
      if (MB_OVERLOAD_STRING & (int)ini_get('mbstring.func_overload')) {
118
        user_error('php.ini settings: Please disable mbstring.func_overload', E_USER_WARNING);
119
      }
120
121 1
      if (function_exists('mb_regex_encoding')) {
122 1
        mb_regex_encoding('UTF-8');
123 1
      }
124 1
      ini_set('mbstring.script_encoding', 'pass');
125
126 1
      if ('utf-8' !== strtolower(mb_internal_encoding())) {
127
        mb_internal_encoding('UTF-8');
128
      }
129
130 1
      if ('none' !== strtolower(mb_substitute_character())) {
131 1
        mb_substitute_character('none');
0 ignored issues
show
Unused Code introduced by
The call to the function mb_substitute_character() seems unnecessary as the function has no side-effects.
Loading history...
132 1
      }
133
134 1
      if (!in_array(
135 1
          strtolower(mb_http_output()),
136
          array(
137 1
              'pass',
138 1
              '8bit',
139 1
          ),
140
          true
141 1
      )
142 1
      ) {
143
        mb_http_output('pass');
0 ignored issues
show
Unused Code introduced by
The call to the function mb_http_output() seems unnecessary as the function has no side-effects.
Loading history...
144
      }
145
146 1
      if (!in_array(
147 1
          strtolower(mb_language()),
148
          array(
149 1
              'uni',
150 1
              'neutral',
151 1
          ),
152
          true
153 1
      )
154 1
      ) {
155
        mb_language('uni');
156
      }
157 1
    } elseif (!defined('MB_OVERLOAD_MAIL')) {
158
      extension_loaded('iconv') or self::initIconv();
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
159
160
      require __DIR__ . '/bootup/mbstring.php';
161
    }
162 1
  }
163
164
  /**
165
   * init exif
166
   */
167 1
  protected static function initExif()
168
  {
169 1
    if (extension_loaded('exif')) {
170 1 View Code Duplication
      if (ini_get('exif.encode_unicode') && 'UTF-8' !== strtoupper(ini_get('exif.encode_unicode'))) {
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...
171 1
        ini_set('exif.encode_unicode', 'UTF-8');
172 1
      }
173
174 1 View Code Duplication
      if (ini_get('exif.encode_jis') && 'UTF-8' !== strtoupper(ini_get('exif.encode_jis'))) {
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...
175
        ini_set('exif.encode_jis', 'UTF-8');
176
      }
177 1
    }
178 1
  }
179
180
  /**
181
   * init intl
182
   */
183 1
  protected static function initIntl()
184
  {
185 1
    if (defined('GRAPHEME_CLUSTER_RX')) {
186
      return;
187
    }
188
189 1
    define('GRAPHEME_CLUSTER_RX', PCRE_VERSION >= '8.32' ? '\X' : Intl::GRAPHEME_CLUSTER_RX);
190
191 1
    if (!extension_loaded('intl')) {
192
      extension_loaded('iconv') or self::initIconv();
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
193
      extension_loaded('mbstring') or self::initMbstring();
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
194
195
      require __DIR__ . '/bootup/intl.php';
196
    }
197 1
  }
198
199
  /**
200
   * init locale
201
   */
202 1
  protected static function initLocale()
203
  {
204
    // With non-UTF-8 locale, basename() bugs.
205
    // Be aware that setlocale() can be slow.
206
    // You'd better properly configure your LANG environment variable to an UTF-8 locale.
207
208 1
    if ('' === basename('§')) {
209
      setlocale(LC_ALL, 'C.UTF-8', 'C');
210
      setlocale(
211
          LC_CTYPE,
212
          'en_US.UTF-8',
213
          'fr_FR.UTF-8',
214
          'es_ES.UTF-8',
215
          'de_DE.UTF-8',
216
          'ru_RU.UTF-8',
217
          'pt_BR.UTF-8',
218
          'it_IT.UTF-8',
219
          'ja_JP.UTF-8',
220
          'zh_CN.UTF-8',
221
          '0'
222
      );
223
    }
224 1
  }
225
226
  /**
227
   * Get random bytes
228
   *
229
   * @ref https://github.com/paragonie/random_compat/
230
   *
231
   * @param  int $length Output length
232
   *
233
   * @return  string|false false on error
234
   */
235 1
  public static function get_random_bytes($length)
236
  {
237 1
    if (!$length || !ctype_digit((string)$length)) {
238 1
      return false;
239
    } else {
240 1
      $length = (int)$length;
241
    }
242
243 1
    if (function_exists('random_bytes') && self::is_php('7.0')) {
244
245
      /**
246
       * PHP 7 -> http://php.net/manual/de/function.random-bytes.php
247
       */
248
249
      try {
250
        $return = random_bytes($length);
251
      } catch (\Exception $e) {
252
        $return = false;
253
      }
254
255
      return $return;
256
257
    } else {
258
259
      /**
260
       * PHP 5.2.0 - 5.6.x way to implement random_bytes()
261
       *
262
       * // WARNING: Unfortunately, none of the following PRNGs is guaranteed to exist ...
263
       *
264
       * In order of preference:
265
       *   1. PHP-Module:   "mcrypt" via mcrypt_create_iv()
266
       *   2. Linux / BSD:  "/dev/urandom" via fread()
267
       *   3. Windows:      \COM('CAPICOM.Utilities.1')->GetRandom()
268
       *   4. PHP+OpenSSL:  openssl_random_pseudo_bytes()
269
       */
270
271
      /**
272
       * 1. PHP-Module
273
       */
274
275 1
      if (extension_loaded('mcrypt') && defined(MCRYPT_DEV_URANDOM) === true) {
276
        /** @noinspection PhpUsageOfSilenceOperatorInspection */
277
        $output = @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
278
279
        if ($output !== false) {
280
          return $output;
281
        }
282
      }
283
284
      /**
285
       * 2. Linux / BSD
286
       */
287
288 1
      if (!ini_get('open_basedir') && is_readable('/dev/urandom')) {
289
290 1
        $fp = fopen('/dev/urandom', 'rb');
291
292 1
        if (!empty($fp)) {
293 1
          $st = fstat($fp);
294
295
          // In C, this would be: (stat_mode & S_IFMT) !== S_IFCHR
296 1
          if (($st['mode'] & 0170000) !== 020000) {
297
            fclose($fp);
298
            $fp = false;
299
          }
300
301 1
          unset($st);
302 1
        }
303 1
      }
304
305 1
      if (isset($fp) && $fp !== false) {
306
307
        /**
308
         * stream_set_read_buffer() / stream_set_chunk_size does not exist in HHVM
309
         *
310
         * If we don't set the stream's read buffer to 0, PHP will
311
         * internally buffer 8192 bytes, which can waste entropy
312
         *
313
         * stream_set_read_buffer returns 0 on success
314
         */
315
316 1
        if (function_exists('stream_set_chunk_size')) {
317 1
          stream_set_chunk_size($fp, $length);
318 1
        }
319
320 1
        if (function_exists('stream_set_read_buffer')) {
321 1
          stream_set_read_buffer($fp, $length);
322 1
        }
323
324 1
        $remaining = $length;
325 1
        $buf = '';
326
327
        do {
328 1
          $read = fread($fp, $remaining);
329
330
          // We cannot safely read from the file, so exit the do-while loop.
331 1
          if ($read === false) {
332
            $buf = false;
333
            break;
334
          }
335
336
          // Decrease the number of bytes returned from remaining.
337 1
          $remaining -= UTF8::strlen($read, '8bit');
338 1
          $buf .= $read;
339
340 1
        } while ($remaining > 0);
341
342 1
        fclose($fp);
343
344 1
        if ($buf !== false) {
345 1
          if (UTF8::strlen($buf, '8bit') === $length) {
346 1
            return $buf;
347
          }
348
        }
349
350
      }
351
352
      /*
353
       * 3. Windows
354
       *
355
       * PHP can be used to access COM objects on Windows platforms
356
       *
357
       * ---
358
       *
359
       * PROBLEM: you see this error-message:
360
       *    com_exception thrown with message
361
       *      "Failed to create COM object `CAPICOM.Utilities.1': Ungültige Syntax
362
       *
363
       * SOLUTION: register the dll:
364
       *    regsvr32 c:\windows\capicom.dll
365
       *
366
       * ---
367
       *
368
       * @ref http://php.net/manual/en/ref.com.php
369
       */
370
      if (extension_loaded('com_dotnet') && class_exists('COM') === true) {
371
        // init
372
        $buf = '';
373
374
        /** @noinspection PhpUndefinedClassInspection */
375
        $util = new \COM('CAPICOM.Utilities.1');
0 ignored issues
show
Unused Code introduced by
The call to com::__construct() has too many arguments starting with 'CAPICOM.Utilities.1'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
376
377
        /**
378
         * Let's not let it loop forever. If we run N times and fail to
379
         * get N bytes of random data, then CAPICOM has failed us.
380
         */
381
        $execCount = 0;
382
383
        do {
384
385
          /** @noinspection PhpUndefinedMethodInspection */
386
          $buf .= base64_decode($util->GetRandom($length, 0));
387
          if (UTF8::strlen($buf, '8bit') >= $length) {
388
            return UTF8::substr($buf, 0, $length);
389
          }
390
391
          ++$execCount;
392
393
        } while ($execCount < $length);
394
      }
395
396
      /**
397
       * 4. PHP + OpenSSL
398
       *
399
       * fallback to "openssl_random_pseudo_bytes()"
400
       */
401
      if (function_exists('openssl_random_pseudo_bytes')) {
402
        $output = openssl_random_pseudo_bytes($length, $strong);
403
        if ($output !== false && $strong === true) {
404
          if (UTF8::strlen($output, '8bit') === $length) {
405
            return $output;
406
          }
407
        }
408
      }
409
410
      return false;
411
    }
412
  }
413
414
  /**
415
   * Determines if the current version of PHP is equal to or greater than the supplied value
416
   *
417
   * @param  string
418
   * @param string $version
419
   *
420
   * @return  bool  TRUE if the current version is $version or higher
421
   */
422 7
  public static function is_php($version)
423
  {
424 7
    static $_is_php;
425 7
    $version = (string)$version;
426 7
    if (!isset($_is_php[$version])) {
427 3
      $_is_php[$version] = version_compare(PHP_VERSION, $version, '>=');
428 3
    }
429
430 7
    return $_is_php[$version];
431
  }
432
433
  /**
434
   * filter request-uri
435
   *
436
   * @param null $uri
437
   * @param bool $exit
438
   *
439
   * @return bool|mixed|null
440
   */
441 2
  public static function filterRequestUri($uri = null, $exit = true)
0 ignored issues
show
Coding Style introduced by
filterRequestUri 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...
442
  {
443 2
    if (!isset($uri)) {
444 1
      if (!isset($_SERVER['REQUEST_URI'])) {
445 1
        return false;
446
      } else {
447
        $uri = $_SERVER['REQUEST_URI'];
448
      }
449
    }
450
451
    // Ensures the URL is well formed UTF-8
452
    // When not, assumes Windows-1252 and redirects to the corresponding UTF-8 encoded URL
453
454 1
    if (!preg_match('//u', urldecode($uri))) {
455 1
      $uri = preg_replace_callback(
456 1
          '/[\x80-\xFF]+/',
457
          function($m) {
458 1
            return urlencode($m[0]);
459 1
          },
460
          $uri
461 1
      );
462
463 1
      $uri = preg_replace_callback(
464 1
          '/(?:%[89A-F][0-9A-F])+/i',
465 1
          function($m) {
466 1
            return urlencode(UTF8::encode('UTF-8', urldecode($m[0])));
467 1
          },
468
          $uri
469 1
      );
470
471 1
      if ($exit === true) {
472
        // Use ob_start() to buffer content and avoid problem of headers already sent...
473
        if (headers_sent() === false) {
474
          $severProtocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1');
475
          header($severProtocol . ' 301 Moved Permanently');
476
          header('Location: ' . $uri);
477
          exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method filterRequestUri() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
478
        }
479
      }
480 1
    }
481
482 1
    return $uri;
483
  }
484
485
  /**
486
   * filter request inputs
487
   *
488
   * Ensures inputs are well formed UTF-8
489
   * When not, assumes Windows-1252 and converts to UTF-8
490
   * Tests only values, not keys
491
   *
492
   * @param int    $normalization_form
493
   * @param string $leading_combining
494
   */
495 1
  public static function filterRequestInputs($normalization_form = 4 /* n::NFC */, $leading_combining = '◌')
0 ignored issues
show
Coding Style introduced by
filterRequestInputs uses the super-global variable $_FILES 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...
Coding Style introduced by
filterRequestInputs uses the super-global variable $_ENV 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...
Coding Style introduced by
filterRequestInputs uses the super-global variable $_GET 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...
Coding Style introduced by
filterRequestInputs uses the super-global variable $_POST 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...
Coding Style introduced by
filterRequestInputs uses the super-global variable $_COOKIE 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...
Coding Style introduced by
filterRequestInputs 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...
Coding Style introduced by
filterRequestInputs uses the super-global variable $_REQUEST 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...
496
  {
497
    $a = array(
498 1
        &$_FILES,
499 1
        &$_ENV,
500 1
        &$_GET,
501 1
        &$_POST,
502 1
        &$_COOKIE,
503 1
        &$_SERVER,
504 1
        &$_REQUEST,
505 1
    );
506
507 1
    foreach ($a[0] as &$r) {
508 1
      $a[] = array(
509 1
          &$r['name'],
510 1
          &$r['type'],
511
      );
512 1
    }
513 1
    unset($r);
514 1
    unset($a[0]);
515
516 1
    $len = count($a) + 1;
517 1
    for ($i = 1; $i < $len; ++$i) {
518 1
      foreach ($a[$i] as &$r) {
519 1
        $s = $r; // $r is a ref, $s a copy
520 1
        if (is_array($s)) {
521 1
          $a[$len++] = & $r;
522 1
        } else {
523 1
          $r = self::filterString($s, $normalization_form, $leading_combining);
524
        }
525 1
      }
526 1
      unset($r);
527 1
      unset($a[$i]);
528 1
    }
529 1
  }
530
531
  /**
532
   * @param        $s
533
   * @param int    $normalization_form
534
   * @param string $leading_combining
535
   *
536
   * @return array|bool|mixed|string
537
   */
538 1
  public static function filterString($s, $normalization_form = 4 /* n::NFC */, $leading_combining = '◌')
539
  {
540 1 View Code Duplication
    if (false !== strpos($s, "\r")) {
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...
541
      // Workaround https://bugs.php.net/65732
542 1
      $s = str_replace(array("\r\n", "\r"), "\n", $s);
543 1
    }
544
545 1 View Code Duplication
    if (preg_match('/[\x80-\xFF]/', $s)) {
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...
546 1
      if (Normalizer::isNormalized($s, $normalization_form)) {
547 1
        $n = '-';
548 1
      } else {
549 1
        $n = Normalizer::normalize($s, $normalization_form);
550 1
        if (isset($n[0])) {
551 1
          $s = $n;
552 1
        } else {
553 1
          $s = UTF8::encode('UTF-8', $s);
554
        }
555
      }
556
557 1
      if ($s[0] >= "\x80" && isset($n[0], $leading_combining[0]) && preg_match('/^\p{Mn}/u', $s)) {
558
        // Prevent leading combining chars
559
        // for NFC-safe concatenations.
560 1
        $s = $leading_combining . $s;
561 1
      }
562 1
    }
563
564 1
    return $s;
565
  }
566
}
567