MandrillHandler.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Logger;
  12. /**
  13. * MandrillHandler uses cURL to send the emails to the Mandrill API
  14. *
  15. * @author Adam Nicholson <adamnicholson10@gmail.com>
  16. */
  17. class MandrillHandler extends MailHandler
  18. {
  19. protected $message;
  20. protected $apiKey;
  21. /**
  22. * @param string $apiKey A valid Mandrill API key
  23. * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
  24. * @param int $level The minimum logging level at which this handler will be triggered
  25. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  26. */
  27. public function __construct($apiKey, $message, $level = Logger::ERROR, $bubble = true)
  28. {
  29. parent::__construct($level, $bubble);
  30. if (!$message instanceof \Swift_Message && is_callable($message)) {
  31. $message = call_user_func($message);
  32. }
  33. if (!$message instanceof \Swift_Message) {
  34. throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it');
  35. }
  36. $this->message = $message;
  37. $this->apiKey = $apiKey;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. protected function send($content, array $records)
  43. {
  44. $message = clone $this->message;
  45. $message->setBody($content);
  46. $message->setDate(time());
  47. $ch = curl_init();
  48. curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
  49. curl_setopt($ch, CURLOPT_POST, 1);
  50. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  51. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
  52. 'key' => $this->apiKey,
  53. 'raw_message' => (string) $message,
  54. 'async' => false,
  55. )));
  56. Curl\Util::execute($ch);
  57. }
  58. }