<?php
/**
* Copyright (c) 2011-present Qualiteam software Ltd. All rights reserved.
* See https://www.x-cart.com/license-agreement.html for license details.
*/
namespace XCart\EntityCallback;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use XCart\Doctrine\CallbackManager\CallbackManager;
use XCart\Event\Service\DeferrerCallbackRunEvent;
use XLite\Model\Product;
final class ProductCallback
{
public function __construct(
private CallbackManager $callbackManager,
private EntityManagerInterface $entityManager
) {
}
public function prePersist(Product $product, LifecycleEventArgs $args): void
{
$time = \XLite\Core\Converter::time();
if (!$product->getDate()) {
$product->setDate($time);
}
if (!$product->getArrivalDate()) {
$product->setArrivalDate(
mktime(0, 0, 0, date('m', $time), date('j', $time), date('Y', $time))
);
}
$this->preUpdate($product, $args);
}
public function preUpdate(Product $product, LifecycleEventArgs $args): void
{
$product->setUpdateDate(\XLite\Core\Converter::time());
if (\XLite\Core\Converter::isEmptyString($product->getSku())) {
$product->setSku(null);
}
}
public function postUpdate(Product $product, LifecycleEventArgs $args): void
{
if (
$product->isLowLimitReached()
&& $product->isShouldSend()
&& $product->isInventoryChanged()
) {
$product->sendLowLimitNotification();
}
$context = $this->callbackManager->getContextValue();
if (!in_array($context, ['import', 'load-fixtures', 'remove-data'], true)) {
$this->callbackManager->addDeferredCallback(
'quickDataProductRecalculate',
[
$product->getProductId()
]
);
}
}
public function postPersist(Product $product, LifecycleEventArgs $args): void
{
$context = $this->callbackManager->getContextValue();
if (!in_array($context, ['import', 'load-fixtures'], true)) {
$this->callbackManager->addDeferredCallback(
'quickDataProductRecalculate',
[
$product->getProductId()
]
);
}
}
public function runQuickData(
DeferrerCallbackRunEvent $callbackRunEvent,
string $eventName,
EventDispatcherInterface $dispatcher
): void {
if ($dtos = $callbackRunEvent->getCallbackDto('quickDataProductRecalculate')) {
foreach ($dtos as $dto) {
if ($productId = $dto->getArgs()[0]) {
$this->entityManager
->getRepository(Product::class)
->find($productId)
?->updateQuickData();
}
}
}
}
}