diff --git a/README.md b/README.md index dd11dc0..6159f76 100644 --- a/README.md +++ b/README.md @@ -276,11 +276,10 @@ The closure will be called fresh each time a metric is formatted. This also work ## User ID resolution -Drivers automatically resolve the current user ID using the following strategy: +Drivers automatically resolve the current user ID via `getUserId()`: 1. If a user is authenticated: `auth()->id()` -2. If a session is active: a hashed session ID -3. Otherwise: a random string (stable for the lifetime of the process) +2. Otherwise: `getAnonymousId()`, which returns a hashed session ID if a session is active, or a random string (stable for the lifetime of the process) This is used by the PostHog driver as the `distinctId`, and is available to any driver via `$driver->getUserId()`. diff --git a/src/Drivers/AbstractDriver.php b/src/Drivers/AbstractDriver.php index b342be9..c654373 100644 --- a/src/Drivers/AbstractDriver.php +++ b/src/Drivers/AbstractDriver.php @@ -79,15 +79,17 @@ public function getUserId(): mixed return call_user_func($this->userIdResolver, $this); } - return match(true) { - auth()->check() => auth()->id(), - session()->isStarted() => sha1(session()->getId()), - default => $this->getAnonymousId() - }; + return auth()->check() + ? auth()->id() + : $this->getAnonymousId(); } public function getAnonymousId(): string { + if (session()->isStarted()) { + return sha1(session()->getId()); + } + static $anonymousId = null; return $anonymousId ??= Str::random();