Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

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