| 1 |
<?php |
| 2 |
/** |
| 3 |
* WordPress mail handler for Monolog |
| 4 |
* |
| 5 |
* Handles all features of WordPress mail handler for Monolog. |
| 6 |
* |
| 7 |
* @package Handlers |
| 8 |
* @author Pierre Lannoy <https://pierre.lannoy.fr/>. |
| 9 |
* @since 1.0.0 |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Decalog\Handler; |
| 13 |
|
| 14 |
use Decalog\Plugin\Feature\EventTypes; |
| 15 |
use DLMonolog\Logger; |
| 16 |
use DLMonolog\Handler\AbstractProcessingHandler; |
| 17 |
use DLMonolog\Formatter\FormatterInterface; |
| 18 |
use Decalog\Formatter\NewlineFormatter; |
| 19 |
|
| 20 |
/** |
| 21 |
* Define the Monolog WordPress mail handler. |
| 22 |
* |
| 23 |
* Handles all features of WordPress mail handler for Monolog. |
| 24 |
* |
| 25 |
* @package Handlers |
| 26 |
* @author Pierre Lannoy <https://pierre.lannoy.fr/>. |
| 27 |
* @since 1.0.0 |
| 28 |
*/ |
| 29 |
class MailHandler extends AbstractProcessingHandler { |
| 30 |
|
| 31 |
/** |
| 32 |
* The recipients. |
| 33 |
* |
| 34 |
* @since 1.0.0 |
| 35 |
* @var array $recipients The recipients of the mail. |
| 36 |
*/ |
| 37 |
private $recipients = ''; |
| 38 |
|
| 39 |
/** |
| 40 |
* Initialize the class and set its properties. |
| 41 |
* |
| 42 |
* @param string $recipients The recipients coma separated list. |
| 43 |
* @param integer $level Optional. The min level to log. |
| 44 |
* @param boolean $bubble Optional. Has the record to bubble?. |
| 45 |
* @since 1.0.0 |
| 46 |
*/ |
| 47 |
public function __construct( string $recipients, $level = Logger::DEBUG, bool $bubble = true ) { |
| 48 |
parent::__construct( $level, $bubble ); |
| 49 |
$this->recipients = explode( ',', $recipients ); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* {@inheritDoc} |
| 54 |
*/ |
| 55 |
protected function getDefaultFormatter(): FormatterInterface { |
| 56 |
return new NewlineFormatter(); |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Send the record by mail. |
| 61 |
* |
| 62 |
* @param array $record The record to send. |
| 63 |
* @since 1.0.0 |
| 64 |
*/ |
| 65 |
protected function write( array $record ): void { |
| 66 |
if ( array_key_exists( 'level', $record ) && array_key_exists( $record['level'], EventTypes::$level_names ) ) { |
| 67 |
$level = EventTypes::$level_names[ $record['level'] ]; |
| 68 |
} else { |
| 69 |
$level = ''; |
| 70 |
} |
| 71 |
$subject = sprintf( 'DecaLog: %s', $level ); |
| 72 |
if ( array_key_exists( 'extra', $record ) && array_key_exists( 'sitename', $record['extra'] ) ) { |
| 73 |
$subject .= sprintf( ' on %s', $record['extra']['sitename'] ); |
| 74 |
} |
| 75 |
wp_mail( $this->recipients, $subject, $record['formatted'] ); |
| 76 |
|
| 77 |
} |
| 78 |
} |
| 79 |
|