<?php
namespace App\Log;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class LogEnricherHandler
{
private ?string $sessionId = null;
private string|bool|null $requestId = null;
private $userId;
private ?array $_server = null;
private ?array $_user = null;
public function __construct(private readonly TokenStorageInterface $tokenStorage, private readonly RequestStack $requestStack)
{
}
public function __invoke(array $record): array
{
if (php_sapi_name() == 'cli') {
return $record;
}
if (null === $this->sessionId &&
($request = $this->requestStack->getCurrentRequest()) &&
$request->hasSession() &&
$request->getSession()->isStarted()
) {
$this->sessionId = substr($request->getSession()->getId(), 0, 8) ?: '????????';
}
if ($this->requestId === null) {
$this->requestId = substr(uniqid(), -8);
$this->_server = [
'http.url' => (@$_SERVER['HTTP_HOST']) . (@$_SERVER['REQUEST_URI']),
'http.method' => @$_SERVER['REQUEST_METHOD'],
'http.useragent' => @$_SERVER['HTTP_USER_AGENT'],
'http.referer' => @$_SERVER['HTTP_REFERER'],
'http.x_forwarded_for' => @$_SERVER['HTTP_X_FORWARDED_FOR'],
'http.x_country_code' => @$_SERVER['HTTP_X_COUNTRY_CODE'],
];
}
if ($this->userId === null && ($user = $this->getUser())) {
$this->userId = $user->getId();
$this->_user = [
'user.id' => $user->getId(),
'user.username' => $user->getUsername(),
];
}
$record['http.request_id'] = $this->requestId;
$record['http.url'] = $this->_server['http.url'];
$record['http.method'] = $this->_server['http.method'];
$record['http.useragent'] = $this->_server['http.useragent'];
$record['http.referer'] = $this->_server['http.referer'];
$record['http.x_forwarded_for'] = $this->_server['http.x_forwarded_for'];
$record['token'] = $this->sessionId . '-' . substr(uniqid('', true), -8);
$record['user'] = $this->_user;
$record['country_code'] = $this->_server['http.x_country_code'];
$record['source'] = 'symfony';
$record['ddsource'] = 'symfony';
return $record;
}
protected function getUser(): ?\Symfony\Component\Security\Core\User\UserInterface
{
$token = $this->tokenStorage->getToken();
$user = $token === null ? null : $token->getUser();
if ($user === 'anon.') {
return null;
}
return $user;
}
}