diff --git a/src/Generator/RandomBytesGenerator.php b/src/Generator/RandomBytesGenerator.php new file mode 100644 index 0000000..aafe4a8 --- /dev/null +++ b/src/Generator/RandomBytesGenerator.php @@ -0,0 +1,24 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://benramsey.com/projects/ramsey-uuid/ Documentation + * @link https://packagist.org/packages/ramsey/uuid Packagist + * @link https://github.com/ramsey/uuid GitHub + */ + +namespace Ramsey\Uuid\Generator; + +class RandomBytesGenerator implements RandomGeneratorInterface +{ + + public function generate($length) + { + return random_bytes($length); + } +} diff --git a/src/Generator/RandomGeneratorFactory.php b/src/Generator/RandomGeneratorFactory.php index 3dd3883..519ce14 100644 --- a/src/Generator/RandomGeneratorFactory.php +++ b/src/Generator/RandomGeneratorFactory.php @@ -24,6 +24,14 @@ class RandomGeneratorFactory */ public static $forceNoOpensslRandomPseudoBytes = false; + /** + * For testing, random_bytes() override; if true, treat as if random_bytes() + * is not available. + * + * @var bool + */ + public static $forceNoRandomBytes = false; + /** * Returns true if the system has openssl_random_pseudo_bytes() * @@ -34,8 +42,22 @@ class RandomGeneratorFactory return (function_exists('openssl_random_pseudo_bytes') && !self::$forceNoOpensslRandomPseudoBytes); } + /** + * Returns true if the system has random_bytes() + * + * @return bool + */ + protected static function hasRandomBytes() + { + return (function_exists('random_bytes') && !self::$forceNoRandomBytes); + } + public static function getGenerator() { + if (self::hasRandomBytes()) { + return new RandomBytesGenerator(); + } + if (self::hasOpensslRandomPseudoBytes()) { return new OpenSslGenerator(); } diff --git a/tests/Generator/RandomGeneratorFactoryTest.php b/tests/Generator/RandomGeneratorFactoryTest.php index 580974d..9a3ceb7 100644 --- a/tests/Generator/RandomGeneratorFactoryTest.php +++ b/tests/Generator/RandomGeneratorFactoryTest.php @@ -8,6 +8,7 @@ class RandomGeneratorFactoryTest extends TestCase { public function testFactoryReturnsNonOpenSslGeneratorWithForceNoOpenSsl() { + RandomGeneratorFactory::$forceNoRandomBytes = true; RandomGeneratorFactory::$forceNoOpensslRandomPseudoBytes = true; $generator = RandomGeneratorFactory::getGenerator();