| 1 | <?php |
| 2 | |
| 3 | /* |
| 4 | * This file is part of the Symfony package. |
| 5 | * |
| 6 | * (c) Fabien Potencier <[email protected]> |
| 7 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | */ |
| 11 | |
| 12 | namespace Symfony\Component\Uid; |
| 13 | |
| 14 | /** |
| 15 | * A v4 UUID contains a 122-bit random number. |
| 16 | * |
| 17 | * @author Grégoire Pineau <[email protected]> |
| 18 | */ |
| 19 | class UuidV4 extends Uuid |
| 20 | { |
| 21 | protected const TYPE = 4; |
| 22 | |
| 23 | public function __construct(?string $uuid = null) |
| 24 | { |
| 25 | if (null === $uuid) { |
| 26 | // Generate 36 random hex characters (144 bits) |
| 27 | // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 28 | $uuid = bin2hex(random_bytes(18)); |
| 29 | // Insert dashes to match the UUID format |
| 30 | // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 31 | $uuid[8] = $uuid[13] = $uuid[18] = $uuid[23] = '-'; |
| 32 | // Set the UUID version to 4 |
| 33 | // xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx |
| 34 | $uuid[14] = '4'; |
| 35 | // Set the UUID variant: the 19th char must be in [8, 9, a, b] |
| 36 | // xxxxxxxx-xxxx-4xxx-?xxx-xxxxxxxxxxxx |
| 37 | $uuid[19] = ['8', '9', 'a', 'b', '8', '9', 'a', 'b', 'c' => '8', 'd' => '9', 'e' => 'a', 'f' => 'b'][$uuid[19]] ?? $uuid[19]; |
| 38 | $this->uid = $uuid; |
| 39 | } else { |
| 40 | parent::__construct($uuid, true); |
| 41 | } |
| 42 | } |
| 43 | } |