Created
March 12, 2013 18:05
-
-
Save elnur/5145317 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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