Skip to content

Commit

Permalink
Add hex string generator based on random_bytes()
Browse files Browse the repository at this point in the history
  • Loading branch information
Trainmaster committed Oct 17, 2015
1 parent ce1cec6 commit ff0e695
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 73 deletions.
73 changes: 0 additions & 73 deletions src/Vision/Crypt/Random.php

This file was deleted.

30 changes: 30 additions & 0 deletions src/Vision/Random/String.php
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;
}
}
28 changes: 28 additions & 0 deletions tests/Random/StringTest.php
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);
}
}

0 comments on commit ff0e695

Please sign in to comment.