<?php
/*
* Copyright (c) Pickware GmbH. All rights reserved.
* This file is part of software that is released under a proprietary license.
* You must not copy, modify, distribute, make publicly available, or execute
* its contents or parts thereof without express permission by the copyright
* holder, unless otherwise permitted by law.
*/
declare(strict_types=1);
namespace Pickware\PickwareErpStarter\Reorder\Subscriber;
use DateInterval;
use DateTime;
use DateTimeZone;
use Pickware\DalBundle\EntityManager;
use Pickware\PickwareErpStarter\Reorder\ScheduledTask\ReorderNotificationTask;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskDefinition;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SystemConfigSubscriber implements EventSubscriberInterface
{
public const REORDER_NOTIFICATION_TIME_CONFIGURATION_KEY = 'PickwareErpStarter.global-plugin-config.reorderNotificationTime';
private EntityManager $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
'system_config.written' => 'afterSystemConfigWritten',
];
}
public function afterSystemConfigWritten(EntityWrittenEvent $event): void
{
$writeResults = $event->getWriteResults();
foreach ($writeResults as $writeResult) {
$payload = $writeResult->getPayload();
// Since we only support a global configuration (i.e. not for a specific sales channel), ignore
// configurations that have a sales channel id.
$isSalesChannelConfiguration = $payload['salesChannelId'] !== null;
$isReorderNotificationTimeConfiguration = $payload['configurationKey'] === self::REORDER_NOTIFICATION_TIME_CONFIGURATION_KEY;
if ($isSalesChannelConfiguration || !$isReorderNotificationTimeConfiguration) {
continue;
}
$timeNowInUTC = new DateTime('now', new DateTimeZone('UTC'));
$nextExecutionTimeInUTC = DateTime::createFromFormat('H:i:s', $payload['configurationValue'], new DateTimeZone('UTC'));
if ($timeNowInUTC > $nextExecutionTimeInUTC) {
// New reorder notification time is older than now. Set next execution to tomorrow on that time.
$nextExecutionTimeInUTC->add(new DateInterval('P1D'));
}
$this->updateNextExecutionTimeOfScheduledTask(
ReorderNotificationTask::class,
$nextExecutionTimeInUTC,
$event->getContext(),
);
}
}
private function updateNextExecutionTimeOfScheduledTask(
string $taskClass,
DateTime $nextExecutionTimeInUTC,
Context $context
): void {
$scheduledTask = $this->entityManager->findOneBy(ScheduledTaskDefinition::class, [
'scheduledTaskClass' => $taskClass,
], $context);
if (!$scheduledTask) {
return;
}
// Shopware expects the "nextExecutionTime" of a scheduled task to be in UTC
$this->entityManager->update(
ScheduledTaskDefinition::class,
[
[
'id' => $scheduledTask->getId(),
'nextExecutionTime' => $nextExecutionTimeInUTC,
],
],
$context,
);
}
}