Shopware6 : creation of custom event

Situation : We have a plugin which is creating an invoice for all new orders when they are paid. We need to get the number of this invoice and send it to another system (This second step is managed by another of our plugins).

So I tried to create a custom event in this invoice generation plugin which should logically trigger JUST AFTER the creation of this invoice.

After following this tutorial to create a custom event within a plugin : https://symfony.com/doc/current/components/event_dispatcher.html#creating-and-dispatching-an-event.

I am not able to make my event trigger. It’s like my event was not created.

My custom event is called "InvoiceGeneratedEvent".

Here is the controller of the invoice generation plugin:

<?php

declare(strict_types=1);

namespace HmDocumentGeneratorPluginController;

use HmDocumentGeneratorPluginServiceHmOrderService;
use HmDocumentGeneratorPluginEventInvoiceGeneratedEvent;
use HmDocumentGeneratorPluginSubscriberOrderSubscriber;
use ShopwareCoreCheckoutOrderOrderEntity;
use ShopwareCoreFrameworkContext;
use ShopwareCoreFrameworkDataAbstractionLayerEntityRepositoryInterface;
use ShopwareCoreFrameworkDataAbstractionLayerSearchCriteria;
use ShopwareCoreFrameworkRoutingAnnotationRouteScope;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyContractsEventDispatcherEventDispatcherInterface;

/**
 * @RouteScope(scopes={"api"})
 */
class HmDocumentController extends AbstractController
{
    /**
     * @var HmOrderService
     */
    private $hmOrderService;

    /**
     * @var EntityRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;


    /**
     * HmDocumentController constructor.
     */
    public function __construct(HmOrderService $hmOrderService, EntityRepositoryInterface $orderRepository, EventDispatcherInterface $eventDispatcher)
    {
        $this->hmOrderService = $hmOrderService;
        $this->orderRepository = $orderRepository;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @Route("/api/{version}/_action/hm-document/generate", name="api.action.hm.document.generate", methods={"POST"},
     *     defaults={"XmlHttpRequest"=true})
     */
    public function generate(Request $request, Context $context): JsonResponse
    {
        $orderIds = $request->get('orderIds');

        /** @var OrderEntity[] $orders */
        $orders = $this->orderRepository->search(new Criteria($orderIds), $context)->getEntities();
        
        $total = 0;
        foreach ($orders as $order) {
            $total += $this->hmOrderService->generateDocuments($order);
            $event = new InvoiceGeneratedEvent($orders);
            $this->eventDispatcher->dispatch($event, InvoiceGeneratedEvent::NAME);
            var_dump($order);
            die('bam');
        }

        return new JsonResponse(
            ['data' => sprintf('%d new document(s) generated in %d order(s)', $total, count($orderIds))]
        );
    }
}

Here is the InvoiceGeneratedEvent.php

<?php

declare(strict_types=1);

namespace HmDocumentGeneratorPluginEvent;

use HmDocumentGeneratorPluginServiceHmOrderService;
use ShopwareCoreCheckoutCartEventCheckoutOrderPlacedEvent;
use ShopwareCoreCheckoutOrderOrderEntity;
//use SymfonyComponentEventDispatcherEvent;
use SymfonyContractsEventDispatcherEvent;

/**
 * The invoice.generated event is dispatched each time a document is created
 * after the successful payment of a new order
 */
class InvoiceGeneratedEvent extends Event
{
    public const NAME = 'invoice.generated';

    protected $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    public function getOrder()
    {
    return $this->order;
    }

}

Here is the subscriber

<?php

declare(strict_types=1);

namespace HmDocumentGeneratorPluginSubscriber;

use HmDocumentGeneratorPluginServiceHmOrderService;
use ShopwareCoreCheckoutCartEventCheckoutOrderPlacedEvent;
use HmDocumentGeneratorPluginEventInvoiceGeneratedEvent;
use ShopwareCoreCheckoutOrderOrderEntity;
use SymfonyComponentEventDispatcherEventSubscriberInterface;

class OrderSubscriber implements EventSubscriberInterface
{
    /**
     * @var HmOrderService
     */
    private $service;

    public function __construct(HmOrderService $service)
    {
        $this->service = $service;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
            InvoiceGeneratedEvent::NAME => 'onInvoiceGenerated',
        ];
    }

    public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
    {
        $order = $event->getOrder();

        if ($order instanceof OrderEntity) {
            $this->service->generateDocuments($order);
        }
    }

    public function onInvoiceGenerated(InvoiceGeneratedEvent $event)
    {
        var_dump($event);
        die('boum');
    }
}

Am I missing something there?

EDIT : Here is my services.xml in which I have correctly added the ‘kernel.event_subscriber’

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="HmDocumentGeneratorPluginSubscriberOrderSubscriber">
            <argument id="HmDocumentGeneratorPluginServiceHmOrderService" type="service" />
            <tag name="kernel.event_subscriber" />
            <tag name="kernel.event_listener" />
        </service>

        <service id="HmDocumentGeneratorPluginServiceHmDocumentService">
            <argument type="service"
                      id="ShopwareCoreSystemNumberRangeValueGeneratorNumberRangeValueGeneratorInterface" />
            <argument type="service" id="ShopwareCoreCheckoutDocumentDocumentService" />
            <argument type="service" id="document.repository" />
        </service>

        <service id="HmDocumentGeneratorPluginControllerHmDocumentController">
            <call method="setContainer">
                <argument id="service_container" type="service" />
            </call>
            <tag name="controller.service_arguments" />
            <argument type="service" id="HmDocumentGeneratorPluginServiceHmOrderService" />
            <argument type="service" id="order.repository" />
        </service>
    </services>
</container>

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *