Snowflake::getDefaultSequenceResolver()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
/*
4
 * This file is part of the godruoyi/php-snowflake.
5
 *
6
 * (c) Godruoyi <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled.
9
 */
10
11
namespace Godruoyi\Snowflake;
12
13
class Snowflake
14
{
15
    const MAX_TIMESTAMP_LENGTH = 41;
16
17
    const MAX_DATACENTER_LENGTH = 5;
18
19
    const MAX_WORKID_LENGTH = 5;
20
21
    const MAX_SEQUENCE_LENGTH = 12;
22
23
    const MAX_FIRST_LENGTH = 1;
24
25
    /**
26
     * The data center id.
27
     *
28
     * @var int
29
     */
30
    protected $datacenter;
31
32
    /**
33
     * The worker id.
34
     *
35
     * @var int
36
     */
37
    protected $workerid;
38
39
    /**
40
     * The Sequence Resolver instance.
41
     *
42
     * @var \Godruoyi\Snowflake\SequenceResolver|null
43
     */
44
    protected $sequence;
45
46
    /**
47
     * The start timestamp.
48
     *
49
     * @var int
50
     */
51
    protected $startTime;
52
53
    /**
54
     * Default sequence resolver.
55
     *
56
     * @var \Godruoyi\Snowflake\SequenceResolver|null
57
     */
58
    protected $defaultSequenceResolver;
59
60
    /**
61
     * Build Snowflake Instance.
62
     *
63
     * @param int $datacenter
64
     * @param int $workerid
65
     */
66 13
    public function __construct(int $datacenter = null, int $workerid = null)
67
    {
68 13
        $maxDataCenter = -1 ^ (-1 << self::MAX_DATACENTER_LENGTH);
69 13
        $maxWorkId = -1 ^ (-1 << self::MAX_WORKID_LENGTH);
70
71
        // If not set datacenter or workid, we will set a default value to use.
72 13
        $this->datacenter = $datacenter > $maxDataCenter || $datacenter < 0 ? mt_rand(0, 31) : $datacenter;
73 13
        $this->workerid = $workerid > $maxWorkId || $workerid < 0 ? mt_rand(0, 31) : $workerid;
74 13
    }
75
76
    /**
77
     * Get snowflake id.
78
     *
79
     * @return string
80
     */
81 6
    public function id()
82
    {
83 6
        $currentTime = $this->getCurrentMicrotime();
84 6
        while (($sequence = $this->callResolver($currentTime)) > (-1 ^ (-1 << self::MAX_SEQUENCE_LENGTH))) {
85
            usleep(1);
86
            $currentTime = $this->getCurrentMicrotime();
87
        }
88
89 6
        $workerLeftMoveLength = self::MAX_SEQUENCE_LENGTH;
90 6
        $datacenterLeftMoveLength = self::MAX_WORKID_LENGTH + $workerLeftMoveLength;
91 6
        $timestampLeftMoveLength = self::MAX_DATACENTER_LENGTH + $datacenterLeftMoveLength;
92
93 6
        return (string) ((($currentTime - $this->getStartTimeStamp()) << $timestampLeftMoveLength)
94 6
            | ($this->datacenter << $datacenterLeftMoveLength)
95 6
            | ($this->workerid << $workerLeftMoveLength)
96 6
            | ($sequence));
97
    }
98
99
    /**
100
     * Parse snowflake id.
101
     */
102 3
    public function parseId(string $id, $transform = false): array
103
    {
104 3
        $id = decbin($id);
105
106
        $data = [
107 3
            'timestamp' => substr($id, 0, -22),
108 3
            'sequence' => substr($id, -12),
109 3
            'workerid' => substr($id, -17, 5),
110 3
            'datacenter' => substr($id, -22, 5),
111
        ];
112
113
        return $transform ? array_map(function ($value) {
114 3
            return bindec($value);
115 3
        }, $data) : $data;
116
    }
117
118
    /**
119
     * Get current microtime timestamp.
120
     *
121
     * @return int
122
     */
123 15
    public function getCurrentMicrotime()
124
    {
125 15
        return floor(microtime(true) * 1000) | 0;
126
    }
127
128
    /**
129
     * Set start time (millisecond).
130
     */
131 3 View Code Duplication
    public function setStartTimeStamp(int $startTime)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133 3
        $missTime = $this->getCurrentMicrotime() - $startTime;
134
135 3
        if ($missTime < 0) {
136
            throw new \Exception('The start time cannot be greater than the current time');
137
        }
138
139 3
        $maxTimeDiff = -1 ^ (-1 << self::MAX_TIMESTAMP_LENGTH);
140
141 3
        if ($missTime > $maxTimeDiff) {
142 2
            throw new \Exception(sprintf('The current microtime - starttime is not allowed to exceed -1 ^ (-1 << %d), You can reset the start time to fix this', self::MAX_TIMESTAMP_LENGTH));
143
        }
144
145 3
        $this->startTime = $startTime;
146
147 3
        return $this;
148
    }
149
150
    /**
151
     * Get start timestamp (millisecond), If not set default to 2019-08-08 08:08:08.
152
     *
153
     * @return int
154
     */
155 10
    public function getStartTimeStamp()
156
    {
157 10
        if ($this->startTime > 0) {
158 3
            return $this->startTime;
159
        }
160
161
        // We set a default start time if you not set.
162 9
        $defaultTime = '2019-08-08 08:08:08';
163
164 9
        return strtotime($defaultTime) * 1000;
165
    }
166
167
    /**
168
     * Set Sequence Resolver.
169
     *
170
     * @param SequenceResolver|callable $sequence
171
     */
172 4
    public function setSequenceResolver($sequence)
173
    {
174 4
        $this->sequence = $sequence;
0 ignored issues
show
Documentation Bug introduced by
It seems like $sequence can also be of type callable. However, the property $sequence is declared as type object<Godruoyi\Snowflake\SequenceResolver>|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
175
176 4
        return $this;
177
    }
178
179
    /**
180
     * Get Sequence Resolver.
181
     *
182
     * @return \Godruoyi\Snowflake\SequenceResolver|callable|null
183
     */
184 10
    public function getSequenceResolver()
185
    {
186 10
        return $this->sequence;
187
    }
188
189
    /**
190
     * Get Default Sequence Resolver.
191
     *
192
     * @return \Godruoyi\Snowflake\SequenceResolver
193
     */
194 8
    public function getDefaultSequenceResolver(): SequenceResolver
195
    {
196 8
        return $this->defaultSequenceResolver ?: $this->defaultSequenceResolver = new RandomSequenceResolver();
197
    }
198
199
    /**
200
     * Call resolver.
201
     *
202
     * @param callable|\Godruoyi\Snowflake\SequenceResolver $resolver
0 ignored issues
show
Bug introduced by
There is no parameter named $resolver. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
203
     * @param int                                           $maxSequence
0 ignored issues
show
Bug introduced by
There is no parameter named $maxSequence. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
204
     *
205
     * @return int
206
     */
207 8
    protected function callResolver($currentTime)
208
    {
209 8
        $resolver = $this->getSequenceResolver();
210
211 8
        if (is_callable($resolver)) {
212 2
            return $resolver($currentTime);
213
        }
214
215 6
        return is_null($resolver) || !($resolver instanceof SequenceResolver)
216 6
            ? $this->getDefaultSequenceResolver()->sequence($currentTime)
217 6
            : $resolver->sequence($currentTime);
218
    }
219
}
220