Skip to content

Commit df63934

Browse files
authored
Integrate middleware sorting (#20)
1 parent e6c3668 commit df63934

2 files changed

Lines changed: 28 additions & 6 deletions

File tree

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"illuminate/support": ">=6.0",
1313
"illuminate/console": ">=6.0",
1414
"illuminate/redis": ">=6.0",
15-
"onliner/command-bus": "^1.1.5"
15+
"onliner/command-bus": "^1.1.6"
1616
},
1717
"require-dev": {
1818
"predis/predis": "^2.0.2"

src/Providers/CommandBusProvider.php

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,14 @@ public function boot(): void
4242

4343
public function register(): void
4444
{
45+
$middlewares = $this->middlewares();
46+
4547
$this->app->tag($this->config('extensions'), [self::TAG_EXTENSION]);
46-
$this->app->tag($this->config('middlewares'), [self::TAG_MIDDLEWARE]);
48+
$this->app->tag(array_keys($middlewares), [self::TAG_MIDDLEWARE]);
4749

4850
$this->registerRemote($this->config('remote'));
4951
$this->registerRetries($this->config('retries'));
50-
$this->registerDispatcher($this->config('handlers'));
52+
$this->registerDispatcher($this->config('handlers'), $middlewares);
5153
}
5254

5355
/**
@@ -153,10 +155,11 @@ private function registerRetries(array $config): void
153155

154156
/**
155157
* @param array<string, string> $handlers
158+
* @param array<string, int> $middlewares
156159
*/
157-
private function registerDispatcher(array $handlers): void
160+
private function registerDispatcher(array $handlers, array $middlewares): void
158161
{
159-
$this->app->singleton(Dispatcher::class, function (Container $app) use ($handlers) {
162+
$this->app->singleton(Dispatcher::class, function (Container $app) use ($handlers, $middlewares) {
160163
$builder = new Builder();
161164

162165
foreach ($handlers as $command => $class) {
@@ -171,13 +174,32 @@ private function registerDispatcher(array $handlers): void
171174
}
172175

173176
foreach ($app->tagged(self::TAG_MIDDLEWARE) as $middleware) {
174-
$builder->middleware($middleware);
177+
$builder->middleware($middleware, $middlewares[get_class($middleware)] ?? 0);
175178
}
176179

177180
return $builder->build();
178181
});
179182
}
180183

184+
/**
185+
* @return array<string, int>
186+
*/
187+
private function middlewares(): array
188+
{
189+
$config = $this->config('middlewares');
190+
$middlewares = [];
191+
192+
foreach ($config as $key => $value) {
193+
if (is_string($key) && is_int($value)) {
194+
$middlewares[$key] = $value;
195+
} elseif (is_string($value) && is_int($key)) {
196+
$middlewares[$value] = $key;
197+
}
198+
}
199+
200+
return $middlewares;
201+
}
202+
181203
private function config(string $section): array
182204
{
183205
return $this->app->get('config')->get('commandbus.' . $section, []);

0 commit comments

Comments
 (0)