1
0
mirror of https://github.com/fzaninotto/Faker.git synced 2025-03-22 00:09:59 +01:00

Merge pull request #1 from foobugs/uuid-provider

Uuid provider
This commit is contained in:
Maik Penz 2013-02-05 10:00:44 -08:00
commit 1a2901a780
2 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,47 @@
<?php
namespace Faker\Provider;
class Uuid extends \Faker\Provider\Base
{
/**
* Generate name based md5 UUID (version 3).
* @example '7e57d004-2b97-0e7a-b45f-5387367791cd'
*/
public static function uuid()
{
$seed = mt_rand(0, PHP_INT_MAX);
// Hash the seed and convert to a byte array
$val = md5($seed, true);
$byte = array_values(unpack('C16', $val));
// extract fields from byte array
$tLo = ($byte[0] << 24) | ($byte[1] << 16) | ($byte[2] << 8) | $byte[3];
$tMi = ($byte[4] << 8) | $byte[5];
$tHi = ($byte[6] << 8) | $byte[7];
$csLo = $byte[9];
$csHi = $byte[8] & 0x3f | (1 << 7);
// if needed to make it big endian
if (pack('L', 0x6162797A) == pack('N', 0x6162797A)) {
$tLo = (($tLo & 0x000000ff) << 24) | (($tLo & 0x0000ff00) << 8)
| (($tLo & 0x00ff0000) >> 8) | (($tLo & 0xff000000) >> 24);
$tMi = (($tMi & 0x00ff) << 8) | (($tMi & 0xff00) >> 8);
$tHi = (($tHi & 0x00ff) << 8) | (($tHi & 0xff00) >> 8);
}
// apply version number
$tHi &= 0x0fff;
$tHi |= (3 << 12);
// cast to string
$uuid = sprintf(
'%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
$tLo, $tMi, $tHi, $csHi, $csLo,
$byte[10], $byte[11], $byte[12], $byte[13], $byte[14], $byte[15]
);
return $uuid;
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace Faker\Test\Provider;
use Faker\Provider\Uuid as BaseProvider;
class UuidTest extends \PHPUnit_Framework_TestCase
{
public function testUuidReturnsUuid()
{
$uuid = BaseProvider::uuid();
$this->assertTrue($this->isUuid($uuid));
}
public function testUuidExpectedSeed()
{
mt_srand(123);
$this->assertEquals("8eea2b29-832f-3633-985c-b2a257eabb5a", BaseProvider::uuid());
$this->assertEquals("9424cf48-58b3-3b7d-b89f-c049e9f5d31f", BaseProvider::uuid());
}
protected function isUuid($uuid)
{
return is_string($uuid) && (bool) preg_match('/^[a-f0-9]{8,8}-(?:[a-f0-9]{4,4}-){3,3}[a-f0-9]{12,12}$/i', $uuid);
}
}