<?php
declare(strict_types=1);
namespace Vio\B2BWorkflow\Core\Framework\Subscriber;
use ReflectionClass;
use ReflectionException;
use RuntimeException;
use Shopware\Core\Framework\Event\BusinessEventCollectorEvent;
use Shopware\Core\Framework\Event\BusinessEventDefinition;
use Shopware\Core\Framework\Event\BusinessEventInterface;
use Shopware\Core\Framework\Event\FlowEventAware;
use Shopware\Core\Framework\Event\MailActionInterface;
use Shopware\Core\Framework\Event\SalesChannelAware;
use Shopware\Core\Framework\Feature;
use Shopware\Core\Framework\Log\LogAwareBusinessEventInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Vio\B2BWorkflow\Core\Checkout\Cart\Event\CheckoutCustomerOrderRequestPlacedEvent;
use Vio\B2BWorkflow\Core\Checkout\Cart\Event\CheckoutEmployeeOrderRequestPlacedEvent;
class BusinessSubscriber implements EventSubscriberInterface
{
public const EVENTS = [
CheckoutEmployeeOrderRequestPlacedEvent::class,
CheckoutCustomerOrderRequestPlacedEvent::class
];
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
BusinessEventCollectorEvent::NAME => 'onCollectBusinessEvents'
];
}
/**
* @throws ReflectionException
*/
public function onCollectBusinessEvents(BusinessEventCollectorEvent $event): void
{
// add BusinessEvents
foreach (self::EVENTS as $eventClassName) {
$definition = $this->createDefinition($eventClassName);
$event->getCollection()->set($definition->getName(), $definition);
}
}
/**
* @throws ReflectionException
*/
private function createDefinition(string $eventClassName): BusinessEventDefinition
{
$reflectionClass = new ReflectionClass($eventClassName);
if (Feature::isActive('FEATURE_NEXT_17858')) {
if (!$reflectionClass->implementsInterface(FlowEventAware::class)) {
throw new RuntimeException(sprintf('Event %s is not a business event', $eventClassName));
}
} else if (!$reflectionClass->implementsInterface(BusinessEventInterface::class)) {
throw new RuntimeException(sprintf('Event %s is not a business event', $eventClassName));
}
$aware = array_keys(array_filter($reflectionClass->getInterfaces(), static function (ReflectionClass $interface) {
return $interface->isSubclassOf(FlowEventAware::class);
})
);
$instance = $reflectionClass->newInstanceWithoutConstructor();//NOSONAR
$name = $instance->getName();
return new BusinessEventDefinition(
$name,
$eventClassName,
$instance instanceof MailActionInterface,
$instance instanceof LogAwareBusinessEventInterface,
$instance instanceof SalesChannelAware,
$instance::getAvailableData()->toArray(),
$aware
);
}
}