1<?php
2
3declare(strict_types=1);
4
5namespace Sabre\DAV;
6
7/**
8 * UUID Utility.
9 *
10 * This class has static methods to generate and validate UUID's.
11 * UUIDs are used a decent amount within various *DAV standards, so it made
12 * sense to include it.
13 *
14 * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
15 * @author Evert Pot (http://evertpot.com/)
16 * @license http://sabre.io/license/ Modified BSD License
17 */
18class UUIDUtil
19{
20    /**
21     * Returns a pseudo-random v4 UUID.
22     *
23     * This function is based on a comment by Andrew Moore on php.net
24     *
25     * @see http://www.php.net/manual/en/function.uniqid.php#94959
26     *
27     * @return string
28     */
29    public static function getUUID()
30    {
31        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
32            // 32 bits for "time_low"
33            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
34
35            // 16 bits for "time_mid"
36            mt_rand(0, 0xffff),
37
38            // 16 bits for "time_hi_and_version",
39            // four most significant bits holds version number 4
40            mt_rand(0, 0x0fff) | 0x4000,
41
42            // 16 bits, 8 bits for "clk_seq_hi_res",
43            // 8 bits for "clk_seq_low",
44            // two most significant bits holds zero and one for variant DCE1.1
45            mt_rand(0, 0x3fff) | 0x8000,
46
47            // 48 bits for "node"
48            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
49        );
50    }
51
52    /**
53     * Checks if a string is a valid UUID.
54     *
55     * @param string $uuid
56     *
57     * @return bool
58     */
59    public static function validateUUID($uuid)
60    {
61        return 0 !== preg_match(
62            '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i',
63            $uuid
64        );
65    }
66}
67