| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* This file is part of the ramsey/uuid library |
| 5 |
* |
| 6 |
* For the full copyright and license information, please view the LICENSE |
| 7 |
* file that was distributed with this source code. |
| 8 |
* |
| 9 |
* @copyright Copyright (c) Ben Ramsey <[email protected]> |
| 10 |
* @license http://opensource.org/licenses/MIT MIT |
| 11 |
*/ |
| 12 |
declare (strict_types=1); |
| 13 |
namespace Dudlewebs\WPMCS\Ramsey\Uuid\Rfc4122; |
| 14 |
|
| 15 |
use Dudlewebs\WPMCS\Ramsey\Uuid\Exception\InvalidBytesException; |
| 16 |
use Dudlewebs\WPMCS\Ramsey\Uuid\Uuid; |
| 17 |
use function decbin; |
| 18 |
use function str_pad; |
| 19 |
use function strlen; |
| 20 |
use function strpos; |
| 21 |
use function substr; |
| 22 |
use function unpack; |
| 23 |
use const STR_PAD_LEFT; |
| 24 |
/** |
| 25 |
* Provides common functionality for handling the variant, as defined by RFC 4122 |
| 26 |
* |
| 27 |
* @psalm-immutable |
| 28 |
*/ |
| 29 |
trait VariantTrait |
| 30 |
{ |
| 31 |
/** |
| 32 |
* Returns the bytes that comprise the fields |
| 33 |
*/ |
| 34 |
abstract public function getBytes(): string; |
| 35 |
/** |
| 36 |
* Returns the variant identifier, according to RFC 4122, for the given bytes |
| 37 |
* |
| 38 |
* The following values may be returned: |
| 39 |
* |
| 40 |
* - `0` -- Reserved, NCS backward compatibility. |
| 41 |
* - `2` -- The variant specified in RFC 4122. |
| 42 |
* - `6` -- Reserved, Microsoft Corporation backward compatibility. |
| 43 |
* - `7` -- Reserved for future definition. |
| 44 |
* |
| 45 |
* @link https://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, ยง 4.1.1: Variant |
| 46 |
* |
| 47 |
* @return int The variant identifier, according to RFC 4122 |
| 48 |
*/ |
| 49 |
public function getVariant(): int |
| 50 |
{ |
| 51 |
if (strlen($this->getBytes()) !== 16) { |
| 52 |
throw new InvalidBytesException('Invalid number of bytes'); |
| 53 |
} |
| 54 |
/** @var array $parts */ |
| 55 |
$parts = unpack('n*', $this->getBytes()); |
| 56 |
// $parts[5] is a 16-bit, unsigned integer containing the variant bits |
| 57 |
// of the UUID. We convert this integer into a string containing a |
| 58 |
// binary representation, padded to 16 characters. We analyze the first |
| 59 |
// three characters (three most-significant bits) to determine the |
| 60 |
// variant. |
| 61 |
$binary = str_pad(decbin((int) $parts[5]), 16, '0', STR_PAD_LEFT); |
| 62 |
$msb = substr($binary, 0, 3); |
| 63 |
if ($msb === '111') { |
| 64 |
$variant = Uuid::RESERVED_FUTURE; |
| 65 |
} elseif ($msb === '110') { |
| 66 |
$variant = Uuid::RESERVED_MICROSOFT; |
| 67 |
} elseif (strpos($msb, '10') === 0) { |
| 68 |
$variant = Uuid::RFC_4122; |
| 69 |
} else { |
| 70 |
$variant = Uuid::RESERVED_NCS; |
| 71 |
} |
| 72 |
return $variant; |
| 73 |
} |
| 74 |
} |
| 75 |
|