Skip to content

Commit a6c892b

Browse files
committed
Add CommandHandlerAbstract with command type validation
1 parent 0821a99 commit a6c892b

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
declare(strict_types=1);
3+
/**
4+
* @author Julien Mercier-Rojas <julien@jeckel-lab.fr>
5+
* Created at : 14/11/2019
6+
*/
7+
8+
namespace JeckelLab\CommandDispatcher\CommandHandler;
9+
10+
use JeckelLab\CommandDispatcher\Command\CommandInterface;
11+
use JeckelLab\CommandDispatcher\Exception\InvalidCommandException;
12+
13+
/**
14+
* Class CommandHandlerAbstract
15+
* @package JeckelLab\CommandDispatcher\CommandHandler
16+
*/
17+
abstract class CommandHandlerAbstract implements CommandHandlerInterface
18+
{
19+
/**
20+
* @param CommandInterface $command
21+
* @throws InvalidCommandException
22+
*/
23+
protected function validateCommand(CommandInterface $command): void
24+
{
25+
foreach (self::getHandledCommands() as $handledCommand) {
26+
if ($command instanceof $handledCommand) {
27+
return;
28+
}
29+
}
30+
throw new InvalidCommandException(sprintf(
31+
'Invalid command "%s" provided to handler.',
32+
get_class($command)
33+
));
34+
}
35+
}

src/CommandHandler/CommandHandlerInterface.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
use JeckelLab\CommandDispatcher\Command\CommandInterface;
1111
use JeckelLab\CommandDispatcher\CommandResponse\CommandResponseInterface;
12+
use JeckelLab\CommandDispatcher\Exception\InvalidCommandException;
1213

1314
/**
1415
* Interface CommandHandlerInterface
@@ -24,6 +25,7 @@ public static function getHandledCommands(): array;
2425
/**
2526
* @param CommandInterface $command
2627
* @return CommandResponseInterface
28+
* @throws InvalidCommandException
2729
*/
2830
public function __invoke(CommandInterface $command): CommandResponseInterface;
2931
}

0 commit comments

Comments
 (0)