<?php
namespace Tonur\Packstation\Subscriber;
use Exception;
use Psr\Log\LoggerAwareTrait;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\CustomField\CustomFieldEntity;
use Shopware\Core\System\SystemConfig\Event\SystemConfigChangedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Tonur\Packstation\TonurPackstation6;
class SystemConfigSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $customFieldRepository;
use LoggerAwareTrait;
public function __construct(EntityRepositoryInterface $customFieldRepository)
{
$this->customFieldRepository = $customFieldRepository;
}
public static function getSubscribedEvents()
{
return [
SystemConfigChangedEvent::class => 'onSystemConfigChanged'
];
}
public function onSystemConfigChanged(SystemConfigChangedEvent $event)
{
$key = TonurPackstation6::BUNDLE_NAME . '.config.invertDeliveryEnabled';
if ($key !== $event->getKey()) {
return;
}
if ($event->getSalesChannelId() != null) {
return;
}
try {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('name', TonurPackstation6::CUSTOMFIELD_PACKSTATION_DELIVERY_ENABLED));
$context = Context::createDefaultContext();
/** @var CustomFieldEntity $repertusPackstationDeliveryEnabled */
$repertusPackstationDeliveryEnabled = $this->customFieldRepository->search($criteria, $context)->first();
if (!$repertusPackstationDeliveryEnabled || !($config = $repertusPackstationDeliveryEnabled->getConfig())) {
return;
}
if (!$event->getValue()) {
$config['label'] = [
"de-DE" => "Lieferung an Packstation möglich",
"en-GB" => "Delivery to packstation is possible"
];
} else {
$config['label'] = [
"de-DE" => "Lieferung an Packstation nicht möglich",
"en-GB" => "delivery to packstation is not possible"
];
}
$this->customFieldRepository->update([[
'id' => $repertusPackstationDeliveryEnabled->getId(),
'config' => $config
]], $context);
} catch (Exception $ex) {
$this->logger->error(__METHOD__ . ': an error occurred.', ['message' => $ex->getMessage(), 'exception' => $ex]);
}
}
}