Conditions | 11 |
Paths | 66 |
Total Lines | 64 |
Code Lines | 40 |
Lines | 0 |
Ratio | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 1 |
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 |
||
68 | static public function SecureInt($min, $max, $pedantic = true) |
||
69 | { |
||
70 | |||
71 | //Ensure order correctness |
||
72 | if ($min > $max) { |
||
73 | $temp = $max; |
||
74 | $max = $min; |
||
75 | $min = $temp; |
||
76 | } |
||
77 | $rand = null; |
||
78 | $manual = true; |
||
79 | if (phpversion() >= 7) { |
||
80 | try { |
||
81 | $rand = random_int($min, $max); |
||
82 | $manual = false; |
||
83 | } catch (\Exception $e) { |
||
84 | $manual = true; |
||
85 | } |
||
86 | } |
||
87 | |||
88 | if ($manual === true) { |
||
89 | //http://stackoverflow.com/questions/1313223/replace-rand-with-openssl-random-pseudo-bytes |
||
90 | $secure = false; |
||
91 | $diff = $max - $min; |
||
92 | if ($diff <= 0) { |
||
93 | return $min; |
||
94 | } // not so random... |
||
95 | $range = $diff + 1; // because $max is inclusive |
||
96 | $bits = ceil(log(($range), 2)); |
||
97 | $bytes = ceil($bits / 8.0); |
||
98 | $bits_max = 1 << $bits; |
||
99 | // e.g. if $range = 3000 (bin: 101110111000) |
||
100 | // +--------+--------+ |
||
101 | // |....1011|10111000| |
||
102 | // +--------+--------+ |
||
103 | // bits=12, bytes=2, bits_max=2^12=4096 |
||
104 | $num = 0; |
||
105 | do { |
||
106 | $num = hexdec( |
||
107 | bin2hex(openssl_random_pseudo_bytes($bytes, $secure)) |
||
108 | ) % $bits_max; |
||
109 | if ($secure === false) { |
||
110 | throw new TwLibException( |
||
111 | 'Non secure value generated. This is a system issue' |
||
112 | ); |
||
113 | } |
||
114 | if ($num >= $range) { |
||
115 | if ($pedantic) { |
||
116 | continue; |
||
117 | } // start over instead of accepting bias |
||
118 | // else |
||
119 | $num = $num % $range; // to hell with security |
||
120 | } |
||
121 | break; |
||
122 | } while (true); |
||
123 | $rand = $num + $min; |
||
124 | } |
||
125 | if ($rand === null) { |
||
126 | //We must not be NULL here, we could be 0, but if we are NULL then something went wrong with generation |
||
127 | throw new TwLibException('Rand could not be generated'); |
||
128 | } |
||
129 | |||
130 | return $rand; |
||
131 | } |
||
132 | |||
164 | } |