<?php
declare(strict_types=1);
namespace Iwv\IwvDatevV6\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\DeleteCommand;
use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
use Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskDefinition;
use Iwv\IwvDatevV6\Service\ScheduledTask\ScheduledExportTask;
use Iwv\IwvDatevV6\Core\Content\IwvDatev\ScheduledExportEvents;
use Iwv\IwvDatevV6\Core\Content\IwvDatev\ScheduledExportDefinition;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use League\Flysystem\FilesystemInterface;
class ScheduledExportSubscriber implements EventSubscriberInterface
{
/** @var EntityRepositoryInterface */
protected $scheduledTaskRepository;
/** @var FilesystemInterface $filesystemPrivate */
private $filesystemPrivate;
/**
* @param EntityRepositoryInterface $scheduledTaskRepository
* @param FilesystemInterface $filesystemPrivate
*/
public function __construct(
EntityRepositoryInterface $scheduledTaskRepository,
FilesystemInterface $filesystemPrivate
) {
$this->scheduledTaskRepository = $scheduledTaskRepository;
$this->filesystemPrivate = $filesystemPrivate;
}
public static function getSubscribedEvents(): array
{
return [
PreWriteValidationEvent::class => 'onPreWriteValidationEvent',
ScheduledExportEvents::ENTITY_DELETED_EVENT => 'onEntityDeleted',
ScheduledExportEvents::ENTITY_WRITTEN_EVENT => 'onEntityWritten',
];
}
public function onPreWriteValidationEvent(PreWriteValidationEvent $event): void
{
foreach ($event->getCommands() as $command) {
if ($command->getDefinition()->getEntityName() !== ScheduledExportDefinition::ENTITY_NAME) {
continue;
}
if (!$command instanceof DeleteCommand) {
continue;
}
$command->requestChangeSet();
}
}
public function onEntityDeleted(EntityDeletedEvent $event): void
{
foreach ($event->getIds() as $id) {
if ($this->filesystemPrivate->has($id)) {
$this->filesystemPrivate->delete($id);
}
}
}
public function onEntityWritten(EntityWrittenEvent $event): void
{
$context = $event->getContext();
/** @var \Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskEntity $taskDB */
if ($taskDB = $this->scheduledTaskRepository
->search((new Criteria)
->addFilter(new EqualsFilter('name', ScheduledExportTask::getTaskName()))
->addFilter(new EqualsFilter('status', ScheduledTaskDefinition::STATUS_QUEUED))
, $context)
->first()) {
$this->scheduledTaskRepository->update([
[
'id' => $taskDB->getId(),
'status' => ScheduledTaskDefinition::STATUS_SCHEDULED,
]
]
, $context);
}
}
}