~thirdplace/components

ref: 22dabc2fccdb2aeaa807b85e67a590b342dc554e components/src/logger/MailgunHandler.php -rwxr-xr-x 1.8 KiB
22dabc2fDag feat: add mailgun handler 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types=1);

namespace Thirdplace;

final class MailgunHandler
{
    private HttpClient $client;
    private string $apiDomain;
    private string $apiKey;
    private string $from;
    private string $to;

    public function __construct(
        HttpClient $client,
        string $apiDomain,
        string $apiKey,
        string $from,
        string $to
    ) {
        $this->client = $client;
        $this->apiDomain = $apiDomain;
        $this->apiKey = $apiKey;
        $this->from = $from;
        $this->to = $to;
    }

    public function __invoke(array $record): void
    {
        if (isset($record['context']['e'])) {
            $record['context']['e'] = create_sane_stacktrace($record['context']['e']);
        }
        if ($record['context'] === []) {
            $record['context'] = '';
        } else {
            $json = Json::encode($record['context']) ?: '["Unable to json encode context"]';
            $record['context'] = $json;
        }
        $text = sprintf(
            "[%s] %s.%s %s %s\n",
            $record['created_at']->format('Y-m-d H:i:s'),
            $record['name'],
            $record['level_name'],
            str_replace(["\n", "\r"], '\n', $record['message']),
            $record['context']
        );
        $url = sprintf('https://api.mailgun.net/v3/%s/messages', $this->apiDomain);
        $response = $this->client->request('POST', $url, [
            'auth' => [
                'user' => 'api',
                'pass' => $this->apiKey,
            ],
            'body' => [
                'from'      => $this->from,
                'to'        => $this->to,
                'subject'   => $text,
                'text'      => $text,
            ],
        ]);
        if ($response->code !== 200) {
            throw new \Exception("MailgunHandler: $response->body");
        }
    }
}