Passed
Push — master ( df82e9...2d46b6 )
by xu
01:50
created

Snowflake::callResolver()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.8666
c 0
b 0
f 0
cc 4
nc 5
nop 1
crap 4
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
     * Build Snowflake Instance.
55
     *
56
     * @param int $datacenter
57
     * @param int $workerid
58
     */
59 10
    public function __construct(int $datacenter = null, int $workerid = null)
60
    {
61 10
        $maxDataCenter = -1 ^ (-1 << self::MAX_DATACENTER_LENGTH);
62 10
        $maxWorkId = -1 ^ (-1 << self::MAX_WORKID_LENGTH);
63
64
        // If not set datacenter or workid, we will set a default value to use.
65 10
        $this->datacenter = $datacenter > $maxDataCenter || $datacenter < 0 ? mt_rand(0, 31) : $datacenter;
66 10
        $this->workerid = $workerid > $maxWorkId || $workerid < 0 ? mt_rand(0, 31) : $workerid;
67 10
    }
68
69
    /**
70
     * Get snowflake id.
71
     *
72
     * @return int
73
     */
74 5
    public function id()
75
    {
76 5
        $currentTime = $this->getCurrentMicrotime();
77 5
        while (($sequence = $this->callResolver($currentTime)) > (-1 ^ (-1 << self::MAX_SEQUENCE_LENGTH))) {
78
            usleep(1);
79
            $currentTime = $this->getCurrentMicrotime();
80
        }
81
82 5
        $workerLeftMoveLength = self::MAX_SEQUENCE_LENGTH;
83 5
        $datacenterLeftMoveLength = self::MAX_WORKID_LENGTH + $workerLeftMoveLength;
84 5
        $timestampLeftMoveLength = self::MAX_DATACENTER_LENGTH + $datacenterLeftMoveLength;
85
86 5
        return (string) ((($currentTime - $this->getStartTimeStamp()) << $timestampLeftMoveLength)
87 5
            | ($this->datacenter << $datacenterLeftMoveLength)
88 5
            | ($this->workerid << $workerLeftMoveLength)
89 5
            | ($sequence));
90
    }
91
92
    /**
93
     * Parse snowflake id.
94
     *
95
     * @param string $id
96
     *
97
     * @return array
98
     */
99 3
    public function parseId(string $id, $transform = false): array
100
    {
101 3
        $id = decbin($id);
102
103
        $data = [
104 3
            'timestamp' => substr($id, 0, -22),
105 3
            'sequence' => substr($id, -12),
106 3
            'workerid' => substr($id, -17, 5),
107 3
            'datacenter' => substr($id, -22, 5),
108
        ];
109
110
        return $transform ? array_map(function ($value) {
111 3
            return bindec($value);
112 3
        }, $data) : $data;
113
    }
114
115
    /**
116
     * Get current microtime timestamp.
117
     *
118
     * @return int
119
     */
120 7
    public function getCurrentMicrotime()
121
    {
122 7
        return floor(microtime(true) * 1000) | 0;
123
    }
124
125
    /**
126
     * Set start time (millisecond).
127
     *
128
     * @param int $startTime
129
     */
130 2
    public function setStartTimeStamp(int $startTime)
131
    {
132 2
        $missTime = $this->getCurrentMicrotime() - $startTime;
133 2
        if ($missTime < 0 || $missTime > ($maxTimeDiff = ((1 << self::MAX_TIMESTAMP_LENGTH) - 1))) {
134 1
            throw new \Exception('The starttime cannot be greater than current time and the maximum time difference is '.$maxTimeDiff);
135
        }
136
137 2
        $this->startTime = $startTime;
138
139 2
        return $this;
140
    }
141
142
    /**
143
     * Get start timestamp (millisecond), If not set default to 2019-08-08 08:08:08.
144
     *
145
     * @return int
146
     */
147 6
    public function getStartTimeStamp()
148
    {
149 6
        if ($this->startTime > 0) {
150 2
            return $this->startTime;
151
        }
152
153
        // We set a default start time if you not set.
154 5
        $defaultTime = '2019-08-08 08:08:08';
155
156 5
        return strtotime($defaultTime) * 1000;
157
    }
158
159
    /**
160
     * Set Sequence Resolver.
161
     *
162
     * @param SequenceResolver|callable $sequence
163
     */
164 3
    public function setSequenceResolver($sequence)
165
    {
166 3
        $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...
167
168 3
        return $this;
169
    }
170
171
    /**
172
     * Get Sequence Resolver.
173
     *
174
     * @return \Godruoyi\Snowflake\SequenceResolver|callable|null
175
     */
176 6
    public function getSequenceResolver()
177
    {
178 6
        return $this->sequence;
179
    }
180
181
    /**
182
     * Get Default Sequence Resolver.
183
     *
184
     * @return \Godruoyi\Snowflake\SequenceResolver
185
     */
186 4
    public function getDefaultSequenceResolver(): SequenceResolver
187
    {
188 4
        return new RandomSequenceResolver();
189
    }
190
191
    /**
192
     * Call resolver.
193
     *
194
     * @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...
195
     * @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...
196
     *
197
     * @return int
198
     */
199 5
    protected function callResolver($currentTime)
200
    {
201 5
        $resolver = $this->getSequenceResolver();
202
203 5
        if (is_callable($resolver)) {
204 2
            return $resolver($currentTime);
205
        }
206
207 3
        return is_null($resolver) || !($resolver instanceof SequenceResolver)
208 3
            ? $this->getDefaultSequenceResolver()->sequence($currentTime)
209 3
            : $resolver->sequence($currentTime);
210
    }
211
}
212