1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-05 12:47:39 +02:00

Wrap up type-hint adding to all handlers

This commit is contained in:
Jordi Boggiano
2018-11-19 23:28:33 +01:00
parent 1c5b0b8ff4
commit 4a33226f25
47 changed files with 338 additions and 352 deletions

View File

@@ -30,14 +30,18 @@ class LogmaticFormatter extends JsonFormatter
*/ */
protected $appname = ''; protected $appname = '';
public function setHostname(string $hostname) public function setHostname(string $hostname): self
{ {
$this->hostname = $hostname; $this->hostname = $hostname;
return $this;
} }
public function setAppname(string $appname) public function setAppname(string $appname): self
{ {
$this->appname = $appname; $this->appname = $appname;
return $this;
} }
/** /**

View File

@@ -67,9 +67,11 @@ class NormalizerFormatter implements FormatterInterface
return $this->maxNormalizeDepth; return $this->maxNormalizeDepth;
} }
public function setMaxNormalizeDepth(int $maxNormalizeDepth): void public function setMaxNormalizeDepth(int $maxNormalizeDepth): self
{ {
$this->maxNormalizeDepth = $maxNormalizeDepth; $this->maxNormalizeDepth = $maxNormalizeDepth;
return $this;
} }
/** /**
@@ -80,9 +82,11 @@ class NormalizerFormatter implements FormatterInterface
return $this->maxNormalizeItemCount; return $this->maxNormalizeItemCount;
} }
public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): void public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self
{ {
$this->maxNormalizeItemCount = $maxNormalizeItemCount; $this->maxNormalizeItemCount = $maxNormalizeItemCount;
return $this;
} }
/** /**

View File

@@ -54,7 +54,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
]; ];
/** /**
* @param mixed $facility * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param string|int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */

View File

