Skip to content

Instantly share code, notes, and snippets.

@elnur
Created March 12, 2013 18:05
Show Gist options
  • Save elnur/5145317 to your computer and use it in GitHub Desktop.
Save elnur/5145317 to your computer and use it in GitHub Desktop.
<?php
namespace Elnur\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Observe;
use Elnur\Manager\VisitManager;
use Elnur\Model\Visit;
/**
* @Service
*/
class VisitListener
{
/**
* @var SecurityContextInterface
*/
private $securityContext;
/**
* @var VisitManager
*/
private $visitManager;
/**
* @InjectParams
*
* @param SecurityContextInterface $securityContext
* @param VisitManager $visitManager
*/
public function __construct(SecurityContextInterface $securityContext, VisitManager $visitManager)
{
$this->securityContext = $securityContext;
$this->visitManager = $visitManager;
}
/**
* @Observe("kernel.request")
*/
public function onRequest(GetResponseEvent $event)
{
if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
return;
}
$token = $this->securityContext->getToken();
if (null === $token) {
return;
}
$request = $event->getRequest();
$user = $this->securityContext->isGranted('ROLE_USER') ? $token->getUser() : null;
$ip = $request->getClientIp();
$method = $request->getRealMethod();
$uri = substr($request->getRequestUri(), strlen($request->getBaseUrl()));
$referer = $request->server->get('HTTP_REFERER');
$agent = $request->server->get('HTTP_USER_AGENT');
$visit = new Visit([
'user' => $user,
'ip' => $ip,
'method' => $method,
'uri' => $uri,
'referer' => $referer,
'agent' => $agent,
]);
$this->visitManager->save($visit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment