-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add hex string generator based on random_bytes()
- Loading branch information
1 parent
ce1cec6
commit ff0e695
Showing
3 changed files
with
58 additions
and
73 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
<?php | ||
/** | ||
* Vision PHP-Framework | ||
* | ||
* @author Frank Liepert <[email protected]> | ||
* @copyright 2012-2015 Frank Liepert | ||
* @license http://www.opensource.org/licenses/mit-license.php MIT | ||
*/ | ||
namespace Vision\Random; | ||
|
||
class String | ||
{ | ||
/** | ||
* @param int $length | ||
* | ||
* @return bool|string | ||
*/ | ||
public function generateHex($length) | ||
{ | ||
$length = (int) $length; | ||
|
||
if ($length < 2 || (($length % 2) === 1)) { | ||
return false; | ||
} | ||
|
||
$bytes = random_bytes($length / 2); | ||
|
||
return $bytes ? bin2hex($bytes) : false; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
<?php | ||
namespace VisionTest\Random; | ||
|
||
use Vision\Random\String; | ||
|
||
class StringTest extends \PHPUnit_Framework_TestCase | ||
{ | ||
public function testGenerateHex() | ||
{ | ||
$string = new String(); | ||
|
||
$hex = $string->generateHex(10); | ||
$this->assertInternalType('string', $hex); | ||
$this->assertSame(10, strlen($hex)); | ||
$this->assertTrue(ctype_xdigit($hex)); | ||
} | ||
|
||
public function testGenerateHexWithInvalidLength() | ||
{ | ||
$string = new String(); | ||
|
||
$hex = $string->generateHex(3); | ||
$this->assertFalse($hex); | ||
|
||
$hex = $string->generateHex(1); | ||
$this->assertFalse($hex); | ||
} | ||
} |