1: <?php
2:
3: /**
4: * Copyright 2015, Eduardo Trujillo
5: *
6: * For the full copyright and license information, please view the LICENSE
7: * file that was distributed with this source code.
8: *
9: * This file is part of the Nucleus package
10: */
11:
12: namespace Chromabits\Nucleus\Strings;
13:
14: use Chromabits\Nucleus\Foundation\BaseObject;
15:
16: /**
17: * Class Uuid.
18: *
19: * @author Eduardo Trujillo <ed@chromabits.com>
20: * @package Chromabits\Nucleus\Strings
21: */
22: class Uuid extends BaseObject
23: {
24: /**
25: * Generates a v4 UUID from data.
26: *
27: * @param string $data
28: *
29: * @return string
30: */
31: public static function v4FromData($data)
32: {
33: assert(strlen($data) == 16);
34:
35: $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
36: $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
37:
38: return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
39: }
40:
41: /**
42: * Generates a random v4 UUID.
43: *
44: * @return string
45: */
46: public static function v4()
47: {
48: return static::v4FromData(openssl_random_pseudo_bytes(16));
49: }
50:
51: /**
52: * Check if the input string is a valid v4 UUID.
53: *
54: * @param string $input
55: *
56: * @return bool
57: */
58: public static function validV4($input)
59: {
60: return preg_match(
61: '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]'
62: . '{3}-[0-9a-f]{12}$/',
63: $input
64: ) === 1;
65: }
66: }
67: