<?php declare(strict_types=1);
namespace Crehler\ProductExportScheduler\Subscriber;
use Crehler\ProductExportScheduler\DataAbstractionLayer\Entity\ProductExportLog\ProductExportLogDefinition;
use Crehler\ProductExportScheduler\Service\ProductExportLogService;
use League\Flysystem\FilesystemInterface;
use Shopware\Core\Content\ProductExport\Service\ProductExportFileHandlerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductExportSubscriber implements EventSubscriberInterface
{
protected EntityRepositoryInterface $productExportRepository;
protected ProductExportFileHandlerInterface $productExportFileHandler;
protected FilesystemInterface $fileSystem;
protected ProductExportLogService $productExportLogService;
public function __construct(
EntityRepositoryInterface $productExportRepository,
ProductExportFileHandlerInterface $productExportFileHandler,
ProductExportLogService $productExportLogService,
FilesystemInterface $fileSystem
) {
$this->productExportRepository = $productExportRepository;
$this->productExportFileHandler = $productExportFileHandler;
$this->productExportLogService = $productExportLogService;
$this->fileSystem = $fileSystem;
}
public static function getSubscribedEvents(): array
{
return [
'product_export.written' => 'onProductExportWritten',
];
}
public function onProductExportWritten(EntityWrittenEvent $event)
{
foreach ($event->getWriteResults() as $writeResult) {
if (!$this->productExportWritten($writeResult)) {
continue;
}
$primaryKey = $writeResult->getPrimaryKey();
$primaryKey = \is_array($primaryKey) ? $primaryKey['id'] : $primaryKey;
$productExportResult = $this->productExportRepository->search(new Criteria([$primaryKey]), $event->getContext());
if ($productExportResult->getTotal() !== 0) {
$productExport = $productExportResult->first();
$filePath = $this->productExportFileHandler->getFilePath($productExport);
try {
$size = $this->fileSystem->getSize($filePath);
} catch (\Throwable $e) {
$size = 0;
}
$this->productExportLogService->log(
$productExport->getId(),
ProductExportLogDefinition::DONE_STATUS,
$size
);
}
}
}
private function productExportWritten(EntityWriteResult $writeResult): bool
{
return $writeResult->getEntityName() === 'product_export'
&& $writeResult->getOperation() !== EntityWriteResult::OPERATION_DELETE
&& \array_key_exists('generatedAt', $writeResult->getPayload())
&& $writeResult->getPayload()['generatedAt'] !== null;
}
}