1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Cubiche package. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) Cubiche |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Cubiche\Core\Bus\Middlewares\Handler; |
13
|
|
|
|
14
|
|
|
use Cubiche\Core\Bus\MessageInterface; |
15
|
|
|
use Cubiche\Core\Bus\Middlewares\Handler\Resolver\HandlerClass\ResolverInterface; |
16
|
|
|
use Cubiche\Core\Bus\Middlewares\MiddlewareInterface; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* MessageHandlerMiddleware class. |
20
|
|
|
* |
21
|
|
|
* @author Ivannis Suárez Jerez <[email protected]> |
22
|
|
|
*/ |
23
|
|
|
class MessageHandlerMiddleware implements MiddlewareInterface |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @var ResolverInterface |
27
|
|
|
*/ |
28
|
|
|
protected $handlerClassResolver; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* MessageHandlerMiddleware constructor. |
32
|
|
|
* |
33
|
|
|
* @param ResolverInterface $handlerClassResolver |
34
|
|
|
*/ |
35
|
|
|
public function __construct(ResolverInterface $handlerClassResolver) |
36
|
|
|
{ |
37
|
|
|
$this->handlerClassResolver = $handlerClassResolver; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* {@inheritdoc} |
42
|
|
|
*/ |
43
|
|
|
public function handle($message, callable $next) |
44
|
|
|
{ |
45
|
|
|
$this->ensureTypeOfMessage($message); |
46
|
|
|
$handler = $this->handlerClassResolver->resolve($message); |
47
|
|
|
|
48
|
|
|
$handler($message); |
49
|
|
|
$next($message); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @return ResolverInterface |
54
|
|
|
*/ |
55
|
|
|
public function resolver() |
56
|
|
|
{ |
57
|
|
|
return $this->handlerClassResolver; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param mixed $message |
62
|
|
|
* |
63
|
|
|
* @throws \InvalidArgumentException |
64
|
|
|
*/ |
65
|
|
|
protected function ensureTypeOfMessage($message) |
66
|
|
|
{ |
67
|
|
|
if (!$message instanceof MessageInterface) { |
68
|
|
|
throw new \InvalidArgumentException( |
69
|
|
|
sprintf( |
70
|
|
|
'The object must be an instance of %s. Instance of %s given', |
71
|
|
|
MessageInterface::class, |
72
|
|
|
get_class($message) |
73
|
|
|
) |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|