summaryrefslogtreecommitdiff
path: root/src/Timestamp.php
blob: a23ba13d743452cab60a1f6858ff1df2bf1af168 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php

declare(strict_types=1);

namespace Zhineng\Snowflake;

final class Timestamp extends Field
{
    use Makable;

    /**
     * The epoch in milliseconds.
     */
    public readonly int $epoch;

    public function __construct(
        string $name = 'timestamp',
        int $bits = 41,
        \DateTime|int|null $epoch = null
    ) {
        parent::__construct($name, $bits);

        $this->epoch = $epoch instanceof \DateTime
            ? $epoch->getTimestamp() * 1000
            : ($epoch ?? 0);

        if ($this->epoch < 0) {
            throw new \InvalidArgumentException('Epoch must be non-negative.');
        }
    }

    public function value(): int
    {
        $now = (int) floor(microtime(as_float: true) * 1000);

        return $now - $this->epoch;
    }
}