68 lines
1.7 KiB
PHP
68 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Logging;
|
|
|
|
use App\Entity\Core\User;
|
|
use Monolog\Attribute\AsMonologProcessor;
|
|
use Monolog\LogRecord;
|
|
use Symfony\Bundle\SecurityBundle\Security;
|
|
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
|
|
|
|
#[AsMonologProcessor]
|
|
class UserDataProcessor
|
|
{
|
|
public function __construct(private readonly Security $security)
|
|
{
|
|
}
|
|
|
|
public function __invoke(LogRecord $record): LogRecord
|
|
{
|
|
if (isset($record->extra['user'])) {
|
|
return $record;
|
|
}
|
|
|
|
if ('cli' === php_sapi_name()) {
|
|
$record->extra['user'] = [
|
|
'id' => null,
|
|
'username' => 'SYSTEM',
|
|
'role' => 'system',
|
|
];
|
|
|
|
return $record;
|
|
}
|
|
|
|
/** @var User $user */
|
|
$user = $this->security->getUser();
|
|
|
|
if (null === $user) {
|
|
$record->extra['user'] = [
|
|
'id' => null,
|
|
'username' => 'ANONYMOUS',
|
|
'role' => 'public',
|
|
];
|
|
|
|
return $record;
|
|
}
|
|
|
|
// Check for switched or aliased users
|
|
$originalUser = null;
|
|
$token = $this->security->getToken();
|
|
if ($token instanceof SwitchUserToken) {
|
|
// User is currently switched to
|
|
$originalUser = $token->getOriginalToken()->getUser();
|
|
}
|
|
if (null !== $originalUser) {
|
|
$username = sprintf('%s (via %s)', $user->getUserIdentifier(), $originalUser->getUserIdentifier());
|
|
} else {
|
|
$username = $user->getUserIdentifier();
|
|
}
|
|
$record->extra['user'] = [
|
|
'id' => $user->getId(),
|
|
'username' => $username,
|
|
'roles' => $user->getRoles(),
|
|
];
|
|
|
|
return $record;
|
|
}
|
|
}
|