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\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
31
 * consisting of milliseconds elapsed since the Unix Epoch
32
 *
33
 * @psalm-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
        $timestamp = new Time($seconds, $microseconds);
46
 
47
        // Convert the seconds into milliseconds.
48
        $sec = $this->calculator->multiply(
49
            $timestamp->getSeconds(),
50
            new IntegerObject(self::MILLISECONDS),
51
        );
52
 
53
        // Convert the microseconds into milliseconds; the scale is zero because
54
        // 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),
60
        );
61
 
62
        /** @var IntegerObject $unixTime */
63
        $unixTime = $this->calculator->add($sec, $usec);
64
 
65
        $unixTimeHex = str_pad(
66
            $this->calculator->toHexadecimal($unixTime)->toString(),
67
            12,
68
            '0',
69
            STR_PAD_LEFT
70
        );
71
 
72
        return new Hexadecimal($unixTimeHex);
73
    }
74
 
75
    public function convertTime(Hexadecimal $uuidTimestamp): Time
76
    {
77
        $milliseconds = $this->calculator->toInteger($uuidTimestamp);
78
 
79
        $unixTimestamp = $this->calculator->divide(
80
            RoundingMode::HALF_UP,
81
            6,
82
            $milliseconds,
83
            new IntegerObject(self::MILLISECONDS)
84
        );
85
 
86
        $split = explode('.', (string) $unixTimestamp, 2);
87
 
88
        return new Time($split[0], $split[1] ?? '0');
89
    }
90
}