Debian Codegraph @

vendor/ramsey/uuid/src/Converter/Time/UnixTimeConverter.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\CalculatorInterface;
19 use Ramsey\Uuid\Math\RoundingMode;
20 use Ramsey\Uuid\Type\Hexadecimal;
21 use Ramsey\Uuid\Type\Integer as IntegerObject;
22 use Ramsey\Uuid\Type\Time;
23
24 use function explode;
25 use function str_pad;
26
27 use const STR_PAD_LEFT;
28
29 /**
30 * UnixTimeConverter converts Unix Epoch timestamps to/from hexadecimal values consisting of milliseconds elapsed since
31 * the Unix Epoch
32 *
33 * @immutable
34 */
35 class UnixTimeConverter implements TimeConverterInterface
36 {
37 private const MILLISECONDS = 1000;
38
39 public function __construct(private CalculatorInterface $calculator)
40 {
41 }
42
43 public function calculateTime(string $seconds, string $microseconds): Hexadecimal
44 {
45 /** @phpstan-ignore possiblyImpure.new */
46 $timestamp = new Time($seconds, $microseconds);
47
48 // Convert the seconds into milliseconds.
49 $sec = $this->calculator->multiply(
50 $timestamp->getSeconds(),
51 new IntegerObject(self::MILLISECONDS) /** @phpstan-ignore possiblyImpure.new */
52 );
53
54 // Convert the microseconds into milliseconds; the scale is zero because we need to discard the fractional part.
55 $usec = $this->calculator->divide(
56 RoundingMode::DOWN, // Always round down to stay in the previous millisecond.
57 0,
58 $timestamp->getMicroseconds(),
59 new IntegerObject(self::MILLISECONDS), /** @phpstan-ignore possiblyImpure.new */
60 );
61
62 /** @var IntegerObject $unixTime */
63 $unixTime = $this->calculator->add($sec, $usec);
64
65 /** @phpstan-ignore possiblyImpure.new */
66 return new Hexadecimal(
67 str_pad(
68 $this->calculator->toHexadecimal($unixTime)->toString(),
69 12,
70 '0',
71 STR_PAD_LEFT
72 ),
73 );
74 }
75
76 public function convertTime(Hexadecimal $uuidTimestamp): Time
77 {
78 $milliseconds = $this->calculator->toInteger($uuidTimestamp);
79
80 $unixTimestamp = $this->calculator->divide(
81 RoundingMode::HALF_UP,
82 6,
83 $milliseconds,
84 new IntegerObject(self::MILLISECONDS), /** @phpstan-ignore possiblyImpure.new */
85 );
86
87 $split = explode('.', (string) $unixTimestamp, 2);
88
89 /** @phpstan-ignore possiblyImpure.new */
90 return new Time($split[0], $split[1] ?? '0');
91 }
92 }