Debian Codegraph @

vendor/ramsey/uuid/src/Provider/Node/RandomNodeProvider.php

raw
1 <?php
2 /**
3 * This file is part of the ramsey/uuid library
4 *
5 * For the full copyright and license information, please view the LICENSE
6 * file that was distributed with this source code.
7 *
8 * @copyright Copyright (c) Ben Ramsey <[email protected]>
9 * @license http://opensource.org/licenses/MIT MIT
10 * @link https://benramsey.com/projects/ramsey-uuid/ Documentation
11 * @link https://packagist.org/packages/ramsey/uuid Packagist
12 * @link https://github.com/ramsey/uuid GitHub
13 */
14
15 namespace Ramsey\Uuid\Provider\Node;
16
17 use Exception;
18 use Ramsey\Uuid\Provider\NodeProviderInterface;
19
20 /**
21 * RandomNodeProvider provides functionality to generate a random node ID, in
22 * the event that the node ID could not be obtained from the host system
23 *
24 * @link http://tools.ietf.org/html/rfc4122#section-4.5
25 */
26 class RandomNodeProvider implements NodeProviderInterface
27 {
28 /**
29 * Returns the system node ID
30 *
31 * @return string System node ID as a hexadecimal string
32 * @throws Exception if it was not possible to gather sufficient entropy
33 */
34 public function getNode()
35 {
36 $nodeBytes = random_bytes(6);
37
38 // Split the node bytes for math on 32-bit systems.
39 $nodeMsb = substr($nodeBytes, 0, 3);
40 $nodeLsb = substr($nodeBytes, 3);
41
42 // Set the multicast bit; see RFC 4122, section 4.5.
43 $nodeMsb = hex2bin(
44 str_pad(
45 dechex(hexdec(bin2hex($nodeMsb)) | 0x010000),
46 6,
47 '0',
48 STR_PAD_LEFT
49 )
50 );
51
52 // Recombine the node bytes.
53 $node = $nodeMsb . $nodeLsb;
54
55 return str_pad(bin2hex($node), 12, '0', STR_PAD_LEFT);
56 }
57 }