2021-01-13 04:50:45 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
use Illuminate\Support\Carbon;
|
2021-09-01 07:17:37 +00:00
|
|
|
use Cache;
|
2021-01-13 04:50:45 +00:00
|
|
|
|
|
|
|
class SnowflakeService {
|
|
|
|
|
|
|
|
public static function byDate(Carbon $ts = null)
|
|
|
|
{
|
2021-09-01 07:17:37 +00:00
|
|
|
$seq = Cache::get('snowflake:seq');
|
|
|
|
|
|
|
|
if(!$seq) {
|
|
|
|
Cache::put('snowflake:seq', 1);
|
|
|
|
$seq = 1;
|
|
|
|
} else {
|
|
|
|
Cache::increment('snowflake:seq');
|
|
|
|
}
|
|
|
|
|
|
|
|
if($seq >= 4095) {
|
|
|
|
$seq = 0;
|
|
|
|
Cache::put('snowflake:seq', 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
if($ts == null) {
|
|
|
|
$ts = microtime(true);
|
|
|
|
}
|
|
|
|
|
|
|
|
if($ts instanceOf Carbon) {
|
|
|
|
$ts = now()->parse($ts)->timestamp;
|
|
|
|
}
|
|
|
|
|
2021-01-13 04:50:45 +00:00
|
|
|
return ((round($ts * 1000) - 1549756800000) << 22)
|
2021-09-01 07:17:37 +00:00
|
|
|
| (random_int(1,31) << 17)
|
|
|
|
| (random_int(1,31) << 12)
|
|
|
|
| $seq;
|
2021-01-13 04:50:45 +00:00
|
|
|
}
|
|
|
|
|
2021-09-01 07:17:37 +00:00
|
|
|
}
|