Debian Codegraph @

vendor/ramsey/uuid/src/Uuid.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;
16
17 use DateTime;
18 use Exception;
19 use InvalidArgumentException;
20 use Ramsey\Uuid\Converter\NumberConverterInterface;
21 use Ramsey\Uuid\Codec\CodecInterface;
22 use Ramsey\Uuid\Exception\InvalidUuidStringException;
23 use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
24 use Ramsey\Uuid\Exception\UnsupportedOperationException;
25
26 /**
27 * Represents a universally unique identifier (UUID), according to RFC 4122.
28 *
29 * This class provides immutable UUID objects (the Uuid class) and the static
30 * methods `uuid1()`, `uuid3()`, `uuid4()`, and `uuid5()` for generating version
31 * 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
32 *
33 * If all you want is a unique ID, you should probably call `uuid1()` or `uuid4()`.
34 * Note that `uuid1()` may compromise privacy since it creates a UUID containing
35 * the computer’s network address. `uuid4()` creates a random UUID.
36 *
37 * @link http://tools.ietf.org/html/rfc4122
38 * @link http://en.wikipedia.org/wiki/Universally_unique_identifier
39 * @link http://docs.python.org/3/library/uuid.html
40 * @link http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html
41 */
42 class Uuid implements UuidInterface
43 {
44 /**
45 * When this namespace is specified, the name string is a fully-qualified domain name.
46 * @link http://tools.ietf.org/html/rfc4122#appendix-C
47 */
48 const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
49
50 /**
51 * When this namespace is specified, the name string is a URL.
52 * @link http://tools.ietf.org/html/rfc4122#appendix-C
53 */
54 const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
55
56 /**
57 * When this namespace is specified, the name string is an ISO OID.
58 * @link http://tools.ietf.org/html/rfc4122#appendix-C
59 */
60 const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
61
62 /**
63 * When this namespace is specified, the name string is an X.500 DN in DER or a text output format.
64 * @link http://tools.ietf.org/html/rfc4122#appendix-C
65 */
66 const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8';
67
68 /**
69 * The nil UUID is special form of UUID that is specified to have all 128 bits set to zero.
70 * @link http://tools.ietf.org/html/rfc4122#section-4.1.7
71 */
72 const NIL = '00000000-0000-0000-0000-000000000000';
73
74 /**
75 * Reserved for NCS compatibility.
76 * @link http://tools.ietf.org/html/rfc4122#section-4.1.1
77 */
78 const RESERVED_NCS = 0;
79
80 /**
81 * Specifies the UUID layout given in RFC 4122.
82 * @link http://tools.ietf.org/html/rfc4122#section-4.1.1
83 */
84 const RFC_4122 = 2;
85
86 /**
87 * Reserved for Microsoft compatibility.
88 * @link http://tools.ietf.org/html/rfc4122#section-4.1.1
89 */
90 const RESERVED_MICROSOFT = 6;
91
92 /**
93 * Reserved for future definition.
94 * @link http://tools.ietf.org/html/rfc4122#section-4.1.1
95 */
96 const RESERVED_FUTURE = 7;
97
98 /**
99 * Regular expression pattern for matching a valid UUID of any variant.
100 */
101 const VALID_PATTERN = '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$';
102
103 /**
104 * Version 1 (time-based) UUID object constant identifier
105 */
106 const UUID_TYPE_TIME = 1;
107
108 /**
109 * Version 2 (identifier-based) UUID object constant identifier
110 */
111 const UUID_TYPE_IDENTIFIER = 2;
112
113 /**
114 * Version 3 (name-based and hashed with MD5) UUID object constant identifier
115 */
116 const UUID_TYPE_HASH_MD5 = 3;
117
118 /**
119 * Version 4 (random) UUID object constant identifier
120 */
121 const UUID_TYPE_RANDOM = 4;
122
123 /**
124 * Version 5 (name-based and hashed with SHA1) UUID object constant identifier
125 */
126 const UUID_TYPE_HASH_SHA1 = 5;
127
128 /**
129 * The factory to use when creating UUIDs.
130 * @var UuidFactoryInterface
131 */
132 private static $factory = null;
133
134 /**
135 * The codec to use when encoding or decoding UUID strings.
136 * @var CodecInterface
137 */
138 protected $codec;
139
140 /**
141 * The fields that make up this UUID.
142 *
143 * This is initialized to the nil value.
144 *
145 * @var array
146 * @see UuidInterface::getFieldsHex()
147 */
148 protected $fields = [
149 'time_low' => '00000000',
150 'time_mid' => '0000',
151 'time_hi_and_version' => '0000',
152 'clock_seq_hi_and_reserved' => '00',
153 'clock_seq_low' => '00',
154 'node' => '000000000000',
155 ];
156
157 /**
158 * The number converter to use for converting hex values to/from integers.
159 * @var NumberConverterInterface
160 */
161 protected $converter;
162
163 /**
164 * Creates a universally unique identifier (UUID) from an array of fields.
165 *
166 * Unless you're making advanced use of this library to generate identifiers
167 * that deviate from RFC 4122, you probably do not want to instantiate a
168 * UUID directly. Use the static methods, instead:
169 *
170 * ```
171 * use Ramsey\Uuid\Uuid;
172 *
173 * $timeBasedUuid = Uuid::uuid1();
174 * $namespaceMd5Uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'http://php.net/');
175 * $randomUuid = Uuid::uuid4();
176 * $namespaceSha1Uuid = Uuid::uuid5(Uuid::NAMESPACE_URL, 'http://php.net/');
177 * ```
178 *
179 * @param array $fields An array of fields from which to construct a UUID;
180 * see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
181 * @param NumberConverterInterface $converter The number converter to use
182 * for converting hex values to/from integers.
183 * @param CodecInterface $codec The codec to use when encoding or decoding
184 * UUID strings.
185 */
186 public function __construct(
187 array $fields,
188 NumberConverterInterface $converter,
189 CodecInterface $codec
190 ) {
191 $this->fields = $fields;
192 $this->codec = $codec;
193 $this->converter = $converter;
194 }
195
196 /**
197 * Converts this UUID object to a string when the object is used in any
198 * string context.
199 *
200 * @return string
201 * @link http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
202 */
203 public function __toString()
204 {
205 return $this->toString();
206 }
207
208 /**
209 * Converts this UUID object to a string when the object is serialized
210 * with `json_encode()`
211 *
212 * @return string
213 * @link http://php.net/manual/en/class.jsonserializable.php
214 */
215 public function jsonSerialize()
216 {
217 return $this->toString();
218 }
219
220 /**
221 * Converts this UUID object to a string when the object is serialized
222 * with `serialize()`
223 *
224 * @return string
225 * @link http://php.net/manual/en/class.serializable.php
226 */
227 public function serialize()
228 {
229 return $this->toString();
230 }
231
232 /**
233 * Re-constructs the object from its serialized form.
234 *
235 * @param string $serialized
236 * @link http://php.net/manual/en/class.serializable.php
237 * @throws InvalidUuidStringException
238 */
239 public function unserialize($serialized)
240 {
241 $uuid = self::fromString($serialized);
242 $this->codec = $uuid->codec;
243 $this->converter = $uuid->converter;
244 $this->fields = $uuid->fields;
245 }
246
247 public function compareTo(UuidInterface $other)
248 {
249 if ($this->getMostSignificantBitsHex() < $other->getMostSignificantBitsHex()) {
250 return -1;
251 }
252
253 if ($this->getMostSignificantBitsHex() > $other->getMostSignificantBitsHex()) {
254 return 1;
255 }
256
257 if ($this->getLeastSignificantBitsHex() < $other->getLeastSignificantBitsHex()) {
258 return -1;
259 }
260
261 if ($this->getLeastSignificantBitsHex() > $other->getLeastSignificantBitsHex()) {
262 return 1;
263 }
264
265 return 0;
266 }
267
268 public function equals($other)
269 {
270 if (!$other instanceof UuidInterface) {
271 return false;
272 }
273
274 return $this->compareTo($other) == 0;
275 }
276
277 public function getBytes()
278 {
279 return $this->codec->encodeBinary($this);
280 }
281
282 /**
283 * Returns the high field of the clock sequence multiplexed with the variant
284 * (bits 65-72 of the UUID).
285 *
286 * @return int Unsigned 8-bit integer value of clock_seq_hi_and_reserved
287 */
288 public function getClockSeqHiAndReserved()
289 {
290 return hexdec($this->getClockSeqHiAndReservedHex());
291 }
292
293 public function getClockSeqHiAndReservedHex()
294 {
295 return $this->fields['clock_seq_hi_and_reserved'];
296 }
297
298 /**
299 * Returns the low field of the clock sequence (bits 73-80 of the UUID).
300 *
301 * @return int Unsigned 8-bit integer value of clock_seq_low
302 */
303 public function getClockSeqLow()
304 {
305 return hexdec($this->getClockSeqLowHex());
306 }
307
308 public function getClockSeqLowHex()
309 {
310 return $this->fields['clock_seq_low'];
311 }
312
313 /**
314 * Returns the clock sequence value associated with this UUID.
315 *
316 * For UUID version 1, the clock sequence is used to help avoid
317 * duplicates that could arise when the clock is set backwards in time
318 * or if the node ID changes.
319 *
320 * For UUID version 3 or 5, the clock sequence is a 14-bit value
321 * constructed from a name as described in RFC 4122, Section 4.3.
322 *
323 * For UUID version 4, clock sequence is a randomly or pseudo-randomly
324 * generated 14-bit value as described in RFC 4122, Section 4.4.
325 *
326 * @return int Unsigned 14-bit integer value of clock sequence
327 * @link http://tools.ietf.org/html/rfc4122#section-4.1.5
328 */
329 public function getClockSequence()
330 {
331 return ($this->getClockSeqHiAndReserved() & 0x3f) << 8 | $this->getClockSeqLow();
332 }
333
334 public function getClockSequenceHex()
335 {
336 return sprintf('%04x', $this->getClockSequence());
337 }
338
339 public function getNumberConverter()
340 {
341 return $this->converter;
342 }
343
344 /**
345 * @inheritdoc
346 */
347 public function getDateTime()
348 {
349 if ($this->getVersion() != 1) {
350 throw new UnsupportedOperationException('Not a time-based UUID');
351 }
352
353 $unixTimeNanoseconds = $this->getTimestamp() - 0x01b21dd213814000;
354 $unixTime = ($unixTimeNanoseconds - $unixTimeNanoseconds % 1e7) / 1e7;
355
356 return new DateTime("@{$unixTime}");
357 }
358
359 /**
360 * Returns an array of the fields of this UUID, with keys named according
361 * to the RFC 4122 names for the fields.
362 *
363 * * **time_low**: The low field of the timestamp, an unsigned 32-bit integer
364 * * **time_mid**: The middle field of the timestamp, an unsigned 16-bit integer
365 * * **time_hi_and_version**: The high field of the timestamp multiplexed with
366 * the version number, an unsigned 16-bit integer
367 * * **clock_seq_hi_and_reserved**: The high field of the clock sequence
368 * multiplexed with the variant, an unsigned 8-bit integer
369 * * **clock_seq_low**: The low field of the clock sequence, an unsigned
370 * 8-bit integer
371 * * **node**: The spatially unique node identifier, an unsigned 48-bit
372 * integer
373 *
374 * @return array The UUID fields represented as integer values
375 * @link http://tools.ietf.org/html/rfc4122#section-4.1.2
376 */
377 public function getFields()
378 {
379 return [
380 'time_low' => $this->getTimeLow(),
381 'time_mid' => $this->getTimeMid(),
382 'time_hi_and_version' => $this->getTimeHiAndVersion(),
383 'clock_seq_hi_and_reserved' => $this->getClockSeqHiAndReserved(),
384 'clock_seq_low' => $this->getClockSeqLow(),
385 'node' => $this->getNode(),
386 ];
387 }
388
389 public function getFieldsHex()
390 {
391 return $this->fields;
392 }
393
394 public function getHex()
395 {
396 return str_replace('-', '', $this->toString());
397 }
398
399 /**
400 * @inheritdoc
401 */
402 public function getInteger()
403 {
404 return $this->converter->fromHex($this->getHex());
405 }
406
407 /**
408 * Returns the least significant 64 bits of this UUID's 128 bit value.
409 *
410 * @return mixed Converted representation of the unsigned 64-bit integer value
411 * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present
412 */
413 public function getLeastSignificantBits()
414 {
415 return $this->converter->fromHex($this->getLeastSignificantBitsHex());
416 }
417
418 public function getLeastSignificantBitsHex()
419 {
420 return sprintf(
421 '%02s%02s%012s',
422 $this->fields['clock_seq_hi_and_reserved'],
423 $this->fields['clock_seq_low'],
424 $this->fields['node']
425 );
426 }
427
428 /**
429 * Returns the most significant 64 bits of this UUID's 128 bit value.
430 *
431 * @return mixed Converted representation of the unsigned 64-bit integer value
432 * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present
433 */
434 public function getMostSignificantBits()
435 {
436 return $this->converter->fromHex($this->getMostSignificantBitsHex());
437 }
438
439 public function getMostSignificantBitsHex()
440 {
441 return sprintf(
442 '%08s%04s%04s',
443 $this->fields['time_low'],
444 $this->fields['time_mid'],
445 $this->fields['time_hi_and_version']
446 );
447 }
448
449 /**
450 * Returns the node value associated with this UUID
451 *
452 * For UUID version 1, the node field consists of an IEEE 802 MAC
453 * address, usually the host address. For systems with multiple IEEE
454 * 802 addresses, any available one can be used. The lowest addressed
455 * octet (octet number 10) contains the global/local bit and the
456 * unicast/multicast bit, and is the first octet of the address
457 * transmitted on an 802.3 LAN.
458 *
459 * For systems with no IEEE address, a randomly or pseudo-randomly
460 * generated value may be used; see RFC 4122, Section 4.5. The
461 * multicast bit must be set in such addresses, in order that they
462 * will never conflict with addresses obtained from network cards.
463 *
464 * For UUID version 3 or 5, the node field is a 48-bit value constructed
465 * from a name as described in RFC 4122, Section 4.3.
466 *
467 * For UUID version 4, the node field is a randomly or pseudo-randomly
468 * generated 48-bit value as described in RFC 4122, Section 4.4.
469 *
470 * @return int Unsigned 48-bit integer value of node
471 * @link http://tools.ietf.org/html/rfc4122#section-4.1.6
472 */
473 public function getNode()
474 {
475 return hexdec($this->getNodeHex());
476 }
477
478 public function getNodeHex()
479 {
480 return $this->fields['node'];
481 }
482
483 /**
484 * Returns the high field of the timestamp multiplexed with the version
485 * number (bits 49-64 of the UUID).
486 *
487 * @return int Unsigned 16-bit integer value of time_hi_and_version
488 */
489 public function getTimeHiAndVersion()
490 {
491 return hexdec($this->getTimeHiAndVersionHex());
492 }
493
494 public function getTimeHiAndVersionHex()
495 {
496 return $this->fields['time_hi_and_version'];
497 }
498
499 /**
500 * Returns the low field of the timestamp (the first 32 bits of the UUID).
501 *
502 * @return int Unsigned 32-bit integer value of time_low
503 */
504 public function getTimeLow()
505 {
506 return hexdec($this->getTimeLowHex());
507 }
508
509 public function getTimeLowHex()
510 {
511 return $this->fields['time_low'];
512 }
513
514 /**
515 * Returns the middle field of the timestamp (bits 33-48 of the UUID).
516 *
517 * @return int Unsigned 16-bit integer value of time_mid
518 */
519 public function getTimeMid()
520 {
521 return hexdec($this->getTimeMidHex());
522 }
523
524 public function getTimeMidHex()
525 {
526 return $this->fields['time_mid'];
527 }
528
529 /**
530 * Returns the timestamp value associated with this UUID.
531 *
532 * The 60 bit timestamp value is constructed from the time_low,
533 * time_mid, and time_hi fields of this UUID. The resulting
534 * timestamp is measured in 100-nanosecond units since midnight,
535 * October 15, 1582 UTC.
536 *
537 * The timestamp value is only meaningful in a time-based UUID, which
538 * has version type 1. If this UUID is not a time-based UUID then
539 * this method throws UnsupportedOperationException.
540 *
541 * @return int Unsigned 60-bit integer value of the timestamp
542 * @throws UnsupportedOperationException If this UUID is not a version 1 UUID
543 * @link http://tools.ietf.org/html/rfc4122#section-4.1.4
544 */
545 public function getTimestamp()
546 {
547 if ($this->getVersion() != 1) {
548 throw new UnsupportedOperationException('Not a time-based UUID');
549 }
550
551 return hexdec($this->getTimestampHex());
552 }
553
554 /**
555 * @inheritdoc
556 */
557 public function getTimestampHex()
558 {
559 if ($this->getVersion() != 1) {
560 throw new UnsupportedOperationException('Not a time-based UUID');
561 }
562
563 return sprintf(
564 '%03x%04s%08s',
565 ($this->getTimeHiAndVersion() & 0x0fff),
566 $this->fields['time_mid'],
567 $this->fields['time_low']
568 );
569 }
570
571 public function getUrn()
572 {
573 return 'urn:uuid:' . $this->toString();
574 }
575
576 public function getVariant()
577 {
578 $clockSeq = $this->getClockSeqHiAndReserved();
579
580 if (0 === ($clockSeq & 0x80)) {
581 return self::RESERVED_NCS;
582 }
583
584 if (0 === ($clockSeq & 0x40)) {
585 return self::RFC_4122;
586 }
587
588 if (0 === ($clockSeq & 0x20)) {
589 return self::RESERVED_MICROSOFT;
590 }
591
592 return self::RESERVED_FUTURE;
593 }
594
595 public function getVersion()
596 {
597 if ($this->getVariant() == self::RFC_4122) {
598 return (int) (($this->getTimeHiAndVersion() >> 12) & 0x0f);
599 }
600
601 return null;
602 }
603
604 public function toString()
605 {
606 return $this->codec->encode($this);
607 }
608
609 /**
610 * Returns the currently set factory used to create UUIDs.
611 *
612 * @return UuidFactoryInterface
613 */
614 public static function getFactory()
615 {
616 if (!self::$factory) {
617 self::$factory = new UuidFactory();
618 }
619
620 return self::$factory;
621 }
622
623 /**
624 * Sets the factory used to create UUIDs.
625 *
626 * @param UuidFactoryInterface $factory
627 */
628 public static function setFactory(UuidFactoryInterface $factory)
629 {
630 self::$factory = $factory;
631 }
632
633 /**
634 * Creates a UUID from a byte string.
635 *
636 * @param string $bytes
637 * @return UuidInterface
638 * @throws InvalidUuidStringException
639 * @throws InvalidArgumentException
640 */
641 public static function fromBytes($bytes)
642 {
643 return self::getFactory()->fromBytes($bytes);
644 }
645
646 /**
647 * Creates a UUID from the string standard representation.
648 *
649 * @param string $name A string that specifies a UUID
650 * @return UuidInterface
651 * @throws InvalidUuidStringException
652 */
653 public static function fromString($name)
654 {
655 return self::getFactory()->fromString($name);
656 }
657
658 /**
659 * Creates a UUID from a 128-bit integer string.
660 *
661 * @param string $integer String representation of 128-bit integer
662 * @return UuidInterface
663 * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present
664 * @throws InvalidUuidStringException
665 */
666 public static function fromInteger($integer)
667 {
668 return self::getFactory()->fromInteger($integer);
669 }
670
671 /**
672 * Check if a string is a valid UUID.
673 *
674 * @param string $uuid The string UUID to test
675 * @return boolean
676 */
677 public static function isValid($uuid)
678 {
679 $uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid);
680
681 if ($uuid == self::NIL) {
682 return true;
683 }
684
685 if (!preg_match('/' . self::VALID_PATTERN . '/D', $uuid)) {
686 return false;
687 }
688
689 return true;
690 }
691
692 /**
693 * Generate a version 1 UUID from a host ID, sequence number, and the current time.
694 *
695 * @param int|string $node A 48-bit number representing the hardware address
696 * This number may be represented as an integer or a hexadecimal string.
697 * @param int $clockSeq A 14-bit number used to help avoid duplicates that
698 * could arise when the clock is set backwards in time or if the node ID
699 * changes.
700 * @return UuidInterface
701 * @throws UnsatisfiedDependencyException if called on a 32-bit system and
702 * `Moontoast\Math\BigNumber` is not present
703 * @throws InvalidArgumentException
704 * @throws Exception if it was not possible to gather sufficient entropy
705 */
706 public static function uuid1($node = null, $clockSeq = null)
707 {
708 return self::getFactory()->uuid1($node, $clockSeq);
709 }
710
711 /**
712 * Generate a version 3 UUID based on the MD5 hash of a namespace identifier
713 * (which is a UUID) and a name (which is a string).
714 *
715 * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID
716 * @param string $name The name to create a UUID for
717 * @return UuidInterface
718 * @throws InvalidUuidStringException
719 */
720 public static function uuid3($ns, $name)
721 {
722 return self::getFactory()->uuid3($ns, $name);
723 }
724
725 /**
726 * Generate a version 4 (random) UUID.
727 *
728 * @return UuidInterface
729 * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present
730 * @throws InvalidArgumentException
731 * @throws Exception
732 */
733 public static function uuid4()
734 {
735 return self::getFactory()->uuid4();
736 }
737
738 /**
739 * Generate a version 5 UUID based on the SHA-1 hash of a namespace
740 * identifier (which is a UUID) and a name (which is a string).
741 *
742 * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID
743 * @param string $name The name to create a UUID for
744 * @return UuidInterface
745 * @throws InvalidUuidStringException
746 */
747 public static function uuid5($ns, $name)
748 {
749 return self::getFactory()->uuid5($ns, $name);
750 }
751 }