Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions src/EventListener/ShippingExportEventListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@
use Waaz\SyliusTntPlugin\Api\ShippingLabelFetcherInterface;
use Webmozart\Assert\Assert;

class ShippingExportEventListener
/**
* This listener overrides the one from waaz/sylius-tnt-plugin to gracefully handle
* TNT validation errors: it catches exceptions and avoids asserting on absent labels,
* while letting the fetcher add precise flash error messages for the user.
*/
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener(event: 'bitbag.shipping_export.export_shipment', method: 'exportShipment')]
final class ShippingExportEventListener
{
public const TNT_GATEWAY_CODE = 'tnt';

Expand All @@ -39,16 +47,27 @@ public function exportShipment(ResourceControllerEvent $event): void
$shipment = $shippingExport->getShipment();
Assert::isInstanceOf($shipment, ShipmentInterface::class);

$this->shippingLabelFetcher->createShipment($shippingGateway, $shipment);
try {
$this->shippingLabelFetcher->createShipment($shippingGateway, $shipment);
} catch (\Throwable $e) {
return;
}

$labelContent = $this->shippingLabelFetcher->getLabelContent();
Assert::stringNotEmpty($labelContent);
try {
$labelContent = $this->shippingLabelFetcher->getLabelContent();
} catch (\Throwable $e) {
return;
}

if (!\is_string($labelContent) || '' === trim($labelContent)) {
return;
}

$this->saveShippingLabel($shippingExport, $labelContent, 'pdf'); // Save label
$this->markShipmentAsExported($shippingExport); // Mark shipment as "Exported"
$this->saveShippingLabel($shippingExport, $labelContent, 'pdf');
$this->markShipmentAsExported($shippingExport);
}

public function saveShippingLabel(
private function saveShippingLabel(
ShippingExportInterface $shippingExport,
string $labelContent,
string $labelExtension,
Expand Down Expand Up @@ -81,7 +100,7 @@ private function getFilename(ShippingExportInterface $shippingExport): string
'_',
[
$shipmentId,
preg_replace('~[^A-Za-z0-9]~', '', $orderNumber),
(string) preg_replace('~[^A-Za-z0-9]~', '', $orderNumber),
],
);
}
Expand Down