1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Handler;
13
14use Monolog\Logger;
15use Swift;
16use Swift_Message;
17
18/**
19 * MandrillHandler uses cURL to send the emails to the Mandrill API
20 *
21 * @author Adam Nicholson <adamnicholson10@gmail.com>
22 */
23class MandrillHandler extends MailHandler
24{
25    /** @var Swift_Message */
26    protected $message;
27    /** @var string */
28    protected $apiKey;
29
30    /**
31     * @psalm-param Swift_Message|callable(): Swift_Message $message
32     *
33     * @param string                 $apiKey  A valid Mandrill API key
34     * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced
35     */
36    public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true)
37    {
38        parent::__construct($level, $bubble);
39
40        if (!$message instanceof Swift_Message && is_callable($message)) {
41            $message = $message();
42        }
43        if (!$message instanceof Swift_Message) {
44            throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it');
45        }
46        $this->message = $message;
47        $this->apiKey = $apiKey;
48    }
49
50    /**
51     * {@inheritDoc}
52     */
53    protected function send(string $content, array $records): void
54    {
55        $mime = 'text/plain';
56        if ($this->isHtmlBody($content)) {
57            $mime = 'text/html';
58        }
59
60        $message = clone $this->message;
61        $message->setBody($content, $mime);
62        /** @phpstan-ignore-next-line */
63        if (version_compare(Swift::VERSION, '6.0.0', '>=')) {
64            $message->setDate(new \DateTimeImmutable());
65        } else {
66            /** @phpstan-ignore-next-line */
67            $message->setDate(time());
68        }
69
70        $ch = curl_init();
71
72        curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
73        curl_setopt($ch, CURLOPT_POST, 1);
74        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
75        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
76            'key' => $this->apiKey,
77            'raw_message' => (string) $message,
78            'async' => false,
79        ]));
80
81        Curl\Util::execute($ch);
82    }
83}
84