13 private array $middleware = [];
15 private ObjectFactory $objectFactory;
16 private array $middlewareSpecs;
17 private bool $loadedFromSpecs =
false;
19 private bool $isProcessing =
false;
21 public function __construct( ObjectFactory $objectFactory, array $specs ) {
22 $this->objectFactory = $objectFactory;
23 $this->middlewareSpecs = $specs;
27 if ( $this->isProcessing ) {
31 "Middleware cannot re-trigger the notification processing while it is already in progress. "
34 $this->isProcessing =
true;
36 if ( !$this->loadedFromSpecs ) {
37 foreach ( $this->middlewareSpecs as $spec ) {
38 $this->middleware[] = $this->objectFactory->createObject( $spec, [
39 'assertClass' => NotificationMiddlewareInterface::class
42 $this->loadedFromSpecs =
true;
45 $this->callNext( $batch, 0 );
46 $this->isProcessing =
false;
50 private function callNext( NotificationsBatch $batch,
int $index ): void {
51 if ( $index < count( $this->middleware ) ) {
52 $this->middleware[$index]->handle(
54 function () use ( $batch, $index ) {
55 $this->callNext( $batch, $index + 1 );