1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Chief\Decorators; |
4
|
|
|
|
5
|
|
|
use Chief\Busses\SynchronousCommandBus; |
6
|
|
|
use Chief\Command; |
7
|
|
|
use Chief\CommandBus; |
8
|
|
|
use Chief\Decorator; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
|
11
|
|
|
class LoggingDecorator implements Decorator |
12
|
|
|
{ |
13
|
|
|
use InnerBusTrait; |
14
|
|
|
/** |
15
|
|
|
* @var LoggerInterface |
16
|
|
|
*/ |
17
|
|
|
protected $logger; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var mixed|null |
21
|
|
|
*/ |
22
|
|
|
protected $context; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param LoggerInterface $logger |
26
|
|
|
* @param mixed $context Something which is serializable that will be logged with |
27
|
|
|
* the command execution, such as the request/session information. |
28
|
|
|
* @param CommandBus $innerCommandBus |
29
|
|
|
*/ |
30
|
|
|
public function __construct(LoggerInterface $logger, $context = null, CommandBus $innerCommandBus = null) |
31
|
|
|
{ |
32
|
|
|
$this->logger = $logger; |
33
|
|
|
$this->context = $context; |
34
|
|
|
$this->setInnerBus($innerCommandBus ?: new SynchronousCommandBus()); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Execute a command |
39
|
|
|
* |
40
|
|
|
* @param Command $command |
41
|
|
|
* @throws \Exception |
42
|
|
|
* @return mixed |
43
|
|
|
*/ |
44
|
|
|
public function execute(Command $command) |
45
|
|
|
{ |
46
|
|
|
$this->log('Executing command [' . get_class($command) . ']', $command); |
47
|
|
|
|
48
|
|
|
try { |
49
|
|
|
$response = $this->innerCommandBus->execute($command); |
50
|
|
|
} catch (\Exception $e) { |
51
|
|
|
|
52
|
|
|
$message = 'Failed executing command [' . get_class($command) . ']. ' . $this->createExceptionString($e); |
53
|
|
|
$this->log($message, $command); |
54
|
|
|
throw $e; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$this->log('Successfully executed command [' . get_class($command) . ']', $command); |
58
|
|
|
|
59
|
|
|
return $response; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
protected function log($message, $command) |
63
|
|
|
{ |
64
|
|
|
$context = $this->context ? serialize($this->context) : null; |
65
|
|
|
$this->logger->debug($message, ['Command' => serialize($command), 'Context' => $context]); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
protected function createExceptionString(\Exception $e) |
69
|
|
|
{ |
70
|
|
|
return 'Uncaught ' . get_class($e) . '[' . $e->getMessage() . '] throw in ' . $e->getFile() . |
71
|
|
|
' on line ' . $e->getLine() . '. Stack trace: ' . $e->getTraceAsString(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|