Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`.

Expand Down
12 changes: 7 additions & 5 deletions src/Drivers/AbstractDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down