<?php
namespace App\Event\CountPaidOrder;
use App\Entity\CountPaidOrder\CountPaidOrder;
use App\Entity\Order\Order;
use App\Entity\User\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
class CountPaidOrderSubscriber implements EventSubscriberInterface
{
private $_em;
private $_logger;
public function __construct(EntityManagerInterface $em, LoggerInterface $logger)
{
$this->_em = $em;
$this->_logger = $logger;
}
public static function getSubscribedEvents()
{
return [
CountPaidOrderEvent::NAME => 'countPaidOrder'
];
}
public function countPaidOrder(CountPaidOrderEvent $event)
{
$user_email = $event->getUserEmail();
$countPaidOrders = $this->_em->getRepository(CountPaidOrder::class)->findOneBy(['email' => $user_email]);
$user = $this->_em->getRepository(User::class)->findOneBy(['email' => $user_email]);
if (is_null($user)) {
$this->_logger->critical('No email found', [
'email' => $user_email,
]);
return false;
}
$count = $this->_em->getRepository(Order::class)->findBy([
'ownerEmail' => $user_email,
'isPaid' => 1
]);
$orders = $this->_em->getRepository(Order::class)->findBy(
['ownerEmail' => $user_email]
);
if (is_null($countPaidOrders)) {
$countPaidOrders = new CountPaidOrder();
$countPaidOrders->setEmail($user_email);
$countPaidOrders->setCount(count($count));
$countPaidOrders->setCreatedAt(new \DateTime());
$this->_em->persist($countPaidOrders);
} else {
$countPaidOrders->setCount((int)$countPaidOrders->getCount() + 1);
$countPaidOrders->setUpdatedAt(new \DateTime());
}
$user->setCountPaidOrder($countPaidOrders);
$this->_em->flush();
foreach ($orders as $order) {
if ($order->getCountPaidOrder() == null) {
$order->setCountPaidOrder($countPaidOrders);
$this->_em->flush();
}
}
}
}