src/Service/VehicleStatisticService.php line 28

  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Vehicle;
  4. use App\Repository\VehicleStatisticRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. class VehicleStatisticService
  9. {
  10.     private const SESSION_KEY_PREFIX 'vehicle_stat_';
  11.     public function __construct(
  12.         private VehicleStatisticRepository $statisticRepository,
  13.         private EntityManagerInterface $entityManager,
  14.         private RequestStack $requestStack
  15.     ) {
  16.     }
  17.     public function trackAction(Vehicle $vehiclestring $action): bool
  18.     {
  19.         $session $this->requestStack->getSession();
  20.         $sessionKey $this->getSessionKey($vehicle->getId(), $action);
  21.         $today date('Y-m-d');
  22.         if ($session->get($sessionKey) === $today) {
  23.             return false;
  24.         }
  25.         $currentMonth = (int) date('n');
  26.         $currentYear = (int) date('Y');
  27.         $statistic $this->statisticRepository->addOrIncrementStatistic(
  28.             $vehicle,
  29.             $action,
  30.             $currentMonth,
  31.             $currentYear
  32.         );
  33.         $this->entityManager->flush();
  34.         $session->set($sessionKey$today);
  35.         return true;
  36.     }
  37.     public function canTrackAction(Vehicle $vehiclestring $action): bool
  38.     {
  39.         $session $this->requestStack->getSession();
  40.         $sessionKey $this->getSessionKey($vehicle->getId(), $action);
  41.         $today date('Y-m-d');
  42.         return $session->get($sessionKey) !== $today;
  43.     }
  44.     private function getSessionKey(int $vehicleIdstring $action): string
  45.     {
  46.         return self::SESSION_KEY_PREFIX $vehicleId '_' $action;
  47.     }
  48. }