Debian Codegraph @

vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php

raw
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
13 declare(strict_types=1);
14
15 namespace Ramsey\Uuid\Converter\Time;
16
17 use Ramsey\Uuid\Converter\TimeConverterInterface;
18 use Ramsey\Uuid\Math\BrickMathCalculator;
19 use Ramsey\Uuid\Math\CalculatorInterface;
20 use Ramsey\Uuid\Type\Hexadecimal;
21 use Ramsey\Uuid\Type\Integer as IntegerObject;
22 use Ramsey\Uuid\Type\Time;
23
24 use function count;
25 use function dechex;
26 use function explode;
27 use function is_float;
28 use function is_int;
29 use function str_pad;
30 use function strlen;
31 use function substr;
32
33 use const STR_PAD_LEFT;
34 use const STR_PAD_RIGHT;
35
36 /**
37 * PhpTimeConverter uses built-in PHP functions and standard math operations available to the PHP programming language
38 * to provide facilities for converting parts of time into representations that may be used in UUIDs
39 *
40 * @immutable
41 */
42 class PhpTimeConverter implements TimeConverterInterface
43 {
44 /**
45 * The number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix epoch.
46 */
47 private const GREGORIAN_TO_UNIX_INTERVALS = 0x01b21dd213814000;
48
49 /**
50 * The number of 100-nanosecond intervals in one second.
51 */
52 private const SECOND_INTERVALS = 10_000_000;
53
54 /**
55 * The number of 100-nanosecond intervals in one microsecond.
56 */
57 private const MICROSECOND_INTERVALS = 10;
58
59 private int $phpPrecision;
60 private CalculatorInterface $calculator;
61 private TimeConverterInterface $fallbackConverter;
62
63 public function __construct(
64 ?CalculatorInterface $calculator = null,
65 ?TimeConverterInterface $fallbackConverter = null,
66 ) {
67 if ($calculator === null) {
68 $calculator = new BrickMathCalculator();
69 }
70
71 if ($fallbackConverter === null) {
72 $fallbackConverter = new GenericTimeConverter($calculator);
73 }
74
75 $this->calculator = $calculator;
76 $this->fallbackConverter = $fallbackConverter;
77 $this->phpPrecision = (int) ini_get('precision');
78 }
79
80 public function calculateTime(string $seconds, string $microseconds): Hexadecimal
81 {
82 $seconds = new IntegerObject($seconds); /** @phpstan-ignore possiblyImpure.new */
83 $microseconds = new IntegerObject($microseconds); /** @phpstan-ignore possiblyImpure.new */
84
85 // Calculate the count of 100-nanosecond intervals since the Gregorian calendar epoch
86 // for the given seconds and microseconds.
87 $uuidTime = ((int) $seconds->toString() * self::SECOND_INTERVALS)
88 + ((int) $microseconds->toString() * self::MICROSECOND_INTERVALS)
89 + self::GREGORIAN_TO_UNIX_INTERVALS;
90
91 // Check to see whether we've overflowed the max/min integer size.
92 // If so, we will default to a different time converter.
93 // @phpstan-ignore function.alreadyNarrowedType (the integer value might have overflowed)
94 if (!is_int($uuidTime)) {
95 return $this->fallbackConverter->calculateTime(
96 $seconds->toString(),
97 $microseconds->toString(),
98 );
99 }
100
101 /** @phpstan-ignore possiblyImpure.new */
102 return new Hexadecimal(
103 str_pad(dechex($uuidTime), 16, '0', STR_PAD_LEFT)
104 );
105 }
106
107 public function convertTime(Hexadecimal $uuidTimestamp): Time
108 {
109 $timestamp = $this->calculator->toInteger($uuidTimestamp);
110
111 // Convert the 100-nanosecond intervals into seconds and microseconds.
112 $splitTime = $this->splitTime(
113 ($timestamp->toString() - self::GREGORIAN_TO_UNIX_INTERVALS) / self::SECOND_INTERVALS,
114 );
115
116 if (count($splitTime) === 0) {
117 return $this->fallbackConverter->convertTime($uuidTimestamp);
118 }
119
120 /** @phpstan-ignore possiblyImpure.new */
121 return new Time($splitTime['sec'], $splitTime['usec']);
122 }
123
124 /**
125 * @param float | int $time The time to split into seconds and microseconds
126 *
127 * @return string[]
128 *
129 * @pure
130 */
131 private function splitTime(float | int $time): array
132 {
133 $split = explode('.', (string) $time, 2);
134
135 // If the $time value is a float but $split only has 1 element, then the float math was rounded up to the next
136 // second, so we want to return an empty array to allow use of the fallback converter.
137 if (is_float($time) && count($split) === 1) {
138 return [];
139 }
140
141 if (count($split) === 1) {
142 return ['sec' => $split[0], 'usec' => '0'];
143 }
144
145 // If the microseconds are less than six characters AND the length of the number is greater than or equal to the
146 // PHP precision, then it's possible that we lost some precision for the microseconds. Return an empty array so
147 // that we can choose to use the fallback converter.
148 if (strlen($split[1]) < 6 && strlen((string) $time) >= $this->phpPrecision) {
149 return [];
150 }
151
152 $microseconds = $split[1];
153
154 // Ensure the microseconds are no longer than 6 digits. If they are,
155 // truncate the number to the first 6 digits and round up, if needed.
156 if (strlen($microseconds) > 6) {
157 $roundingDigit = (int) substr($microseconds, 6, 1);
158 $microseconds = (int) substr($microseconds, 0, 6);
159
160 if ($roundingDigit >= 5) {
161 $microseconds++;
162 }
163 }
164
165 return [
166 'sec' => $split[0],
167 'usec' => str_pad((string) $microseconds, 6, '0', STR_PAD_RIGHT),
168 ];
169 }
170 }