@@ -80,13 +80,15 @@ class CubeHandler extends AbstractProcessingHandler
} }
/** /**
* Establish a connection to a http server * Establish a connection to an http server
* @throws \LogicException when no curl extension *
* @throws \LogicException when unable to connect to the socket
* @throws MissingExtensionException when no curl extension
*/ */
protected function connectHttp(): void protected function connectHttp(): void
{ {
if (!extension_loaded('curl')) { if (!extension_loaded('curl')) {
throw new \LogicException('The curl extension is needed to use http URLs with the CubeHandler'); throw new MissingExtensionException('The curl extension is required to use http URLs with the CubeHandler');
} }
$this->httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put'); $this->httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put');

View File

@@ -41,11 +41,11 @@ class FleepHookHandler extends SocketHandler
* see https://fleep.io/integrations/webhooks/ * see https://fleep.io/integrations/webhooks/
* *
* @param string $token Webhook token * @param string $token Webhook token
* @param bool|int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @throws MissingExtensionException * @throws MissingExtensionException
*/ */
public function __construct($token, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler');
@@ -71,8 +71,6 @@ class FleepHookHandler extends SocketHandler
/** /**
* Handles a log record * Handles a log record
*
* @param array $record
*/ */
public function write(array $record): void public function write(array $record): void
{ {
@@ -82,11 +80,8 @@ class FleepHookHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -95,11 +90,8 @@ class FleepHookHandler extends SocketHandler
/** /**
* Builds the header of the API Call * Builds the header of the API Call
*
* @param string $content
* @return string
*/ */
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST " . self::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n"; $header = "POST " . self::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n";
$header .= "Host: " . self::FLEEP_HOST . "\r\n"; $header .= "Host: " . self::FLEEP_HOST . "\r\n";
@@ -112,11 +104,8 @@ class FleepHookHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
$dataArray = [ $dataArray = [
'message' => $record['formatted'], 'message' => $record['formatted'],

View File

@@ -34,13 +34,12 @@ class FlowdockHandler extends SocketHandler
protected $apiToken; protected $apiToken;
/** /**
* @param string $apiToken * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool|int $level The minimum logging level at which this handler will be triggered * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* *
* @throws MissingExtensionException if OpenSSL is missing * @throws MissingExtensionException if OpenSSL is missing
*/ */
public function __construct($apiToken, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $apiToken, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler');
@@ -84,11 +83,8 @@ class FlowdockHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -97,22 +93,16 @@ class FlowdockHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
return json_encode($record['formatted']['flowdock']); return json_encode($record['formatted']['flowdock']);
} }
/** /**
* Builds the header of the API Call * Builds the header of the API Call
*
* @param string $content
* @return string
*/ */
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n"; $header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n";
$header .= "Host: api.flowdock.com\r\n"; $header .= "Host: api.flowdock.com\r\n";

View File

@@ -53,8 +53,6 @@ trait FormattableHandlerTrait
* Gets the default formatter. * Gets the default formatter.
* *
* Overwrite this if the LineFormatter is not a good default for your handler. * Overwrite this if the LineFormatter is not a good default for your handler.
*
* @return FormatterInterface
*/ */
protected function getDefaultFormatter(): FormatterInterface protected function getDefaultFormatter(): FormatterInterface
{ {

View File

@@ -31,7 +31,7 @@ class GelfHandler extends AbstractProcessingHandler
/** /**
* @param PublisherInterface $publisher a publisher object * @param PublisherInterface $publisher a publisher object
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true) public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true)

View File

@@ -26,8 +26,8 @@ class GroupHandler extends Handler implements ProcessableHandlerInterface, Reset
protected $handlers; protected $handlers;
/** /**
* @param array $handlers Array of Handlers. * @param HandlerInterface[] $handlers Array of Handlers.
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(array $handlers, bool $bubble = true) public function __construct(array $handlers, bool $bubble = true)
{ {
@@ -114,7 +114,7 @@ class GroupHandler extends Handler implements ProcessableHandlerInterface, Reset
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function setFormatter(FormatterInterface $formatter) public function setFormatter(FormatterInterface $formatter): HandlerInterface
{ {
foreach ($this->handlers as $handler) { foreach ($this->handlers as $handler) {
$handler->setFormatter($formatter); $handler->setFormatter($formatter);

View File

@@ -38,10 +38,6 @@ class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, F
*/ */
protected $handler; protected $handler;
/**
* HandlerWrapper constructor.
* @param HandlerInterface $handler
*/
public function __construct(HandlerInterface $handler) public function __construct(HandlerInterface $handler)
{ {
$this->handler = $handler; $this->handler = $handler;

View File

@@ -70,18 +70,27 @@ class HipChatHandler extends SocketHandler
private $host; private $host;
/** /**
* @param string $token HipChat API Token * @param string $token HipChat API Token
* @param string $room The room that should be alerted of the message (Id or Name) * @param string $room The room that should be alerted of the message (Id or Name)
* @param string $name Name used in the "from" field. * @param string|null $name Name used in the "from" field.
* @param bool $notify Trigger a notification in clients or not * @param bool $notify Trigger a notification in clients or not
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useSSL Whether to connect via SSL. * @param bool $useSSL Whether to connect via SSL.
* @param string $format The format of the messages (default to text, can be set to html if you have html in the messages) * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
* @param string $host The HipChat server hostname. * @param string $host The HipChat server hostname.
*/ */
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, bool $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com') public function __construct(
{ string $token,
string $room,
?string $name = 'Monolog',
bool $notify = false,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useSSL = true,
string $format = 'text',
string $host = 'api.hipchat.com'
) {
$connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80'; $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
parent::__construct($connectionString, $level, $bubble); parent::__construct($connectionString, $level, $bubble);
@@ -95,11 +104,8 @@ class HipChatHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -108,11 +114,8 @@ class HipChatHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
$dataArray = [ $dataArray = [
'notify' => $this->notify ? 'true' : 'false', 'notify' => $this->notify ? 'true' : 'false',
@@ -296,13 +299,8 @@ class HipChatHandler extends SocketHandler
* Note that this might cause false failures in the specific case of using * Note that this might cause false failures in the specific case of using
* a valid name with less than 16 characters, but 16 or more bytes, on a * a valid name with less than 16 characters, but 16 or more bytes, on a
* system where `mb_strlen()` is unavailable. * system where `mb_strlen()` is unavailable.
*
* @param string $str
* @param int $length
*
* @return bool
*/ */
private function validateStringLength($str, $length) private function validateStringLength(string $str, int $length): bool
{ {
if (function_exists('mb_strlen')) { if (function_exists('mb_strlen')) {
return (mb_strlen($str) <= $length); return (mb_strlen($str) <= $length);

View File

@@ -30,12 +30,12 @@ class IFTTTHandler extends AbstractProcessingHandler
private $secretKey; private $secretKey;
/** /**
* @param string $eventName The name of the IFTTT Maker event that should be triggered * @param string $eventName The name of the IFTTT Maker event that should be triggered
* @param string $secretKey A valid IFTTT secret key * @param string $secretKey A valid IFTTT secret key
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($eventName, $secretKey, $level = Logger::ERROR, bool $bubble = true) public function __construct(string $eventName, string $secretKey, $level = Logger::ERROR, bool $bubble = true)
{ {
$this->eventName = $eventName; $this->eventName = $eventName;
$this->secretKey = $secretKey; $this->secretKey = $secretKey;

View File

@@ -27,15 +27,15 @@ class InsightOpsHandler extends SocketHandler
protected $logToken; protected $logToken;
/** /**
* @param string $token Log token supplied by InsightOps * @param string $token Log token supplied by InsightOps
* @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'. * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'.
* @param bool $useSSL Whether or not SSL encryption should be used * @param bool $useSSL Whether or not SSL encryption should be used
* @param int $level The minimum logging level to trigger this handler * @param string|int $level The minimum logging level to trigger this handler
* @param bool $bubble Whether or not messages that are handled should bubble up the stack. * @param bool $bubble Whether or not messages that are handled should bubble up the stack.
* *
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/ */
public function __construct($token, $region = 'us', $useSSL = true, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $token, string $region = 'us', bool $useSSL = true, $level = Logger::DEBUG, bool $bubble = true)
{ {
if ($useSSL && !extension_loaded('openssl')) { if ($useSSL && !extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');
@@ -51,11 +51,8 @@ class InsightOpsHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
return $this->logToken . ' ' . $record['formatted']; return $this->logToken . ' ' . $record['formatted'];
} }

View File

@@ -24,14 +24,15 @@ class LogEntriesHandler extends SocketHandler
protected $logToken; protected $logToken;
/** /**
* @param string $token Log token supplied by LogEntries * @param string $token Log token supplied by LogEntries
* @param bool $useSSL Whether or not SSL encryption should be used. * @param bool $useSSL Whether or not SSL encryption should be used.
* @param int $level The minimum logging level to trigger this handler * @param string|int $level The minimum logging level to trigger this handler
* @param bool $bubble Whether or not messages that are handled should bubble up the stack. * @param bool $bubble Whether or not messages that are handled should bubble up the stack.
* @param string $host Custom hostname to send the data to if needed
* *
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/ */
public function __construct($token, $useSSL = true, $level = Logger::DEBUG, bool $bubble = true, string $host = 'data.logentries.com') public function __construct(string $token, bool $useSSL = true, $level = Logger::DEBUG, bool $bubble = true, string $host = 'data.logentries.com')
{ {
if ($useSSL && !extension_loaded('openssl')) { if ($useSSL && !extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');
@@ -44,11 +45,8 @@ class LogEntriesHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
return $this->logToken . ' ' . $record['formatted']; return $this->logToken . ' ' . $record['formatted'];
} }

View File

@@ -32,10 +32,17 @@ class LogglyHandler extends AbstractProcessingHandler
protected $tag = []; protected $tag = [];
public function __construct($token, $level = Logger::DEBUG, bool $bubble = true) /**
* @param string $token API token supplied by Loggly
* @param string|int $level The minimum logging level to trigger this handler
* @param bool $bubble Whether or not messages that are handled should bubble up the stack.
*
* @throws MissingExtensionException If the curl extension is missing
*/
public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!extension_loaded('curl')) { if (!extension_loaded('curl')) {
throw new \LogicException('The curl extension is needed to use the LogglyHandler'); throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler');
} }
$this->token = $token; $this->token = $token;
@@ -43,18 +50,28 @@ class LogglyHandler extends AbstractProcessingHandler
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
} }
public function setTag($tag) /**
* @param string[]|string $tag
*/
public function setTag($tag): self
{ {
$tag = !empty($tag) ? $tag : []; $tag = !empty($tag) ? $tag : [];
$this->tag = is_array($tag) ? $tag : [$tag]; $this->tag = is_array($tag) ? $tag : [$tag];
return $this;
} }
public function addTag($tag) /**
* @param string[]|string $tag
*/
public function addTag($tag): self
{ {
if (!empty($tag)) { if (!empty($tag)) {
$tag = is_array($tag) ? $tag : [$tag]; $tag = is_array($tag) ? $tag : [$tag];
$this->tag = array_unique(array_merge($this->tag, $tag)); $this->tag = array_unique(array_merge($this->tag, $tag));
} }
return $this;
} }
protected function write(array $record): void protected function write(array $record): void
@@ -75,7 +92,7 @@ class LogglyHandler extends AbstractProcessingHandler
} }
} }
protected function send($data, $endpoint) protected function send(string $data, string $endpoint): void
{ {
$url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token); $url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token);

View File

@@ -64,7 +64,7 @@ class LogmaticHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
protected function generateDataStream($record): string protected function generateDataStream(array $record): string
{ {
return $this->logToken . ' ' . $record['formatted']; return $this->logToken . ' ' . $record['formatted'];
} }

View File

@@ -27,10 +27,10 @@ class MandrillHandler extends MailHandler
/** /**
* @param string $apiKey A valid Mandrill API key * @param string $apiKey A valid Mandrill API key
* @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($apiKey, $message, $level = Logger::ERROR, bool $bubble = true) public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);

View File

@@ -12,9 +12,9 @@
namespace Monolog\Handler; namespace Monolog\Handler;
/** /**
* Exception can be thrown if an extension for an handler is missing * Exception can be thrown if an extension for a handler is missing
* *
* @author Christian Bergau <cbergau86@gmail.com> * @author Christian Bergau <cbergau86@gmail.com>
*/ */
class MissingExtensionException extends \Exception class MissingExtensionException extends \Exception
{ {

View File

@@ -43,10 +43,10 @@ class MongoDBHandler extends AbstractProcessingHandler
* @param Client|Manager $mongodb MongoDB library or driver client * @param Client|Manager $mongodb MongoDB library or driver client
* @param string $database Database name * @param string $database Database name
* @param string $collection Collection name * @param string $collection Collection name
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($mongodb, $database, $collection, $level = Logger::DEBUG, bool $bubble = true) public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!($mongodb instanceof Client || $mongodb instanceof Manager)) { if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required'); throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required');

View File

@@ -54,7 +54,7 @@ class NativeMailerHandler extends MailHandler
/** /**
* The Content-type for the message * The Content-type for the message
* @var string * @var string|null
*/ */
protected $contentType; protected $contentType;
@@ -68,11 +68,11 @@ class NativeMailerHandler extends MailHandler
* @param string|array $to The receiver of the mail * @param string|array $to The receiver of the mail
* @param string $subject The subject of the mail * @param string $subject The subject of the mail
* @param string $from The sender of the mail * @param string $from The sender of the mail
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $maxColumnWidth The maximum column width that the message lines will have * @param int $maxColumnWidth The maximum column width that the message lines will have
*/ */
public function __construct($to, $subject, $from, $level = Logger::ERROR, bool $bubble = true, $maxColumnWidth = 70) public function __construct($to, string $subject, string $from, $level = Logger::ERROR, bool $bubble = true, int $maxColumnWidth = 70)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->to = (array) $to; $this->to = (array) $to;
@@ -84,10 +84,9 @@ class NativeMailerHandler extends MailHandler
/** /**
* Add headers to the message * Add headers to the message
* *
* @param string|array $headers Custom added headers * @param string|array $headers Custom added headers
* @return self
*/ */
public function addHeader($headers) public function addHeader($headers): self
{ {
foreach ((array) $headers as $header) { foreach ((array) $headers as $header) {
if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) { if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) {
@@ -102,10 +101,9 @@ class NativeMailerHandler extends MailHandler
/** /**
* Add parameters to the message * Add parameters to the message
* *
* @param string|array $parameters Custom added parameters * @param string|array $parameters Custom added parameters
* @return self
*/ */
public function addParameter($parameters) public function addParameter($parameters): self
{ {
$this->parameters = array_merge($this->parameters, (array) $parameters); $this->parameters = array_merge($this->parameters, (array) $parameters);
@@ -141,28 +139,20 @@ class NativeMailerHandler extends MailHandler
} }
} }
/** public function getContentType(): ?string
* @return string $contentType
*/
public function getContentType()
{ {
return $this->contentType; return $this->contentType;
} }
/** public function getEncoding(): string
* @return string $encoding
*/
public function getEncoding()
{ {
return $this->encoding; return $this->encoding;
} }
/** /**
* @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML * @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML messages.
* messages.
* @return self
*/ */
public function setContentType($contentType) public function setContentType(string $contentType): self
{ {
if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) { if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) {
throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection'); throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection');
@@ -173,11 +163,7 @@ class NativeMailerHandler extends MailHandler
return $this; return $this;
} }
/** public function setEncoding(string $encoding): self
* @param string $encoding
* @return self
*/
public function setEncoding($encoding)
{ {
if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) { if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) {
throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection'); throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection');

View File

@@ -29,14 +29,14 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Name of the New Relic application that will receive logs from this handler. * Name of the New Relic application that will receive logs from this handler.
* *
* @var string * @var string|null
*/ */
protected $appName; protected $appName;
/** /**
* Name of the current transaction * Name of the current transaction
* *
* @var string * @var string|null
*/ */
protected $transactionName; protected $transactionName;
@@ -51,16 +51,18 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
* @param string $appName * @param string|int $level The minimum logging level at which this handler will be triggered.
* @param bool $explodeArrays * @param bool $bubble Whether the messages that are handled can bubble up the stack or not.
* @param string $transactionName * @param string|null $appName
* @param bool $explodeArrays
* @param string|null $transactionName
*/ */
public function __construct( public function __construct(
$level = Logger::ERROR, $level = Logger::ERROR,
$bubble = true, bool $bubble = true,
$appName = null, ?string $appName = null,
$explodeArrays = false, bool $explodeArrays = false,
$transactionName = null ?string $transactionName = null
) { ) {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
@@ -124,7 +126,7 @@ class NewRelicHandler extends AbstractProcessingHandler
* *
* @return bool * @return bool
*/ */
protected function isNewRelicEnabled() protected function isNewRelicEnabled(): bool
{ {
return extension_loaded('newrelic'); return extension_loaded('newrelic');
} }
@@ -132,11 +134,8 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Returns the appname where this log should be sent. Each log can override the default appname, set in this * Returns the appname where this log should be sent. Each log can override the default appname, set in this
* handler's constructor, by providing the appname in it's context. * handler's constructor, by providing the appname in it's context.
*
* @param array $context
* @return null|string
*/ */
protected function getAppName(array $context) protected function getAppName(array $context): ?string
{ {
if (isset($context['appname'])) { if (isset($context['appname'])) {
return $context['appname']; return $context['appname'];
@@ -148,12 +147,8 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Returns the name of the current transaction. Each log can override the default transaction name, set in this * Returns the name of the current transaction. Each log can override the default transaction name, set in this
* handler's constructor, by providing the transaction_name in it's context * handler's constructor, by providing the transaction_name in it's context
*
* @param array $context
*
* @return null|string
*/ */
protected function getTransactionName(array $context) protected function getTransactionName(array $context): ?string
{ {
if (isset($context['transaction_name'])) { if (isset($context['transaction_name'])) {
return $context['transaction_name']; return $context['transaction_name'];
@@ -164,20 +159,16 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Sets the NewRelic application that should receive this log. * Sets the NewRelic application that should receive this log.
*
* @param string $appName
*/ */
protected function setNewRelicAppName($appName) protected function setNewRelicAppName(string $appName): void
{ {
newrelic_set_appname($appName); newrelic_set_appname($appName);
} }
/** /**
* Overwrites the name of the current transaction * Overwrites the name of the current transaction
*
* @param string $transactionName
*/ */
protected function setNewRelicTransactionName($transactionName) protected function setNewRelicTransactionName(string $transactionName): void
{ {
newrelic_name_transaction($transactionName); newrelic_name_transaction($transactionName);
} }
@@ -186,7 +177,7 @@ class NewRelicHandler extends AbstractProcessingHandler
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
*/ */
protected function setNewRelicParameter($key, $value) protected function setNewRelicParameter(string $key, $value): void
{ {
if (null === $value || is_scalar($value)) { if (null === $value || is_scalar($value)) {
newrelic_add_custom_parameter($key, $value); newrelic_add_custom_parameter($key, $value);

View File

@@ -23,14 +23,17 @@ use Monolog\Logger;
*/ */
class NullHandler extends Handler class NullHandler extends Handler
{ {
/**
* @var int
*/
private $level; private $level;
/** /**
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
*/ */
public function __construct(int $level = Logger::DEBUG) public function __construct($level = Logger::DEBUG)
{ {
$this->level = $level; $this->level = Logger::toMonologLevel($level);
} }
/** /**

View File

@@ -68,8 +68,8 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/** /**
* @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details * @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details
* @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional)
* @param int|string $level * @param string|int $level The minimum logging level at which this handler will be triggered.
* @param bool $bubble * @param bool $bubble Whether the messages that are handled can bubble up the stack or not.
* @throws \RuntimeException * @throws \RuntimeException
*/ */
public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true) public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true)
@@ -82,7 +82,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
$this->connector = $this->initConnector($connector); $this->connector = $this->initConnector($connector);
} }
private function initOptions(array $options) private function initOptions(array $options): array
{ {
$wrongOptions = array_diff(array_keys($options), array_keys($this->options)); $wrongOptions = array_diff(array_keys($options), array_keys($this->options));
if ($wrongOptions) { if ($wrongOptions) {
@@ -95,7 +95,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/** /**
* @suppress PhanTypeMismatchArgument * @suppress PhanTypeMismatchArgument
*/ */
private function initConnector(Connector $connector = null): Connector private function initConnector(?Connector $connector = null): Connector
{ {
if (!$connector) { if (!$connector) {
if ($this->options['dataStorage']) { if ($this->options['dataStorage']) {
@@ -171,9 +171,6 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/** /**
* Writes the record down to the log of the implementing handler * Writes the record down to the log of the implementing handler
*
* @param array $record
* @return void
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {

View File

@@ -21,8 +21,8 @@ interface ProcessableHandlerInterface
/** /**
* Adds a processor in the stack. * Adds a processor in the stack.
* *
* @param callable $callback * @param ProcessorInterface|callable $callback
* @return HandlerInterface self * @return HandlerInterface self
*/ */
public function pushProcessor(callable $callback): HandlerInterface; public function pushProcessor(callable $callback): HandlerInterface;

View File

@@ -60,7 +60,7 @@ trait ProcessableHandlerTrait
return $record; return $record;
} }
protected function resetProcessors() protected function resetProcessors(): void
{ {
foreach ($this->processors as $processor) { foreach ($this->processors as $processor) {
if ($processor instanceof ResettableInterface) { if ($processor instanceof ResettableInterface) {

View File

@@ -30,7 +30,7 @@ class PsrHandler extends AbstractHandler
/** /**
* @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true) public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true)

View File

@@ -68,19 +68,31 @@ class PushoverHandler extends SocketHandler
* @param string $token Pushover api token * @param string $token Pushover api token
* @param string|array $users Pushover user id or array of ids the message will be sent to * @param string|array $users Pushover user id or array of ids the message will be sent to
* @param string $title Title sent to the Pushover API * @param string $title Title sent to the Pushover API
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not
* the pushover.net app owner. OpenSSL is required for this option. * the pushover.net app owner. OpenSSL is required for this option.
* @param int $highPriorityLevel The minimum logging level at which this handler will start * @param string|int $highPriorityLevel The minimum logging level at which this handler will start
* sending "high priority" requests to the Pushover API * sending "high priority" requests to the Pushover API
* @param int $emergencyLevel The minimum logging level at which this handler will start * @param string|int $emergencyLevel The minimum logging level at which this handler will start
* sending "emergency" requests to the Pushover API * sending "emergency" requests to the Pushover API
* @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user. * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will
* @param int $expire The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds). * send the same notification to the user.
* @param int $expire The expire parameter specifies how many seconds your notification will continue
* to be retried for (every retry seconds).
*/ */
public function __construct($token, $users, $title = null, $level = Logger::CRITICAL, bool $bubble = true, $useSSL = true, $highPriorityLevel = Logger::CRITICAL, $emergencyLevel = Logger::EMERGENCY, $retry = 30, $expire = 25200) public function __construct(
{ string $token,
$users,
?string $title = null,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useSSL = true,
$highPriorityLevel = Logger::CRITICAL,
$emergencyLevel = Logger::EMERGENCY,
int $retry = 30,
int $expire = 25200
) {
$connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80'; $connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80';
parent::__construct($connectionString, $level, $bubble); parent::__construct($connectionString, $level, $bubble);
@@ -93,14 +105,14 @@ class PushoverHandler extends SocketHandler
$this->expire = $expire; $this->expire = $expire;
} }
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
return $this->buildHeader($content) . $content; return $this->buildHeader($content) . $content;
} }
private function buildContent($record) private function buildContent(array $record): string
{ {
// Pushover has a limit of 512 characters on title and message combined. // Pushover has a limit of 512 characters on title and message combined.
$maxMessageLength = 512 - strlen($this->title); $maxMessageLength = 512 - strlen($this->title);
@@ -141,7 +153,7 @@ class PushoverHandler extends SocketHandler
return http_build_query($dataArray); return http_build_query($dataArray);
} }
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST /1/messages.json HTTP/1.1\r\n"; $header = "POST /1/messages.json HTTP/1.1\r\n";
$header .= "Host: api.pushover.net\r\n"; $header .= "Host: api.pushover.net\r\n";
@@ -164,22 +176,27 @@ class PushoverHandler extends SocketHandler
$this->user = null; $this->user = null;
} }
public function setHighPriorityLevel($value) public function setHighPriorityLevel($value): self
{ {
$this->highPriorityLevel = $value; $this->highPriorityLevel = Logger::toMonologLevel($value);
return $this;
} }
public function setEmergencyLevel($value) public function setEmergencyLevel($value): self
{ {
$this->emergencyLevel = $value; $this->emergencyLevel = Logger::toMonologLevel($value);
return $this;
} }
/** /**
* Use the formatted message? * Use the formatted message?
* @param bool $value
*/ */
public function useFormattedMessage($value) public function useFormattedMessage(bool $value): self
{ {
$this->useFormattedMessage = (bool) $value; $this->useFormattedMessage = $value;
return $this;
} }
} }

View File

@@ -114,9 +114,11 @@ class RavenHandler extends AbstractProcessingHandler
* *
* @param FormatterInterface $formatter * @param FormatterInterface $formatter
*/ */
public function setBatchFormatter(FormatterInterface $formatter): void public function setBatchFormatter(FormatterInterface $formatter): self
{ {
$this->batchFormatter = $formatter; $this->batchFormatter = $formatter;
return $this;
} }
/** /**
@@ -250,13 +252,17 @@ class RavenHandler extends AbstractProcessingHandler
/** /**
* @link https://docs.sentry.io/learn/breadcrumbs/ * @link https://docs.sentry.io/learn/breadcrumbs/
*/ */
public function addBreadcrumb(array $crumb): void public function addBreadcrumb(array $crumb): self
{ {
$this->ravenClient->breadcrumbs->record($crumb); $this->ravenClient->breadcrumbs->record($crumb);
return $this;
} }
public function resetBreadcrumbs(): void public function resetBreadcrumbs(): self
{ {
$this->ravenClient->breadcrumbs->reset(); $this->ravenClient->breadcrumbs->reset();
return $this;
} }
} }

View File

@@ -35,7 +35,7 @@ class RedisHandler extends AbstractProcessingHandler
/** /**
* @param \Predis\Client|\Redis $redis The redis instance * @param \Predis\Client|\Redis $redis The redis instance
* @param string $key The key name to push records to * @param string $key The key name to push records to
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $capSize Number of entries to limit list size to, 0 = unlimited * @param int $capSize Number of entries to limit list size to, 0 = unlimited
*/ */
@@ -67,11 +67,8 @@ class RedisHandler extends AbstractProcessingHandler
/** /**
* Write and cap the collection * Write and cap the collection
* Writes the record to the redis list and caps its * Writes the record to the redis list and caps its
*
* @param array $record associative record array
* @return void
*/ */
protected function writeCapped(array $record) protected function writeCapped(array $record): void
{ {
if ($this->redisClient instanceof \Redis) { if ($this->redisClient instanceof \Redis) {
$this->redisClient->multi() $this->redisClient->multi()

View File

@@ -60,7 +60,7 @@ class RollbarHandler extends AbstractProcessingHandler
/** /**
* @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true) public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true)

View File

@@ -37,14 +37,14 @@ class RotatingFileHandler extends StreamHandler
protected $dateFormat; protected $dateFormat;
/** /**
* @param string $filename * @param string $filename
* @param int $maxFiles The maximal amount of files to keep (0 means unlimited) * @param int $maxFiles The maximal amount of files to keep (0 means unlimited)
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param bool $useLocking Try to lock log file before doing any writes * @param bool $useLocking Try to lock log file before doing any writes
*/ */
public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false) public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
{ {
$this->filename = $filename; $this->filename = $filename;
$this->maxFiles = (int) $maxFiles; $this->maxFiles = (int) $maxFiles;
@@ -79,7 +79,7 @@ class RotatingFileHandler extends StreamHandler
} }
} }
public function setFilenameFormat($filenameFormat, $dateFormat) public function setFilenameFormat(string $filenameFormat, string $dateFormat): self
{ {
if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) { if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
@@ -98,6 +98,8 @@ class RotatingFileHandler extends StreamHandler
$this->dateFormat = $dateFormat; $this->dateFormat = $dateFormat;
$this->url = $this->getTimedFilename(); $this->url = $this->getTimedFilename();
$this->close(); $this->close();
return $this;
} }
/** /**
@@ -158,7 +160,7 @@ class RotatingFileHandler extends StreamHandler
$this->mustRotate = false; $this->mustRotate = false;
} }
protected function getTimedFilename() protected function getTimedFilename(): string
{ {
$fileInfo = pathinfo($this->filename); $fileInfo = pathinfo($this->filename);
$timedFilename = str_replace( $timedFilename = str_replace(
@@ -174,7 +176,7 @@ class RotatingFileHandler extends StreamHandler
return $timedFilename; return $timedFilename;
} }
protected function getGlobPattern() protected function getGlobPattern(): string
{ {
$fileInfo = pathinfo($this->filename); $fileInfo = pathinfo($this->filename);
$glob = str_replace( $glob = str_replace(

View File

@@ -41,9 +41,9 @@ class SamplingHandler extends AbstractHandler implements ProcessableHandlerInter
/** /**
* @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler). * @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler).
* @param int $factor Sample factor * @param int $factor Sample factor (e.g. 10 means every ~10th record is sampled)
*/ */
public function __construct($handler, $factor) public function __construct($handler, int $factor)
{ {
parent::__construct(); parent::__construct();
$this->handler = $handler; $this->handler = $handler;

View File

@@ -48,8 +48,18 @@ class SlackHandler extends SocketHandler
* @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
* @throws MissingExtensionException If no OpenSSL PHP extension configured * @throws MissingExtensionException If no OpenSSL PHP extension configured
*/ */
public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, bool $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array()) public function __construct(
{ string $token,
string $channel,
?string $username = null,
bool $useAttachment = true,
?string $iconEmoji = null,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
array $excludeFields = array()
) {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
} }
@@ -69,23 +79,20 @@ class SlackHandler extends SocketHandler
$this->token = $token; $this->token = $token;
} }
public function getSlackRecord() public function getSlackRecord(): SlackRecord
{ {
return $this->slackRecord; return $this->slackRecord;
} }
public function getToken() public function getToken(): string
{ {
return $this->token; return $this->token;
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -94,24 +101,15 @@ class SlackHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
$dataArray = $this->prepareContentData($record); $dataArray = $this->prepareContentData($record);
return http_build_query($dataArray); return http_build_query($dataArray);
} }
/** protected function prepareContentData(array $record): array
* Prepares content data
*
* @param array $record
* @return array
*/
protected function prepareContentData($record)
{ {
$dataArray = $this->slackRecord->getSlackData($record); $dataArray = $this->slackRecord->getSlackData($record);
$dataArray['token'] = $this->token; $dataArray['token'] = $this->token;
@@ -125,11 +123,8 @@ class SlackHandler extends SocketHandler
/** /**
* Builds the header of the API Call * Builds the header of the API Call
*
* @param string $content
* @return string
*/ */
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST /api/chat.postMessage HTTP/1.1\r\n"; $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
$header .= "Host: slack.com\r\n"; $header .= "Host: slack.com\r\n";
@@ -142,8 +137,6 @@ class SlackHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {
@@ -157,7 +150,7 @@ class SlackHandler extends SocketHandler
* If we do not read some but close the socket too early, slack sometimes * If we do not read some but close the socket too early, slack sometimes
* drops the request entirely. * drops the request entirely.
*/ */
protected function finalizeWrite() protected function finalizeWrite(): void
{ {
$res = $this->getResource(); $res = $this->getResource();
if (is_resource($res)) { if (is_resource($res)) {
@@ -166,41 +159,6 @@ class SlackHandler extends SocketHandler
$this->closeSocket(); $this->closeSocket();
} }
/**
* Returned a Slack message attachment color associated with
* provided level.
*
* @param int $level
* @return string
* @deprecated Use underlying SlackRecord instead
*/
protected function getAttachmentColor($level)
{
trigger_error(
'SlackHandler::getAttachmentColor() is deprecated. Use underlying SlackRecord instead.',
E_USER_DEPRECATED
);
return $this->slackRecord->getAttachmentColor($level);
}
/**
* Stringifies an array of key/value pairs to be used in attachment fields
*
* @param array $fields
* @return string
* @deprecated Use underlying SlackRecord instead
*/
protected function stringify($fields)
{
trigger_error(
'SlackHandler::stringify() is deprecated. Use underlying SlackRecord instead.',
E_USER_DEPRECATED
);
return $this->slackRecord->stringify($fields);
}
public function setFormatter(FormatterInterface $formatter): HandlerInterface public function setFormatter(FormatterInterface $formatter): HandlerInterface
{ {
parent::setFormatter($formatter); parent::setFormatter($formatter);

View File

@@ -43,12 +43,22 @@ class SlackWebhookHandler extends AbstractProcessingHandler
* @param string|null $iconEmoji The emoji name to use (or null) * @param string|null $iconEmoji The emoji name to use (or null)
* @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
* @param bool $includeContextAndExtra Whether the attachment should include context and extra data * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
*/ */
public function __construct($webhookUrl, $channel = null, $username = null, $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, bool $bubble = true, array $excludeFields = array()) public function __construct(
{ string $webhookUrl,
?string $channel = null,
?string $username = null,
bool $useAttachment = true,
?string $iconEmoji = null,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
$level = Logger::CRITICAL,
bool $bubble = true,
array $excludeFields = array()
) {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->webhookUrl = $webhookUrl; $this->webhookUrl = $webhookUrl;
@@ -64,12 +74,12 @@ class SlackWebhookHandler extends AbstractProcessingHandler
); );
} }
public function getSlackRecord() public function getSlackRecord(): SlackRecord
{ {
return $this->slackRecord; return $this->slackRecord;
} }
public function getWebhookUrl() public function getWebhookUrl(): string
{ {
return $this->webhookUrl; return $this->webhookUrl;
} }

View File

@@ -40,13 +40,13 @@ class SlackbotHandler extends AbstractProcessingHandler
private $channel; private $channel;
/** /**
* @param string $slackTeam Slack team slug * @param string $slackTeam Slack team slug
* @param string $token Slackbot token * @param string $token Slackbot token
* @param string $channel Slack channel (encoded ID or name) * @param string $channel Slack channel (encoded ID or name)
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, bool $bubble = true) public function __construct(string $slackTeam, string $token, string $channel, $level = Logger::CRITICAL, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
@@ -57,8 +57,6 @@ class SlackbotHandler extends AbstractProcessingHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {

View File

@@ -38,11 +38,11 @@ class SocketHandler extends AbstractProcessingHandler
private $lastWritingAt; private $lastWritingAt;
/** /**
* @param string $connectionString Socket connection string * @param string $connectionString Socket connection string
* @param int $level The minimum logging level at which this handler will be triggered * @param int|string $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($connectionString, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $connectionString, $level = Logger::DEBUG, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->connectionString = $connectionString; $this->connectionString = $connectionString;
@@ -88,9 +88,11 @@ class SocketHandler extends AbstractProcessingHandler
/** /**
* Set socket connection to be persistent. It only has effect before the connection is initiated. * Set socket connection to be persistent. It only has effect before the connection is initiated.
*/ */
public function setPersistent(bool $persistent): void public function setPersistent(bool $persistent): self
{ {
$this->persistent = $persistent; $this->persistent = $persistent;
return $this;
} }
/** /**
@@ -98,10 +100,12 @@ class SocketHandler extends AbstractProcessingHandler
* *
* @see http://php.net/manual/en/function.fsockopen.php * @see http://php.net/manual/en/function.fsockopen.php
*/ */
public function setConnectionTimeout(float $seconds): void public function setConnectionTimeout(float $seconds): self
{ {
$this->validateTimeout($seconds); $this->validateTimeout($seconds);
$this->connectionTimeout = (float) $seconds; $this->connectionTimeout = $seconds;
return $this;
} }
/** /**
@@ -109,10 +113,12 @@ class SocketHandler extends AbstractProcessingHandler
* *
* @see http://php.net/manual/en/function.stream-set-timeout.php * @see http://php.net/manual/en/function.stream-set-timeout.php
*/ */
public function setTimeout(float $seconds): void public function setTimeout(float $seconds): self
{ {
$this->validateTimeout($seconds); $this->validateTimeout($seconds);
$this->timeout = (float) $seconds; $this->timeout = $seconds;
return $this;
} }
/** /**
@@ -120,18 +126,22 @@ class SocketHandler extends AbstractProcessingHandler
* *
* @param float $seconds 0 for no timeout * @param float $seconds 0 for no timeout
*/ */
public function setWritingTimeout(float $seconds): void public function setWritingTimeout(float $seconds): self
{ {
$this->validateTimeout($seconds); $this->validateTimeout($seconds);
$this->writingTimeout = (float) $seconds; $this->writingTimeout = $seconds;
return $this;
} }
/** /**
* Set chunk size. Only has effect during connection in the writing cycle. * Set chunk size. Only has effect during connection in the writing cycle.
*/ */
public function setChunkSize(int $bytes): void public function setChunkSize(int $bytes): self
{ {
$this->chunkSize = $bytes; $this->chunkSize = $bytes;
return $this;
} }
/** /**
@@ -144,10 +154,8 @@ class SocketHandler extends AbstractProcessingHandler
/** /**
* Get persistent setting * Get persistent setting
*
* @return bool
*/ */
public function isPersistent() public function isPersistent(): bool
{ {
return $this->persistent; return $this->persistent;
} }
@@ -268,7 +276,7 @@ class SocketHandler extends AbstractProcessingHandler
$this->connect(); $this->connect();
} }
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
return (string) $record['formatted']; return (string) $record['formatted'];
} }
@@ -281,14 +289,14 @@ class SocketHandler extends AbstractProcessingHandler
return $this->resource; return $this->resource;
} }
private function connect() private function connect(): void
{ {
$this->createSocketResource(); $this->createSocketResource();
$this->setSocketTimeout(); $this->setSocketTimeout();
$this->setStreamChunkSize(); $this->setStreamChunkSize();
} }
private function createSocketResource() private function createSocketResource(): void
{ {
if ($this->isPersistent()) { if ($this->isPersistent()) {
$resource = $this->pfsockopen(); $resource = $this->pfsockopen();
@@ -301,21 +309,21 @@ class SocketHandler extends AbstractProcessingHandler
$this->resource = $resource; $this->resource = $resource;
} }
private function setSocketTimeout() private function setSocketTimeout(): void
{ {
if (!$this->streamSetTimeout()) { if (!$this->streamSetTimeout()) {
throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()"); throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()");
} }
} }
private function setStreamChunkSize() private function setStreamChunkSize(): void
{ {
if ($this->chunkSize && !$this->streamSetChunkSize()) { if ($this->chunkSize && !$this->streamSetChunkSize()) {
throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()"); throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()");
} }
} }
private function writeToSocket($data) private function writeToSocket(string $data): void
{ {
$length = strlen($data); $length = strlen($data);
$sent = 0; $sent = 0;
@@ -344,7 +352,7 @@ class SocketHandler extends AbstractProcessingHandler
} }
} }
private function writingIsTimedOut($sent) private function writingIsTimedOut(int $sent): bool
{ {
$writingTimeout = (int) floor($this->writingTimeout); $writingTimeout = (int) floor($this->writingTimeout);
if (0 === $writingTimeout) { if (0 === $writingTimeout) {

View File

@@ -31,7 +31,7 @@ class SqsHandler extends AbstractProcessingHandler
/** @var string */ /** @var string */
private $queueUrl; private $queueUrl;
public function __construct(SqsClient $sqsClient, $queueUrl, $level = Logger::DEBUG, bool $bubble = true) public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);

View File

@@ -33,7 +33,7 @@ class StreamHandler extends AbstractProcessingHandler
/** /**
* @param resource|string $stream * @param resource|string $stream
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param bool $useLocking Try to lock log file before doing any writes * @param bool $useLocking Try to lock log file before doing any writes
@@ -41,7 +41,7 @@ class StreamHandler extends AbstractProcessingHandler
* @throws \Exception If a missing directory is not buildable * @throws \Exception If a missing directory is not buildable
* @throws \InvalidArgumentException If stream is not a resource or string * @throws \InvalidArgumentException If stream is not a resource or string
*/ */
public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false) public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
if (is_resource($stream)) { if (is_resource($stream)) {
@@ -82,7 +82,7 @@ class StreamHandler extends AbstractProcessingHandler
* *
* @return string|null * @return string|null
*/ */
public function getUrl() public function getUrl(): ?string
{ {
return $this->url; return $this->url;
} }
@@ -128,12 +128,12 @@ class StreamHandler extends AbstractProcessingHandler
* @param resource $stream * @param resource $stream
* @param array $record * @param array $record
*/ */
protected function streamWrite($stream, array $record) protected function streamWrite($stream, array $record): void
{ {
fwrite($stream, (string) $record['formatted']); fwrite($stream, (string) $record['formatted']);
} }
private function customErrorHandler($code, $msg) private function customErrorHandler($code, $msg): void
{ {
$this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg); $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
} }
@@ -152,7 +152,7 @@ class StreamHandler extends AbstractProcessingHandler
return null; return null;
} }
private function createDir() private function createDir(): void
{ {
// Do not try to create dir if it has already been tried. // Do not try to create dir if it has already been tried.
if ($this->dirCreated) { if ($this->dirCreated) {

View File

@@ -30,7 +30,7 @@ class SwiftMailerHandler extends MailHandler
/** /**
* @param \Swift_Mailer $mailer The mailer to use * @param \Swift_Mailer $mailer The mailer to use
* @param callable|Swift_Message $message An example message for real messages, only the body will be replaced * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced
* @param int|string $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true) public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true)

View File

@@ -32,13 +32,13 @@ class SyslogHandler extends AbstractSyslogHandler
protected $logopts; protected $logopts;
/** /**
* @param string $ident * @param string $ident
* @param mixed $facility * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $logopts Option flags for the openlog() call, defaults to LOG_PID * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID
*/ */
public function __construct($ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, $logopts = LOG_PID) public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID)
{ {
parent::__construct($facility, $level, $bubble); parent::__construct($facility, $level, $bubble);

View File

@@ -25,14 +25,14 @@ class SyslogUdpHandler extends AbstractSyslogHandler
protected $ident; protected $ident;
/** /**
* @param string $host * @param string $host
* @param int $port * @param int $port
* @param mixed $facility * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param string $ident Program name or tag for each log message. * @param string $ident Program name or tag for each log message.
*/ */
public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, $ident = 'php') public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, string $ident = 'php')
{ {
parent::__construct($facility, $level, $bubble); parent::__construct($facility, $level, $bubble);
@@ -69,7 +69,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
/** /**
* Make common syslog header (see rfc5424) * Make common syslog header (see rfc5424)
*/ */
protected function makeCommonSyslogHeader($severity): string protected function makeCommonSyslogHeader(int $severity): string
{ {
$priority = $severity + $this->facility; $priority = $severity + $this->facility;
@@ -88,7 +88,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
$pid . " - - "; $pid . " - - ";
} }
protected function getDateTime() protected function getDateTime(): string
{ {
return date(\DateTime::RFC3339); return date(\DateTime::RFC3339);
} }
@@ -96,8 +96,10 @@ class SyslogUdpHandler extends AbstractSyslogHandler
/** /**
* Inject your own socket, mainly used for testing * Inject your own socket, mainly used for testing
*/ */
public function setSocket(UdpSocket $socket) public function setSocket(UdpSocket $socket): self
{ {
$this->socket = $socket; $this->socket = $socket;
return $this;
} }
} }

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger;
/** /**
* Used for testing purposes. * Used for testing purposes.
* *
@@ -79,16 +81,19 @@ class TestHandler extends AbstractProcessingHandler
$this->recordsByLevel = []; $this->recordsByLevel = [];
} }
public function hasRecords($level) /**
* @param string|int $level Logging level value or name
*/
public function hasRecords($level): bool
{ {
return isset($this->recordsByLevel[$level]); return isset($this->recordsByLevel[Logger::toMonologLevel($level)]);
} }
/** /**
* @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records * @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records
* @param int $level Logger::LEVEL constant value * @param string|int $level Logging level value or name
*/ */
public function hasRecord($record, $level) public function hasRecord($record, $level): bool
{ {
if (is_string($record)) { if (is_string($record)) {
$record = array('message' => $record); $record = array('message' => $record);
@@ -106,22 +111,33 @@ class TestHandler extends AbstractProcessingHandler
}, $level); }, $level);
} }
public function hasRecordThatContains($message, $level) /**
* @param string|int $level Logging level value or name
*/
public function hasRecordThatContains(string $message, $level): bool
{ {
return $this->hasRecordThatPasses(function ($rec) use ($message) { return $this->hasRecordThatPasses(function ($rec) use ($message) {
return strpos($rec['message'], $message) !== false; return strpos($rec['message'], $message) !== false;
}, $level); }, $level);
} }
public function hasRecordThatMatches($regex, $level) /**
* @param string|int $level Logging level value or name
*/
public function hasRecordThatMatches(string $regex, $level): bool
{ {
return $this->hasRecordThatPasses(function ($rec) use ($regex) { return $this->hasRecordThatPasses(function ($rec) use ($regex) {
return preg_match($regex, $rec['message']) > 0; return preg_match($regex, $rec['message']) > 0;
}, $level); }, $level);
} }
/**
* @param string|int $level Logging level value or name
*/
public function hasRecordThatPasses(callable $predicate, $level) public function hasRecordThatPasses(callable $predicate, $level)
{ {
$level = Logger::toMonologLevel($level);
if (!isset($this->recordsByLevel[$level])) { if (!isset($this->recordsByLevel[$level])) {
return false; return false;
} }

View File

@@ -39,10 +39,8 @@ class ZendMonitorHandler extends AbstractProcessingHandler
]; ];
/** /**
* Construct * @param string|int $level The minimum logging level at which this handler will be triggered.
* * @param bool $bubble Whether the messages that are handled can bubble up the stack or not.
* @param int $level
* @param bool $bubble
* @throws MissingExtensionException * @throws MissingExtensionException
*/ */
public function __construct($level = Logger::DEBUG, bool $bubble = true) public function __construct($level = Logger::DEBUG, bool $bubble = true)
@@ -65,7 +63,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
); );
} }
protected function writeZendMonitorCustomEvent(int $level, string $message, array $formatted) protected function writeZendMonitorCustomEvent(int $level, string $message, array $formatted): void
{ {
zend_monitor_custom_event($level, $message, $formatted); zend_monitor_custom_event($level, $message, $formatted);
} }

View File

@@ -14,7 +14,7 @@ namespace Monolog\Processor;
/** /**
* Injects value of gethostname in all records * Injects value of gethostname in all records
*/ */
class HostnameProcessor class HostnameProcessor implements ProcessorInterface
{ {
private static $host; private static $host;

View File

@@ -25,14 +25,18 @@ class TagProcessor implements ProcessorInterface
$this->setTags($tags); $this->setTags($tags);
} }
public function addTags(array $tags = []) public function addTags(array $tags = []): self
{ {
$this->tags = array_merge($this->tags, $tags); $this->tags = array_merge($this->tags, $tags);
return $this;
} }
public function setTags(array $tags = []) public function setTags(array $tags = []): self
{ {
$this->tags = $tags; $this->tags = $tags;
return $this;
} }
public function __invoke(array $record): array public function __invoke(array $record): array

View File

@@ -163,7 +163,7 @@ class NewRelicHandlerTest extends TestCase
class StubNewRelicHandlerWithoutExtension extends NewRelicHandler class StubNewRelicHandlerWithoutExtension extends NewRelicHandler
{ {
protected function isNewRelicEnabled() protected function isNewRelicEnabled(): bool
{ {
return false; return false;
} }
@@ -171,7 +171,7 @@ class StubNewRelicHandlerWithoutExtension extends NewRelicHandler
class StubNewRelicHandler extends NewRelicHandler class StubNewRelicHandler extends NewRelicHandler
{ {
protected function isNewRelicEnabled() protected function isNewRelicEnabled(): bool
{ {
return true; return true;
} }

View File

@@ -23,7 +23,7 @@ class SyslogUdpHandlerTest extends TestCase
*/ */
public function testWeValidateFacilities() public function testWeValidateFacilities()
{ {
$handler = new SyslogUdpHandler("ip", null, "invalidFacility"); $handler = new SyslogUdpHandler("ip", 514, "invalidFacility");
} }
public function testWeSplitIntoLines() public function testWeSplitIntoLines()