From c07eacc0743eeb416c452f830f97abaf24ba88ec Mon Sep 17 00:00:00 2001 From: Daniel Supernault Date: Thu, 19 Dec 2024 09:29:58 -0700 Subject: [PATCH] Add SnowflakeService and hasSnowflakePrimary --- app/Concerns/HasSnowflakePrimary.php | 19 ++++++++++ app/Services/SnowflakeService.php | 55 ++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 app/Concerns/HasSnowflakePrimary.php create mode 100644 app/Services/SnowflakeService.php 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; + } +}