Skip to content

Commit

Permalink
Better logged user handling (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
martenb authored May 26, 2021
1 parent 169ca38 commit c94fe41
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
24 changes: 16 additions & 8 deletions src/SentryLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@

class SentryLogger extends Logger
{
/** @var IIdentity */
private $identity;
/** @var User */
private $user = null;

/** @var Session */
private $session;
Expand Down Expand Up @@ -52,9 +52,7 @@ public function register(string $dsn, string $environment)

public function setUser(User $user)
{
if ($user->isLoggedIn()) {
$this->identity = $user->getIdentity();
}
$this->user = $user;
}

public function setUserFields(array $userFields)
Expand All @@ -72,6 +70,16 @@ public function setSession(Session $session)
$this->session = $session;
}

/**
* @return IIdentity|null
*/
public function getIdentity()
{
return $this->user !== null && $this->user->isLoggedIn()
? $this->user->getIdentity()
: null;
}

public function log($value, $priority = ILogger::INFO)
{
$response = parent::log($value, $priority);
Expand All @@ -94,12 +102,12 @@ public function log($value, $priority = ILogger::INFO)
return;
}
$scope->setLevel($severity);
if ($this->identity) {
if ($this->getIdentity() !== null) {
$userFields = [
'id' => $this->identity->getId(),
'id' => $this->getIdentity()->getId(),
];
foreach ($this->userFields as $name) {
$userFields[$name] = $this->identity->{$name} ?? null;
$userFields[$name] = $this->getIdentity()->{$name} ?? null;
}
$scope->setUser($userFields);
}
Expand Down
11 changes: 7 additions & 4 deletions tests/cases/DI/Extension.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ test(function (): void {
Assert::with($logger, function () use ($config): void {
Assert::null($this->session);

Assert::null($this->identity);
Assert::null($this->user);
Assert::null($this->getIdentity());

Assert::same([], $this->userFields);

Expand Down Expand Up @@ -86,11 +87,13 @@ test(function (): void {

Assert::type(SentryLogger::class, $logger);

Assert::with($logger, function () use ($config, $identity): void {
Assert::with($logger, function () use ($config, $user, $identity): void {
Assert::type(Session::class, $this->session);

Assert::type(IIdentity::class, $this->identity);
Assert::same($identity, $this->identity);
Assert::type(User::class, $this->user);
Assert::same($user, $this->user);
Assert::type(IIdentity::class, $this->getIdentity());
Assert::same($identity, $this->getIdentity());

Assert::same($config['user_fields'], $this->userFields);

Expand Down

0 comments on commit c94fe41

Please sign in to comment.