@@ 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");
+ }
+ }
+}