- <?php
- namespace ForumBundle\EventSubscriber;
- use CoreBundle\Entity\Category;
- use CoreBundle\Entity\Post;
- use Doctrine\ORM\EntityManagerInterface;
- use Symfony\Component\HttpKernel\Event\ControllerEvent;
- use Symfony\Component\HttpKernel\HttpKernel;
- use Symfony\Component\HttpFoundation\RequestStack;
- use CoreBundle\Entity\Student;
- use CoreBundle\Entity\Tutor;
- use Symfony\Component\EventDispatcher\EventSubscriberInterface;
- use Symfony\Component\HttpKernel\KernelEvents;
- use Symfony\Component\Security\Core\Security;
- class ActivitySubscriber implements EventSubscriberInterface
- {
-     /** @var Security */
-     protected $security;
-     /** @var EntityManagerInterface  */
-     protected $entityManager;
-     protected $requestStack;
-     public function __construct(Security $security, EntityManagerInterface $entityManager, RequestStack $requestStack)
-     {
-         $this->security = $security;
-         $this->entityManager = $entityManager;
-         $this->requestStack = $requestStack;
-     }
-     /**
-       * {@inheritDoc}
-       * @see \Symfony\Component\EventDispatcher\EventSubscriberInterface::getSubscribedEvents()
-       */
-     public static function getSubscribedEvents()
-     {
-         return [
-             KernelEvents::CONTROLLER => 'onCoreController'
-         ];
-     }
-     /**
-      * Update the user "lastActivity" on each request
-      */
-     public function onCoreController(ControllerEvent $event)
-     {
-         // Check that the current request is a "MASTER_REQUEST"
-         // Ignore any sub-request
-         if ($event->getRequestType() !== HttpKernel::MAIN_REQUEST) {
-             return;
-         }
-         // Check token authentication availability
-         if (null !== $this->security->getToken()) {
-             $user = $this->security->getToken()->getUser();
-             if ( (($user instanceof Student) || ($user instanceof Tutor)) /*&& !($user->isActiveNow())*/ ) {
-                 $user->setLastActivity(new \DateTime('now'));
-                 $category_id = $this->requestStack->getCurrentRequest()->get('category_id');
-                 $post_id = $this->requestStack->getCurrentRequest()->get('post_id');
-                 if (null !== $category_id) {
-                     $category = $this->entityManager->getRepository(Category::class)->find($category_id);
-                     if (null !== $category) {
-                         $user->setLastCategory($category);
-                     }
-                 } elseif (null !== $post_id) {
-                     $post = $this->entityManager->getRepository(Post::class)->find($post_id);
-                     if (null !== $post) {
-                         $user->setLastCategory($post->getCategory());
-                     }
-                 }
-                 $this->entityManager->persist($user);
-                 $this->entityManager->flush();
-             }
-         }
-     }
- }