<?php
declare(strict_types=1);
namespace BitBag\OpenMarketplace\Component\ProductComparer\Manager;
use BitBag\OpenMarketplace\Component\Product\Entity\ProductInterface;
use BitBag\OpenMarketplace\Component\ProductComparer\Entity\ComparerInterface;
use BitBag\OpenMarketplace\Component\ProductComparer\Entity\ComparerProductInterface;
use BitBag\OpenMarketplace\Component\ProductComparer\Provider\ComparerProviderInterface;
use Doctrine\ORM\EntityManagerInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;
final class ProductComparerManager implements ProductComparerManagerInterface
{
public function __construct(
private ComparerProviderInterface $provider,
private FactoryInterface $comparerProductFactory,
private EntityManagerInterface $entityManager,
) {
}
/** @inheritDoc */
public function addProductToCompare(ProductInterface $product): void
{
$comparer = $this->provider->provide();
/** @var ComparerProductInterface $comparerProduct */
$comparerProduct = $this->comparerProductFactory->createNew();
$comparerProduct->setComparer($comparer);
$comparerProduct->setProduct($product);
$comparer->addComparerProduct($comparerProduct);
$this->entityManager->persist($comparer);
$this->entityManager->flush();
}
/** @inheritDoc */
public function removeProductFromCompare(ProductInterface $product): void
{
$comparer = $this->provider->provide();
$comparerProduct = $comparer->getComparerProductByProduct($product);
if (!$comparerProduct instanceof ComparerProductInterface) {
return;
}
$comparer->removeComparerProduct($comparerProduct);
$this->entityManager->persist($comparer);
$this->entityManager->flush();
}
/** @inheritDoc */
public function getComparer(): ComparerInterface
{
return $this->provider->provide();
}
}