<?php
declare(strict_types=1);
namespace MadArticleBuyTime\Subscriber;
use MadArticleBuyTime\MadArticleBuyTime;
use MadArticleBuyTime\Service\MadCustomFieldService;
use MadArticleBuyTime\Struct\BuyTimeStruct;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductSearchResultEvent;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductPageLoaded',
ProductListingResultEvent::class => 'onProductListingResult',
ProductSearchResultEvent::class => 'onProductListingResult',
];
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
$this->addBuyTimeExtensionToProduct($product);
}
public function onProductListingResult(ProductListingResultEvent $event): void
{
foreach ($event->getResult() as $product) {
$this->addBuyTimeExtensionToProduct($product);
}
}
private function addBuyTimeExtensionToProduct(SalesChannelProductEntity $product): void
{
if ($product->hasExtension(MadArticleBuyTime::BUYTIME_PRODUCT_EXTENSION_KEY)) {
return;
}
$customFields = $product->getCustomFields();
if (isset($customFields[MadCustomFieldService::CUSTOM_FIELD_BUYTIME_START])
&& isset($customFields[MadCustomFieldService::CUSTOM_FIELDS_BUYTIME_END])
) {
$start = \DateTimeImmutable::createFromFormat(
\DateTimeInterface::ATOM,
$customFields[MadCustomFieldService::CUSTOM_FIELD_BUYTIME_START]
);
$end = \DateTimeImmutable::createFromFormat(
\DateTimeInterface::ATOM,
$customFields[MadCustomFieldService::CUSTOM_FIELDS_BUYTIME_END]
);
if ($start && $end) {
$buyTime = new BuyTimeStruct($start, $end);
$product->addExtension(MadArticleBuyTime::BUYTIME_PRODUCT_EXTENSION_KEY, $buyTime);
}
}
}
}