<?php
namespace Rawafed\CommonsBundle\Service;
use Doctrine\Common\Annotations\Reader;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
class ViewsCountListener
{
private $entityManager;
private $annotationReader;
public function __construct(Reader $annotationReader, EntityManager $entityManager)
{
$this->annotationReader = $annotationReader;
$this->entityManager = $entityManager;
}
public function onKernelController(ControllerEvent $event)
{
if ($event->isMasterRequest()) {
$request = $event->getRequest();
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
list($controllerObject, $methodName) = $controller;
$refMethod = new \ReflectionMethod($controllerObject, $methodName);
$annotations = $this->annotationReader->getMethodAnnotations($refMethod);
foreach ($annotations as $annotation) {
if ($annotation instanceof ViewsCount) {
$attributes = $request->attributes->all();
foreach ($attributes as $name => $attribute) {
if ($attribute instanceof \Rawafed\CommonsBundle\Entity\CountableInterface) {
$__stats = array(
'type' => get_class($attribute),
'id' => $attribute->getId()
);
$field = $annotation->getFieldName();
if ($field != 'views_count') {
$__stats['field'] = $field;
}
$request->attributes->set('__stats', $__stats);
break;
}
}
break;
}
}
}
}
}