Skip to content

Commit 129b64f

Browse files
author
SmetDenis
committed
generateUUID added
1 parent b744ec8 commit 129b64f

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,9 @@ Str::esc($string)
538538

539539
// Convert camel case to human readable format
540540
Str::splitCamelCase($input, $separator = '_', $toLower = true)
541+
542+
// Generates a universally unique identifier (UUID v4) according to RFC 4122
543+
Str::generateUUID()
541544
```
542545

543546

src/Str.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,4 +693,43 @@ public static function splitCamelCase($input, $separator = '_', $toLower = true)
693693

694694
return $output;
695695
}
696+
697+
/**
698+
* Generates a universally unique identifier (UUID v4) according to RFC 4122
699+
* Version 4 UUIDs are pseudo-random!
700+
*
701+
* Returns Version 4 UUID format: xxxxxxxx-xxxx-4xxx-Yxxx-xxxxxxxxxxxx where x is
702+
* any random hex digit and Y is a random choice from 8, 9, a, or b.
703+
*
704+
* @see http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid
705+
*
706+
* @return string
707+
*/
708+
public static function generateUUID()
709+
{
710+
return sprintf(
711+
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
712+
713+
// 32 bits for "time_low"
714+
mt_rand(0, 0xffff),
715+
mt_rand(0, 0xffff),
716+
717+
// 16 bits for "time_mid"
718+
mt_rand(0, 0xffff),
719+
720+
// 16 bits for "time_hi_and_version",
721+
// four most significant bits holds version number 4
722+
mt_rand(0, 0x0fff) | 0x4000,
723+
724+
// 16 bits, 8 bits for "clk_seq_hi_res",
725+
// 8 bits for "clk_seq_low",
726+
// two most significant bits holds zero and one for variant DCE1.1
727+
mt_rand(0, 0x3fff) | 0x8000,
728+
729+
// 48 bits for "node"
730+
mt_rand(0, 0xffff),
731+
mt_rand(0, 0xffff),
732+
mt_rand(0, 0xffff)
733+
);
734+
}
696735
}

tests/StringTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,4 +225,9 @@ public function testSplitCamelCase()
225225
isSame('word number', Str::splitCamelCase('wordNumber', ' '));
226226
isSame('word Number', Str::splitCamelCase('wordNumber', ' ', false));
227227
}
228+
229+
public function testGenerateUUID()
230+
{
231+
isNotSame(Str::generateUUID(), Str::generateUUID());
232+
}
228233
}

0 commit comments

Comments
 (0)