Conditions | 10 |
Paths | 12 |
Total Lines | 54 |
Code Lines | 30 |
Lines | 0 |
Ratio | 0 % |
Tests | 14 |
CRAP Score | 22.5 |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
1 | <?php |
||
2607 | 1 | public static function get_random_string( |
|
2608 | int $length, |
||
2609 | string $possible_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', |
||
2610 | string $encoding = 'UTF-8' |
||
2611 | ): string { |
||
2612 | // init |
||
2613 | 1 | $i = 0; |
|
2614 | 1 | $str = ''; |
|
2615 | |||
2616 | // |
||
2617 | // add random chars |
||
2618 | // |
||
2619 | |||
2620 | 1 | if ($encoding === 'UTF-8') { |
|
2621 | 1 | $max_length = (int) \mb_strlen($possible_chars); |
|
2622 | 1 | if ($max_length === 0) { |
|
2623 | 1 | return ''; |
|
2624 | } |
||
2625 | |||
2626 | 1 | while ($i < $length) { |
|
2627 | try { |
||
2628 | 1 | $rand_int = \random_int(0, $max_length - 1); |
|
2629 | } catch (\Exception $e) { |
||
2630 | $rand_int = \mt_rand(0, $max_length - 1); |
||
2631 | } |
||
2632 | 1 | $char = \mb_substr($possible_chars, $rand_int, 1); |
|
2633 | 1 | if ($char !== false) { |
|
2634 | 1 | $str .= $char; |
|
2635 | 1 | ++$i; |
|
2636 | } |
||
2637 | } |
||
2638 | } else { |
||
2639 | $encoding = self::normalize_encoding($encoding, 'UTF-8'); |
||
2640 | |||
2641 | $max_length = (int) self::strlen($possible_chars, $encoding); |
||
2642 | if ($max_length === 0) { |
||
2643 | return ''; |
||
2644 | } |
||
2645 | |||
2646 | while ($i < $length) { |
||
2647 | try { |
||
2648 | $rand_int = \random_int(0, $max_length - 1); |
||
2649 | } catch (\Exception $e) { |
||
2650 | $rand_int = \mt_rand(0, $max_length - 1); |
||
2651 | } |
||
2652 | $char = self::substr($possible_chars, $rand_int, 1, $encoding); |
||
2653 | if ($char !== false) { |
||
2654 | $str .= $char; |
||
2655 | ++$i; |
||
2656 | } |
||
2657 | } |
||
2658 | } |
||
2659 | |||
2660 | 1 | return $str; |
|
2661 | } |
||
13694 |