src/EventSubscriber/DailyActivitySubscriber.php line 35

Open in your IDE?
  1. <?php
  2. // src/EventSubscriber/DailyActivitySubscriber.php
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Security\Core\User\InMemoryUser;
  9. use App\Entity\UserDailyActivity;
  10. use Symfony\Contracts\Cache\CacheInterface;
  11. use Symfony\Contracts\Cache\ItemInterface;
  12. class DailyActivitySubscriber implements EventSubscriberInterface
  13. {
  14. private EntityManagerInterface $em;
  15. private Security $security;
  16. private CacheInterface $cache;
  17. public function __construct(EntityManagerInterface $em, Security $security,CacheInterface $cache)
  18. {
  19. $this->em = $em;
  20. $this->security = $security;
  21. $this->cache = $cache;
  22. }
  23. public static function getSubscribedEvents(): array
  24. {
  25. return [
  26. RequestEvent::class => 'onRequest',
  27. ];
  28. }
  29. public function onRequest(RequestEvent $event)
  30. {
  31. if (!$event->isMainRequest()) {
  32. return;
  33. }
  34. $user = $this->security->getUser();
  35. // Machine clients (e.g. the capacity API token) are not people and have no id to log.
  36. if (!$user || $user instanceof InMemoryUser) {
  37. return;
  38. }
  39. $userId = $user->getId();
  40. $userType = (new \ReflectionClass($user))->getShortName();
  41. $cacheKey = "daily_log_{$userType}_{$userId}";
  42. $request = $event->getRequest();
  43. $ipAddress = $request->getClientIp();
  44. $alreadyLogged = $this->cache->get($cacheKey, function (ItemInterface $item) use ($userId, $userType,$ipAddress) {
  45. $now = new \DateTimeImmutable();
  46. $midnight = $now->modify('tomorrow')->setTime(0, 0);
  47. $item->expiresAt($midnight);
  48. $today = new \DateTimeImmutable('now');
  49. $repo = $this->em->getRepository(UserDailyActivity::class);
  50. $existing = $repo->findOneBy([
  51. 'userId' => $userId,
  52. 'userType' => $userType,
  53. 'date' => $today,
  54. ]);
  55. if (!$existing) {
  56. $log = new UserDailyActivity();
  57. $log->setUserId($userId);
  58. $log->setUserType($userType);
  59. $log->setDate($today);
  60. $log->setInfo($ipAddress);
  61. $this->em->persist($log);
  62. $this->em->flush();
  63. }
  64. return true; // Flag it as "logged"
  65. });
  66. }
  67. }