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\Formatter\FormatterInterface; 15use Monolog\Formatter\HtmlFormatter; 16 17/** 18 * Base class for all mail handlers 19 * 20 * @author Gyula Sallai 21 * 22 * @phpstan-import-type Record from \Monolog\Logger 23 */ 24abstract class MailHandler extends AbstractProcessingHandler 25{ 26 /** 27 * {@inheritDoc} 28 */ 29 public function handleBatch(array $records): void 30 { 31 $messages = []; 32 33 foreach ($records as $record) { 34 if ($record['level'] < $this->level) { 35 continue; 36 } 37 /** @var Record $message */ 38 $message = $this->processRecord($record); 39 $messages[] = $message; 40 } 41 42 if (!empty($messages)) { 43 $this->send((string) $this->getFormatter()->formatBatch($messages), $messages); 44 } 45 } 46 47 /** 48 * Send a mail with the given content 49 * 50 * @param string $content formatted email body to be sent 51 * @param array $records the array of log records that formed this content 52 * 53 * @phpstan-param Record[] $records 54 */ 55 abstract protected function send(string $content, array $records): void; 56 57 /** 58 * {@inheritDoc} 59 */ 60 protected function write(array $record): void 61 { 62 $this->send((string) $record['formatted'], [$record]); 63 } 64 65 /** 66 * @phpstan-param non-empty-array<Record> $records 67 * @phpstan-return Record 68 */ 69 protected function getHighestRecord(array $records): array 70 { 71 $highestRecord = null; 72 foreach ($records as $record) { 73 if ($highestRecord === null || $highestRecord['level'] < $record['level']) { 74 $highestRecord = $record; 75 } 76 } 77 78 return $highestRecord; 79 } 80 81 protected function isHtmlBody(string $body): bool 82 { 83 return ($body[0] ?? null) === '<'; 84 } 85 86 /** 87 * Gets the default formatter. 88 * 89 * @return FormatterInterface 90 */ 91 protected function getDefaultFormatter(): FormatterInterface 92 { 93 return new HtmlFormatter(); 94 } 95} 96