<?php
namespace App\Manager;
use App\Entity\Sale;
use App\Entity\SaleBehaviour;
use App\Entity\User;
use App\Entity\Vehicle;
use App\Entity\VehicleBehaviour;
use App\Event\FilterBehaviourEvent;
use Doctrine\ORM\EntityManagerInterface;
/**
* Manager users behaviour.
*/
class BehaviourManager
{
public function __construct(private readonly EntityManagerInterface $em)
{
}
public function handleVehicleBehaviour(FilterBehaviourEvent $event): void
{
$user = $event->getUser();
$vehicle = $event->getEntity();
if (!$vehicle instanceof Vehicle || !$user instanceof User) {
return;
}
$vehicleRow = $this->em->getRepository(VehicleBehaviour::class)
->findOneBy([
'user' => $user,
'vehicle' => $vehicle,
]);
if (null === $vehicleRow) {
$vehicleRow = new VehicleBehaviour($user, $vehicle);
} else {
$vehicleRow->setUpdatedAt(new \DateTime());
$vehicleRow->setValue($vehicleRow->getValue() + 1);
}
$this->em->persist($vehicleRow);
$this->em->flush();
$this->handleSaleBehaviour($event);
}
public function handleSaleBehaviour(FilterBehaviourEvent $event): void
{
$user = $event->getUser();
$entity = $event->getEntity();
$sale = $entity instanceof Vehicle ? $entity->getEvent()->getSale() : $entity;
if (!$sale instanceof Sale || !$user instanceof User) {
return;
}
$saleRow = $this->em->getRepository(SaleBehaviour::class)
->findOneBy([
'user' => $user,
'sale' => $sale,
]);
if (null === $saleRow) {
$saleRow = new SaleBehaviour($user, $sale);
} else {
$saleRow->setUpdatedAt(new \DateTime());
$saleRow->setValue($saleRow->getValue() + 1);
}
$this->em->persist($saleRow);
$this->em->flush();
}
}