<?php
declare(strict_types=1);
namespace Wato\DigitecGalaxusExport\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\Filesystem\Filesystem;
use Wato\DigitecGalaxusExport\Helper\SFTPFileHelper;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Psr\Log\LoggerInterface;
use Shopware\Core\System\SystemConfig\SystemConfigService;
class ProductExportWrittenSubscriber implements EventSubscriberInterface {
public function __construct(EntityRepositoryInterface $productExportRepo, SFTPFileHelper $sftp, LoggerInterface $logger, SystemConfigService $systemConfigService)
{
$this->productExportRepo = $productExportRepo;
$this->sftp = $sftp;
$this->logger = $logger;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents()
{
return [
'product_export.written' => 'afterWrite',
];
}
public function afterWrite(EntityWrittenEvent $event): void
{
$context = $event->getContext();
$user = $this->systemConfigService->get('DigitecGalaxusExport.config.ftpUser');
$pw = $this->systemConfigService->get('DigitecGalaxusExport.config.ftpPassword');
$server = $this->systemConfigService->get('DigitecGalaxusExport.config.ftpServer');
$directory = $this->systemConfigService->get('DigitecGalaxusExport.config.articleDataDirectory');
foreach ($event->getPayloads() as $payload)
{
$id = $payload['id'];
$filename = $this->productExportRepo->search(new Criteria([$id]), $context)->first()->fileName;
if (str_starts_with($filename, 'Product'))
{
try {
$this->sftp->deployFile($filename, $user, $pw, $server, $directory);
} catch (\Throwable $t){
$this->logger->error(date('D M d, Y G:i') . ': ' . $t->getMessage() . ' Line: ' . $t->getLine() . ' File: ' . $t->getFile() . PHP_EOL);
continue;
}
}
}
}
private function productExportWritten(EntityWriteResult $writeResult): bool
{
return $writeResult->getEntityName() === 'product_export'
&& $writeResult->getOperation() !== EntityWriteResult::OPERATION_DELETE
&& !\array_key_exists('generatedAt', $writeResult->getPayload());
}
}