Merge pull request #67 from ramsey/php7-random-bytes-generator

Add RandomBytesGenerator for use with PHP 7
This commit is contained in:
Ben Ramsey
2015-07-24 09:39:10 -05:00
4 changed files with 53 additions and 2 deletions
+6 -2
View File
@@ -7,8 +7,12 @@ php:
- 7.0
- hhvm
before_install:
- sudo apt-get update && sudo apt-get install uuid-dev
sudo: false
addons:
apt:
packages:
- uuid-dev
before_script:
- travis_retry composer self-update
+24
View File
@@ -0,0 +1,24 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @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);
}
}
+22
View File
@@ -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();
}
@@ -8,6 +8,7 @@ class RandomGeneratorFactoryTest extends TestCase
{
public function testFactoryReturnsNonOpenSslGeneratorWithForceNoOpenSsl()
{
RandomGeneratorFactory::$forceNoRandomBytes = true;
RandomGeneratorFactory::$forceNoOpensslRandomPseudoBytes = true;
$generator = RandomGeneratorFactory::getGenerator();