~thirdplace/components

6a3766c7585717df15ae9ebdd29ac4375a89dab3 — Dag 1 year, 1 month ago 22dabc2
refactor: mailgun handler
1 files changed, 13 insertions(+), 28 deletions(-)

M src/logger/MailgunHandler.php
M src/logger/MailgunHandler.php => src/logger/MailgunHandler.php +13 -28
@@ 6,23 6,14 @@ namespace Thirdplace;
final class MailgunHandler
{
    private HttpClient $client;
    private string $apiDomain;
    private string $apiKey;
    private string $from;
    private string $to;
    private array $config;

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

    public function __invoke(array $record): void


@@ 30,31 21,25 @@ final class MailgunHandler
        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",
        $subject = sprintf(
            "[%s] %s.%s %s",
            $record['created_at']->format('Y-m-d H:i:s'),
            $record['name'],
            $record['level_name'],
            str_replace(["\n", "\r"], '\n', $record['message']),
            $record['context']
            str_replace(["\n", "\r"], '\n', $record['message'])
        );
        $url = sprintf('https://api.mailgun.net/v3/%s/messages', $this->apiDomain);
        $context = Json::encode($record['context']) ?: '["Unable to json encode context"]';
        $url = sprintf('https://api.mailgun.net/v3/%s/messages', $this->config['domain']);
        $response = $this->client->request('POST', $url, [
            'auth' => [
                'user' => 'api',
                'pass' => $this->apiKey,
                'pass' => $this->config['key'],
            ],
            'body' => [
                'from'      => $this->from,
                'to'        => $this->to,
                'subject'   => $text,
                'text'      => $text,
                'from'      => $this->config['from'],
                'to'        => $this->config['to'],
                'subject'   => truncate($subject),
                'text'      => "$subject\n$context",
            ],
        ]);
        if ($response->code !== 200) {