<?php declare(strict_types=1);
namespace Cbax\ModulOrderImportGalaxus\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Cbax\ModulExternalOrder\Core\Content\ExternalOrder\ExternalOrderEvents;
use Cbax\ModulExternalOrder\Components\ExternalOrderHelper;
use Cbax\ModulOrderImportGalaxus\Bootstrap\Database;
use Cbax\ModulOrderImportGalaxus\Components\Client;
class BackendSubscriber implements EventSubscriberInterface
{
private $client;
private $externalOrderHelper;
private $marketplaceName = Database::MARKETPLACE_NAME;
private $localFilesDir;
public function __construct(
Client $client,
ExternalOrderHelper $externalOrderHelper
) {
$this->client = $client;
$this->externalOrderHelper = $externalOrderHelper;
$this->localFilesDir = $client->localFilesDir;
}
public static function getSubscribedEvents(): array
{
return [
ExternalOrderEvents::CBAX_EXTERNAL_ORDER_IMPORT_FAILED_EVENT => 'onImportFailed',
ExternalOrderEvents::CBAX_EXTERNAL_ORDER_SAVE_EXTERNAL_ORDER_AFTER_SAVE_EVENT => 'onExternalOrderWritten'
];
}
/**
* bei Fehlern beim Import Datei in *_error umbenennen
* @param $event
*/
public function onImportFailed($event)
{
$failedResults = $event->getData();
if (!empty($failedResults) && !empty($failedResults[$this->marketplaceName])) {
$localFilesDir = $this->localFilesDir . '/Orders/input/';
foreach ($failedResults[$this->marketplaceName] as $order) {
if (!empty($order['file'])) {
$file = trim((string) $order['file'][0]);
rename($localFilesDir. $file, $localFilesDir . str_replace('.xml', '-error.xml', $file));
}
if (!empty($order->fileName)) {
$file = trim((string) $order->fileName[0]);
rename($localFilesDir. $file, $localFilesDir . str_replace('.xml', '-error.xml', $file));
}
}
}
}
/**
* das Speichern der Galaxus Order prüfen und bei Fehler Datei in *_error umbenennen bzw. bei Erfolg Datei löschen und Bestätigung erzeugen
* @param $event
*/
public function onExternalOrderWritten($event)
{
$order = $event->getData();
if ($order['marketplace'] === 'galaxus') {
$context = $event->getContext();
$ordernumber = $order['externalOrderNumber'];
$path = '/Orders/input/';
$localFilesDir = $this->localFilesDir . $path;
$allFiles = $this->client->getLocalFiles($path, $context);
$fileArray = $this->client->filterByOrdernumber($allFiles, $ordernumber);
if (count($fileArray) > 0) {
$fileName = $fileArray[0];
// Bestellbestätigung im Upload Ordner erzeugen und per Cronjob hochladen
$this->client->generateOrderResponse($order, $context);
// später unlink (löschen) der Datei
// rename($localFilesDir. $fileName, $localFilesDir . str_replace('.xml', '-completed.xml', $fileName));
unlink($localFilesDir. $fileName);
}
}
}
}