lithium\util\String::_source()
Initializes String::$_source
using the best available random number generator.
When available, /dev/urandom
and COM gets used on *nix and
Windows systems,
respectively.
If all else fails, a Mersenne Twister gets used. (Strictly speaking, this fallback is inadequate, but good enough.)
Note: Users restricting path access through the open_basedir
INI setting,
will need to include /dev/urandom
into the list of allowed paths, as this
method might read from /dev/urandom
.
Returns
\ClosureReturns a closure containing a random number generator.
Source
protected static function _source() {
switch (true) {
case isset(static::$_source):
return static::$_source;
case is_readable('/dev/urandom') && $fp = fopen('/dev/urandom', 'rb'):
return static::$_source = function($bytes) use (&$fp) {
return fread($fp, $bytes);
};
case class_exists('COM', false):
try {
$com = new COM('CAPICOM.Utilities.1');
return static::$_source = function($bytes) use ($com) {
return base64_decode($com->GetRandom($bytes, 0));
};
} catch (Exception $e) {
}
default:
return static::$_source = function($bytes) {
$rand = '';
for ($i = 0; $i < $bytes; $i++) {
$rand .= chr(mt_rand(0, 255));
}
return $rand;
};
}
}