Skip to content

Commit 1ecab04

Browse files
authored
Merge pull request #6 from inextensodigital/simplify-handler-declaration
Simplify command handlers declaration
2 parents ce8275a + 9c394e0 commit 1ecab04

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

DependencyInjection/Compiler/CommandHandlerPass.php

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,13 @@ public function process(ContainerBuilder $container)
2323

2424
foreach ($container->findTaggedServiceIds('rezzza_command_bus.command_handler') as $serviceId => $handlers) {
2525
foreach ($handlers as $data) {
26-
if (!isset($data['command'])) {
26+
$command = $this->getCommand($serviceId, $handlers, $data);
27+
28+
if (null === $command) {
2729
throw new \LogicException('Please provide a command with "rezzza_command.command_handler" tag');
2830
}
2931

30-
$services[$data['command']] = new Definition('Rezzza\CommandBusBundle\Handler\HandlerServiceDefinition', [
32+
$services[$command] = new Definition('Rezzza\CommandBusBundle\Handler\HandlerServiceDefinition', [
3133
$serviceId,
3234
isset($data['method']) ? $data['method'] : null
3335
]);
@@ -36,4 +38,28 @@ public function process(ContainerBuilder $container)
3638

3739
$container->getDefinition('rezzza_command_bus.command_handler_locator.container')->addArgument($services);
3840
}
41+
42+
private function getCommand(string $serviceId, array $handlers, array $data): ?string
43+
{
44+
if (isset($data['command'])) {
45+
return $data['command'];
46+
}
47+
48+
// if no command is defined the handler should manage only one command
49+
if (1 < \count($handlers)) {
50+
return null;
51+
}
52+
53+
$command = $this->guessCommandFromHandlerName($serviceId);
54+
55+
return class_exists($command) ? $command : null;
56+
}
57+
58+
private function guessCommandFromHandlerName(string $handler): string
59+
{
60+
$parts = preg_split('/(?=[A-Z])/',$handler);
61+
array_pop($parts);
62+
63+
return implode('', $parts);
64+
}
3965
}

0 commit comments

Comments
 (0)