~thirdplace/components

22dabc2fccdb2aeaa807b85e67a590b342dc554e — Dag 1 year, 1 month ago 737d1c0
feat: add mailgun handler
1 files changed, 64 insertions(+), 0 deletions(-)

A src/logger/MailgunHandler.php
A src/logger/MailgunHandler.php => src/logger/MailgunHandler.php +64 -0
@@ 0,0 1,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");
        }
    }
}