|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Pageon\SlackWebhookMonolog\Monolog; |
|
4
|
|
|
|
|
5
|
|
|
use Monolog\Handler\AbstractHandler; |
|
6
|
|
|
use Monolog\Handler\AbstractProcessingHandler; |
|
7
|
|
|
use Monolog\Handler\MissingExtensionException; |
|
8
|
|
|
use Monolog\Handler\SocketHandler; |
|
9
|
|
|
use Pageon\SlackWebhookMonolog\Monolog\Interfaces\ConfigInterface as MonologConfig; |
|
10
|
|
|
use Pageon\SlackWebhookMonolog\Slack\Interfaces\ConfigInterface as SlackConfig; |
|
11
|
|
|
use Monolog\Handler\Curl; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @author Jelmer Prins <[email protected]> |
|
15
|
|
|
* |
|
16
|
|
|
* @since 0.1.0 |
|
17
|
|
|
*/ |
|
18
|
|
|
class SlackWebhookHandler extends AbstractProcessingHandler |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* @var SlackConfig |
|
22
|
|
|
*/ |
|
23
|
|
|
private $slackConfig; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var MonologConfig |
|
27
|
|
|
*/ |
|
28
|
|
|
private $monologConfig; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* SlackWebhookHandler constructor. |
|
32
|
|
|
* |
|
33
|
|
|
* @param SlackConfig $slackConfig |
|
34
|
|
|
* @param MonologConfig $monologConfig |
|
35
|
|
|
* |
|
36
|
|
|
* @throws MissingExtensionException When the curl extension is not activated |
|
37
|
|
|
*/ |
|
38
|
|
|
public function __construct(SlackConfig $slackConfig, MonologConfig $monologConfig) |
|
39
|
|
|
{ |
|
40
|
|
|
if (!in_array('curl', get_loaded_extensions())) { |
|
41
|
|
|
throw new MissingExtensionException('The curl extension is required to use the SlackHandler'); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
$this->slackConfig = $slackConfig; |
|
45
|
|
|
$this->monologConfig = $monologConfig; |
|
46
|
|
|
|
|
47
|
|
|
parent::__construct($monologConfig->getLevel(), $monologConfig->doesBubble()); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* {@inheritdoc} |
|
52
|
|
|
*/ |
|
53
|
|
|
public function write(array $record) |
|
54
|
|
|
{ |
|
55
|
|
|
|
|
56
|
|
|
$ch = curl_init(); |
|
57
|
|
|
curl_setopt($ch, CURLOPT_URL, $this->slackConfig->getWebhook()); |
|
58
|
|
|
curl_setopt($ch, CURLOPT_POST, true); |
|
59
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
60
|
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->prepareContentData($record)); |
|
61
|
|
|
|
|
62
|
|
|
Curl\Util::execute($ch); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Prepares content data. |
|
67
|
|
|
* |
|
68
|
|
|
* @param array $record |
|
69
|
|
|
* |
|
70
|
|
|
* @return array |
|
71
|
|
|
*/ |
|
72
|
|
|
private function prepareContentData($record) |
|
73
|
|
|
{ |
|
74
|
|
|
$payload = [ |
|
75
|
|
|
'text' => $record['message'], |
|
76
|
|
|
]; |
|
77
|
|
|
|
|
78
|
|
|
return [ |
|
79
|
|
|
'payload' => json_encode($payload), |
|
80
|
|
|
]; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|