<?php
/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace Ibexa\Bundle\Shipping\EventSubscriber\Notification;
use Ibexa\Contracts\Notifications\Service\NotificationServiceInterface;
use Ibexa\Contracts\Notifications\Value\Notification\SymfonyNotificationAdapter;
use Ibexa\Contracts\Notifications\Value\Recipent\SymfonyRecipientAdapter;
use Ibexa\Contracts\Shipping\Notification\ShipmentStatusChange;
use Ibexa\Contracts\Shipping\Shipment\ShipmentInterface;
use Ibexa\Shipping\Workflow\WorkflowConfigurationInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Workflow\Event\EnteredEvent;
use Symfony\Component\Workflow\WorkflowEvents;
final class TriggerNotificationsSubscriber implements EventSubscriberInterface
{
private WorkflowConfigurationInterface $workflowConfiguration;
private NotificationServiceInterface $notificationService;
public function __construct(
WorkflowConfigurationInterface $workflowConfiguration,
NotificationServiceInterface $notificationService
) {
$this->workflowConfiguration = $workflowConfiguration;
$this->notificationService = $notificationService;
}
public static function getSubscribedEvents(): array
{
return [
WorkflowEvents::ENTERED => [['onWorkflowEntered', -10]],
];
}
public function onWorkflowEntered(EnteredEvent $event): void
{
$workflow = $event->getWorkflow();
$shipmentWorkflow = $this->workflowConfiguration->getConfiguredWorkflowName();
if ($shipmentWorkflow !== $workflow->getName()) {
return;
}
$shipment = $event->getSubject();
if (!$shipment instanceof ShipmentInterface) {
return;
}
$metadata = $workflow
->getMetadataStore()
->getPlaceMetadata($shipment->getStatus());
$triggerNotification = $metadata['trigger_notification'] ?? false;
if (!$triggerNotification) {
return;
}
$transition = $event->getTransition();
$marking = $event->getMarking();
$context = $event->getContext();
$user = $shipment->getOrder()->getUser();
$this->notificationService->send(
new SymfonyNotificationAdapter(
new ShipmentStatusChange(
$shipment,
$workflow,
$transition,
$marking,
$context,
)
),
[new SymfonyRecipientAdapter(new Recipient($user->getEmail()))],
);
}
}