diff --git a/app/Concerns/HasSnowflakePrimary.php b/app/Concerns/HasSnowflakePrimary.php new file mode 100644 index 0000000..c6d9756 --- /dev/null +++ b/app/Concerns/HasSnowflakePrimary.php @@ -0,0 +1,19 @@ +getKey())) { + $keyName = $model->getKeyName(); + $id = resolve(SnowflakeService::class)->next(); + $model->setAttribute($keyName, $id); + } + }); + } +} diff --git a/app/Services/SnowflakeService.php b/app/Services/SnowflakeService.php new file mode 100644 index 0000000..5656d94 --- /dev/null +++ b/app/Services/SnowflakeService.php @@ -0,0 +1,55 @@ += 4095) { + Cache::put('snowflake:seq', 0); + $seq = 0; + } + + return ((round(microtime(true) * 1000) - 1711624913000) << 22) + | (random_int(1,31) << 17) + | (random_int(1,31) << 12) + | $seq; + } + + public static function byDate(Carbon $ts = null) + { + if($ts instanceOf Carbon) { + $ts = now()->parse($ts)->timestamp; + } else { + return self::next(); + } + + return ((round($ts * 1000) - 1711624913000) << 22) + | (random_int(1,31) << 17) + | (random_int(1,31) << 12) + | 0; + } +}