<?php declare(strict_types=1);
namespace Albis\AlbisLease\Subscriber;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\System\CustomField\CustomFieldCollection;
use Shopware\Core\System\CustomField\CustomFieldEntity;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
class ProductPageSubscriber implements EventSubscriberInterface
{
/**
* @var SystemConfigService
*/
private $systemConfigService;
public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents()
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded',
];
}
public function onProductsLoaded(EntityLoadedEvent $event): void
{
$context = $event->getContext();
$entities = $event->getEntities();
if(!method_exists($context->getSource(), 'getSalesChannelId')) {
return;
}
$salesChannelId = $context->getSource()->getSalesChannelId();
$pluginConfig = $this->systemConfigService->get('AlbisLease.config', $salesChannelId);
if(!$pluginConfig['detailPageDisplay']) {
return;
}
/** @var SalesChannelProductEntity $entity */
foreach($entities as $entity) {
$price = $entity->getPrice()->first()->getNet();
if($price >= 500) {
$customFields = array_merge($entity->getCustomFields(), [
'albisLeasingAvailable' => true
]);
$entity->setCustomFields($customFields);
}
}
}
}