1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-29 11:26:09 +01:00

Use fully-qualified name for native functions (#1887)

This commit is contained in:
Christoph Dreis
2024-06-28 10:45:25 +02:00
committed by GitHub
parent 4e03d25f6d
commit 3ba77d1d39
90 changed files with 246 additions and 245 deletions

View File

@@ -30,6 +30,7 @@ return $config->setRules(array(
'header_comment' => ['header' => $header], 'header_comment' => ['header' => $header],
'include' => true, 'include' => true,
'class_attributes_separation' => array('elements' => array('method' => 'one', 'trait_import' => 'none')), 'class_attributes_separation' => array('elements' => array('method' => 'one', 'trait_import' => 'none')),
'native_function_invocation' => true,
'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true, 'no_blank_lines_after_phpdoc' => true,
'no_empty_statement' => true, 'no_empty_statement' => true,

View File

@@ -194,7 +194,7 @@ class ErrorHandler
($this->previousExceptionHandler)($e); ($this->previousExceptionHandler)($e);
} }
if (!headers_sent() && in_array(strtolower((string) ini_get('display_errors')), ['0', '', 'false', 'off', 'none', 'no'], true)) { if (!headers_sent() && \in_array(strtolower((string) \ini_get('display_errors')), ['0', '', 'false', 'off', 'none', 'no'], true)) {
http_response_code(500); http_response_code(500);
} }
@@ -208,7 +208,7 @@ class ErrorHandler
} }
// fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries
if (!$this->hasFatalErrorHandler || !in_array($code, self::FATAL_ERRORS, true)) { if (!$this->hasFatalErrorHandler || !\in_array($code, self::FATAL_ERRORS, true)) {
$level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL; $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL;
$this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]); $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]);
} else { } else {
@@ -234,12 +234,12 @@ class ErrorHandler
{ {
$this->reservedMemory = ''; $this->reservedMemory = '';
if (is_array($this->lastFatalData)) { if (\is_array($this->lastFatalData)) {
$lastError = $this->lastFatalData; $lastError = $this->lastFatalData;
} else { } else {
$lastError = error_get_last(); $lastError = error_get_last();
} }
if (is_array($lastError) && in_array($lastError['type'], self::FATAL_ERRORS, true)) { if (\is_array($lastError) && \in_array($lastError['type'], self::FATAL_ERRORS, true)) {
$trace = $lastError['trace'] ?? null; $trace = $lastError['trace'] ?? null;
$this->logger->log( $this->logger->log(
$this->fatalLevel, $this->fatalLevel,

View File

@@ -59,7 +59,7 @@ class ChromePHPFormatter implements FormatterInterface
if (\count($record->extra) > 0) { if (\count($record->extra) > 0) {
$message['extra'] = $record->extra; $message['extra'] = $record->extra;
} }
if (count($message) === 1) { if (\count($message) === 1) {
$message = reset($message); $message = reset($message);
} }

View File

@@ -86,7 +86,7 @@ class FlowdockFormatter implements FormatterInterface
static $hasMbString; static $hasMbString;
if (null === $hasMbString) { if (null === $hasMbString) {
$hasMbString = function_exists('mb_strlen'); $hasMbString = \function_exists('mb_strlen');
} }
$maxLength = 45; $maxLength = 45;
@@ -96,7 +96,7 @@ class FlowdockFormatter implements FormatterInterface
$message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...'; $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...';
} }
} else { } else {
if (strlen($message) > $maxLength) { if (\strlen($message) > $maxLength) {
$message = substr($message, 0, $maxLength - 4) . ' ...'; $message = substr($message, 0, $maxLength - 4) . ' ...';
} }
} }

View File

@@ -47,7 +47,7 @@ class FluentdFormatter implements FormatterInterface
*/ */
public function __construct(bool $levelTag = false) public function __construct(bool $levelTag = false)
{ {
if (!function_exists('json_encode')) { if (!\function_exists('json_encode')) {
throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter'); throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter');
} }

View File

@@ -104,7 +104,7 @@ class GelfMessageFormatter extends NormalizerFormatter
->setLevel($this->getGraylog2Priority($record->level)); ->setLevel($this->getGraylog2Priority($record->level));
// message length + system name length + 200 for padding / metadata // message length + system name length + 200 for padding / metadata
$len = 200 + strlen($record->message) + strlen($this->systemName); $len = 200 + \strlen($record->message) + \strlen($this->systemName);
if ($len > $this->maxLength) { if ($len > $this->maxLength) {
$message->setShortMessage(Utils::substr($record->message, 0, $this->maxLength)); $message->setShortMessage(Utils::substr($record->message, 0, $this->maxLength));
@@ -115,8 +115,8 @@ class GelfMessageFormatter extends NormalizerFormatter
} }
foreach ($extra as $key => $val) { foreach ($extra as $key => $val) {
$val = is_scalar($val) || null === $val ? $val : $this->toJson($val); $val = \is_scalar($val) || null === $val ? $val : $this->toJson($val);
$len = strlen($this->extraPrefix . $key . $val); $len = \strlen($this->extraPrefix . $key . $val);
if ($len > $this->maxLength) { if ($len > $this->maxLength) {
$message->setAdditional($this->extraPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength)); $message->setAdditional($this->extraPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength));
@@ -126,8 +126,8 @@ class GelfMessageFormatter extends NormalizerFormatter
} }
foreach ($context as $key => $val) { foreach ($context as $key => $val) {
$val = is_scalar($val) || null === $val ? $val : $this->toJson($val); $val = \is_scalar($val) || null === $val ? $val : $this->toJson($val);
$len = strlen($this->contextPrefix . $key . $val); $len = \strlen($this->contextPrefix . $key . $val);
if ($len > $this->maxLength) { if ($len > $this->maxLength) {
$message->setAdditional($this->contextPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength)); $message->setAdditional($this->contextPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength));

View File

@@ -132,7 +132,7 @@ class HtmlFormatter extends NormalizerFormatter
*/ */
protected function convertToString($data): string protected function convertToString($data): string
{ {
if (null === $data || is_scalar($data)) { if (null === $data || \is_scalar($data)) {
return (string) $data; return (string) $data;
} }

View File

@@ -154,13 +154,13 @@ class JsonFormatter extends NormalizerFormatter
return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization'; return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization';
} }
if (is_array($data)) { if (\is_array($data)) {
$normalized = []; $normalized = [];
$count = 1; $count = 1;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
if ($count++ > $this->maxNormalizeItemCount) { if ($count++ > $this->maxNormalizeItemCount) {
$normalized['...'] = 'Over '.$this->maxNormalizeItemCount.' items ('.count($data).' total), aborting normalization'; $normalized['...'] = 'Over '.$this->maxNormalizeItemCount.' items ('.\count($data).' total), aborting normalization';
break; break;
} }
@@ -170,7 +170,7 @@ class JsonFormatter extends NormalizerFormatter
return $normalized; return $normalized;
} }
if (is_object($data)) { if (\is_object($data)) {
if ($data instanceof \DateTimeInterface) { if ($data instanceof \DateTimeInterface) {
return $this->formatDate($data); return $this->formatDate($data);
} }
@@ -195,7 +195,7 @@ class JsonFormatter extends NormalizerFormatter
return $data; return $data;
} }
if (is_resource($data)) { if (\is_resource($data)) {
return parent::normalize($data); return parent::normalize($data);
} }

View File

@@ -226,11 +226,11 @@ class LineFormatter extends NormalizerFormatter
*/ */
protected function convertToString($data): string protected function convertToString($data): string
{ {
if (null === $data || is_bool($data)) { if (null === $data || \is_bool($data)) {
return var_export($data, true); return var_export($data, true);
} }
if (is_scalar($data)) { if (\is_scalar($data)) {
return (string) $data; return (string) $data;
} }
@@ -267,9 +267,9 @@ class LineFormatter extends NormalizerFormatter
} }
if (isset($e->detail)) { if (isset($e->detail)) {
if (is_string($e->detail)) { if (\is_string($e->detail)) {
$str .= ' detail: ' . $e->detail; $str .= ' detail: ' . $e->detail;
} elseif (is_object($e->detail) || is_array($e->detail)) { } elseif (\is_object($e->detail) || \is_array($e->detail)) {
$str .= ' detail: ' . $this->toJson($e->detail, true); $str .= ' detail: ' . $this->toJson($e->detail, true);
} }
} }

View File

@@ -36,7 +36,7 @@ class MongoDBFormatter implements FormatterInterface
$this->maxNestingLevel = max($maxNestingLevel, 0); $this->maxNestingLevel = max($maxNestingLevel, 0);
$this->exceptionTraceAsString = $exceptionTraceAsString; $this->exceptionTraceAsString = $exceptionTraceAsString;
$this->isLegacyMongoExt = extension_loaded('mongodb') && version_compare((string) phpversion('mongodb'), '1.1.9', '<='); $this->isLegacyMongoExt = \extension_loaded('mongodb') && version_compare((string) phpversion('mongodb'), '1.1.9', '<=');
} }
/** /**
@@ -82,9 +82,9 @@ class MongoDBFormatter implements FormatterInterface
$array[$name] = $this->formatDate($value, $nestingLevel + 1); $array[$name] = $this->formatDate($value, $nestingLevel + 1);
} elseif ($value instanceof \Throwable) { } elseif ($value instanceof \Throwable) {
$array[$name] = $this->formatException($value, $nestingLevel + 1); $array[$name] = $this->formatException($value, $nestingLevel + 1);
} elseif (is_array($value)) { } elseif (\is_array($value)) {
$array[$name] = $this->formatArray($value, $nestingLevel + 1); $array[$name] = $this->formatArray($value, $nestingLevel + 1);
} elseif (is_object($value) && !$value instanceof Type) { } elseif (\is_object($value) && !$value instanceof Type) {
$array[$name] = $this->formatObject($value, $nestingLevel + 1); $array[$name] = $this->formatObject($value, $nestingLevel + 1);
} }
} }

View File

@@ -40,7 +40,7 @@ class NormalizerFormatter implements FormatterInterface
public function __construct(?string $dateFormat = null) public function __construct(?string $dateFormat = null)
{ {
$this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat; $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
if (!function_exists('json_encode')) { if (!\function_exists('json_encode')) {
throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter'); throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
} }
} }
@@ -182,8 +182,8 @@ class NormalizerFormatter implements FormatterInterface
return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
} }
if (null === $data || is_scalar($data)) { if (null === $data || \is_scalar($data)) {
if (is_float($data)) { if (\is_float($data)) {
if (is_infinite($data)) { if (is_infinite($data)) {
return ($data > 0 ? '' : '-') . 'INF'; return ($data > 0 ? '' : '-') . 'INF';
} }
@@ -195,13 +195,13 @@ class NormalizerFormatter implements FormatterInterface
return $data; return $data;
} }
if (is_array($data)) { if (\is_array($data)) {
$normalized = []; $normalized = [];
$count = 1; $count = 1;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
if ($count++ > $this->maxNormalizeItemCount) { if ($count++ > $this->maxNormalizeItemCount) {
$normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.count($data).' total), aborting normalization'; $normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.\count($data).' total), aborting normalization';
break; break;
} }
@@ -215,7 +215,7 @@ class NormalizerFormatter implements FormatterInterface
return $this->formatDate($data); return $this->formatDate($data);
} }
if (is_object($data)) { if (\is_object($data)) {
if ($data instanceof Throwable) { if ($data instanceof Throwable) {
return $this->normalizeException($data, $depth); return $this->normalizeException($data, $depth);
} }
@@ -244,11 +244,11 @@ class NormalizerFormatter implements FormatterInterface
return [Utils::getClass($data) => $value]; return [Utils::getClass($data) => $value];
} }
if (is_resource($data)) { if (\is_resource($data)) {
return sprintf('[resource(%s)]', get_resource_type($data)); return sprintf('[resource(%s)]', get_resource_type($data));
} }
return '[unknown('.gettype($data).')]'; return '[unknown('.\gettype($data).')]';
} }
/** /**
@@ -286,9 +286,9 @@ class NormalizerFormatter implements FormatterInterface
} }
if (isset($e->detail)) { if (isset($e->detail)) {
if (is_string($e->detail)) { if (\is_string($e->detail)) {
$data['detail'] = $e->detail; $data['detail'] = $e->detail;
} elseif (is_object($e->detail) || is_array($e->detail)) { } elseif (\is_object($e->detail) || \is_array($e->detail)) {
$data['detail'] = $this->toJson($e->detail, true); $data['detail'] = $this->toJson($e->detail, true);
} }
} }

View File

@@ -40,7 +40,7 @@ class ScalarFormatter extends NormalizerFormatter
{ {
$normalized = $this->normalize($value); $normalized = $this->normalize($value);
if (is_array($normalized)) { if (\is_array($normalized)) {
return $this->toJson($normalized, true); return $this->toJson($normalized, true);
} }

View File

@@ -73,19 +73,19 @@ class WildfireFormatter extends NormalizerFormatter
$message = ['message' => $record->message]; $message = ['message' => $record->message];
$handleError = false; $handleError = false;
if (count($record->context) > 0) { if (\count($record->context) > 0) {
$message['context'] = $this->normalize($record->context); $message['context'] = $this->normalize($record->context);
$handleError = true; $handleError = true;
} }
if (count($record->extra) > 0) { if (\count($record->extra) > 0) {
$message['extra'] = $this->normalize($record->extra); $message['extra'] = $this->normalize($record->extra);
$handleError = true; $handleError = true;
} }
if (count($message) === 1) { if (\count($message) === 1) {
$message = reset($message); $message = reset($message);
} }
if (is_array($message) && isset($message['context']['table'])) { if (\is_array($message) && isset($message['context']['table'])) {
$type = 'TABLE'; $type = 'TABLE';
$label = $record->channel .': '. $record->message; $label = $record->channel .': '. $record->message;
$message = $message['context']['table']; $message = $message['context']['table'];
@@ -108,7 +108,7 @@ class WildfireFormatter extends NormalizerFormatter
// The message itself is a serialization of the above JSON object + it's length // The message itself is a serialization of the above JSON object + it's length
return sprintf( return sprintf(
'%d|%s|', '%d|%s|',
strlen($json), \strlen($json),
$json $json
); );
} }
@@ -130,7 +130,7 @@ class WildfireFormatter extends NormalizerFormatter
*/ */
protected function normalize(mixed $data, int $depth = 0): mixed protected function normalize(mixed $data, int $depth = 0): mixed
{ {
if (is_object($data) && !$data instanceof \DateTimeInterface) { if (\is_object($data) && !$data instanceof \DateTimeInterface) {
return $data; return $data;
} }

View File

@@ -55,7 +55,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
if (!defined('PHP_WINDOWS_VERSION_BUILD')) { if (!\defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->facilities['local0'] = \LOG_LOCAL0; $this->facilities['local0'] = \LOG_LOCAL0;
$this->facilities['local1'] = \LOG_LOCAL1; $this->facilities['local1'] = \LOG_LOCAL1;
$this->facilities['local2'] = \LOG_LOCAL2; $this->facilities['local2'] = \LOG_LOCAL2;
@@ -76,9 +76,9 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
} }
// convert textual description of facility to syslog constant // convert textual description of facility to syslog constant
if (is_string($facility) && array_key_exists(strtolower($facility), $this->facilities)) { if (\is_string($facility) && \array_key_exists(strtolower($facility), $this->facilities)) {
$facility = $this->facilities[strtolower($facility)]; $facility = $this->facilities[strtolower($facility)];
} elseif (!in_array($facility, array_values($this->facilities), true)) { } elseif (!\in_array($facility, array_values($this->facilities), true)) {
throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given'); throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given');
} }

View File

@@ -77,7 +77,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
return; return;
} }
if (count(static::$records) > 0) { if (\count(static::$records) > 0) {
if ($format === self::FORMAT_HTML) { if ($format === self::FORMAT_HTML) {
static::writeOutput('<script>' . self::generateScript() . '</script>'); static::writeOutput('<script>' . self::generateScript() . '</script>');
} else { // js format } else { // js format
@@ -213,7 +213,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
$args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0])); $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0]));
$pos = $match[0][1]; $pos = $match[0][1];
$format = Utils::substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . Utils::substr($format, $pos + strlen($match[0][0])); $format = Utils::substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . Utils::substr($format, $pos + \strlen($match[0][0]));
} }
$args[] = self::quote('font-weight: normal'); $args[] = self::quote('font-weight: normal');
@@ -231,7 +231,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
if (trim($m[1]) === 'autolabel') { if (trim($m[1]) === 'autolabel') {
// Format the string as a label with consistent auto assigned background color // Format the string as a label with consistent auto assigned background color
if (!isset($labels[$string])) { if (!isset($labels[$string])) {
$labels[$string] = $colors[count($labels) % count($colors)]; $labels[$string] = $colors[\count($labels) % \count($colors)];
} }
$color = $labels[$string]; $color = $labels[$string];
@@ -284,7 +284,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function call(...$args): string private static function call(...$args): string
{ {
$method = array_shift($args); $method = array_shift($args);
if (!is_string($method)) { if (!\is_string($method)) {
throw new \UnexpectedValueException('Expected the first arg to be a string, got: '.var_export($method, true)); throw new \UnexpectedValueException('Expected the first arg to be a string, got: '.var_export($method, true));
} }

View File

@@ -148,7 +148,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
return $this; return $this;
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.');
} }
/** /**
@@ -160,6 +160,6 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
return $this->handler->getFormatter(); return $this->handler->getFormatter();
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.');
} }
} }

View File

@@ -68,7 +68,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
if (!function_exists('json_encode')) { if (!\function_exists('json_encode')) {
throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s ChromePHPHandler'); throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s ChromePHPHandler');
} }
} }
@@ -149,7 +149,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
$json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true);
$data = base64_encode($json); $data = base64_encode($json);
if (strlen($data) > 3 * 1024) { if (\strlen($data) > 3 * 1024) {
self::$overflowed = true; self::$overflowed = true;
$record = new LogRecord( $record = new LogRecord(
@@ -158,7 +158,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
channel: 'monolog', channel: 'monolog',
datetime: new DateTimeImmutable(true), datetime: new DateTimeImmutable(true),
); );
self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record); self::$json['rows'][\count(self::$json['rows']) - 1] = $this->getFormatter()->format($record);
$json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true);
$data = base64_encode($json); $data = base64_encode($json);
} }

View File

@@ -47,7 +47,7 @@ class CubeHandler extends AbstractProcessingHandler
throw new \UnexpectedValueException('URL "'.$url.'" is not valid'); throw new \UnexpectedValueException('URL "'.$url.'" is not valid');
} }
if (!in_array($urlInfo['scheme'], $this->acceptedSchemes, true)) { if (!\in_array($urlInfo['scheme'], $this->acceptedSchemes, true)) {
throw new \UnexpectedValueException( throw new \UnexpectedValueException(
'Invalid protocol (' . $urlInfo['scheme'] . ').' 'Invalid protocol (' . $urlInfo['scheme'] . ').'
. ' Valid options are ' . implode(', ', $this->acceptedSchemes) . ' Valid options are ' . implode(', ', $this->acceptedSchemes)
@@ -69,7 +69,7 @@ class CubeHandler extends AbstractProcessingHandler
*/ */
protected function connectUdp(): void protected function connectUdp(): void
{ {
if (!extension_loaded('sockets')) { if (!\extension_loaded('sockets')) {
throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler'); throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler');
} }
@@ -92,7 +92,7 @@ class CubeHandler extends AbstractProcessingHandler
*/ */
protected function connectHttp(): void protected function connectHttp(): void
{ {
if (!extension_loaded('curl')) { if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is required to use http URLs with the CubeHandler'); throw new MissingExtensionException('The curl extension is required to use http URLs with the CubeHandler');
} }
@@ -143,7 +143,7 @@ class CubeHandler extends AbstractProcessingHandler
throw new \LogicException('No UDP socket could be opened'); throw new \LogicException('No UDP socket could be opened');
} }
socket_send($this->udpConnection, $data, strlen($data), 0); socket_send($this->udpConnection, $data, \strlen($data), 0);
} }
private function writeHttp(string $data): void private function writeHttp(string $data): void
@@ -159,7 +159,7 @@ class CubeHandler extends AbstractProcessingHandler
curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']'); curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']');
curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, [ curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, [
'Content-Type: application/json', 'Content-Type: application/json',
'Content-Length: ' . strlen('['.$data.']'), 'Content-Length: ' . \strlen('['.$data.']'),
]); ]);
Curl\Util::execute($this->httpConnection, 5, false); Curl\Util::execute($this->httpConnection, 5, false);

View File

@@ -44,7 +44,7 @@ final class Util
if ($curlResponse === false) { if ($curlResponse === false) {
$curlErrno = curl_errno($ch); $curlErrno = curl_errno($ch);
if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || $retries === 0) { if (false === \in_array($curlErrno, self::$retriableErrorCodes, true) || $retries === 0) {
$curlError = curl_error($ch); $curlError = curl_error($ch);
if ($closeAfterDone) { if ($closeAfterDone) {

View File

@@ -79,11 +79,11 @@ class DeduplicationHandler extends BufferHandler
foreach ($this->buffer as $record) { foreach ($this->buffer as $record) {
if ($record->level->value >= $this->deduplicationLevel->value) { if ($record->level->value >= $this->deduplicationLevel->value) {
$passthru = $passthru === true || !is_array($store) || !$this->isDuplicate($store, $record); $passthru = $passthru === true || !\is_array($store) || !$this->isDuplicate($store, $record);
if ($passthru) { if ($passthru) {
$line = $this->buildDeduplicationStoreEntry($record); $line = $this->buildDeduplicationStoreEntry($record);
file_put_contents($this->deduplicationStore, $line . "\n", FILE_APPEND); file_put_contents($this->deduplicationStore, $line . "\n", FILE_APPEND);
if (!is_array($store)) { if (!\is_array($store)) {
$store = []; $store = [];
} }
$store[] = $line; $store[] = $line;
@@ -113,7 +113,7 @@ class DeduplicationHandler extends BufferHandler
$expectedMessage = preg_replace('{[\r\n].*}', '', $record->message); $expectedMessage = preg_replace('{[\r\n].*}', '', $record->message);
$yesterday = time() - 86400; $yesterday = time() - 86400;
for ($i = count($store) - 1; $i >= 0; $i--) { for ($i = \count($store) - 1; $i >= 0; $i--) {
list($timestamp, $level, $message) = explode(':', $store[$i], 3); list($timestamp, $level, $message) = explode(':', $store[$i], 3);
if ($level === $record->level->getName() && $message === $expectedMessage && $timestamp > $timestampValidity) { if ($level === $record->level->getName() && $message === $expectedMessage && $timestamp > $timestampValidity) {
@@ -155,7 +155,7 @@ class DeduplicationHandler extends BufferHandler
while (!feof($handle)) { while (!feof($handle)) {
$log = fgets($handle); $log = fgets($handle);
if (is_string($log) && '' !== $log && substr($log, 0, 10) >= $timestampValidity) { if (\is_string($log) && '' !== $log && substr($log, 0, 10) >= $timestampValidity) {
$validLogs[] = $log; $validLogs[] = $log;
} }
} }

View File

@@ -40,7 +40,7 @@ class ErrorLogHandler extends AbstractProcessingHandler
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
if (false === in_array($messageType, self::getAvailableTypes(), true)) { if (false === \in_array($messageType, self::getAvailableTypes(), true)) {
$message = sprintf('The given message type "%s" is not supported', print_r($messageType, true)); $message = sprintf('The given message type "%s" is not supported', print_r($messageType, true));
throw new \InvalidArgumentException($message); throw new \InvalidArgumentException($message);

View File

@@ -87,7 +87,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
*/ */
public function setAcceptedLevels(int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency): self public function setAcceptedLevels(int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency): self
{ {
if (is_array($minLevelOrList)) { if (\is_array($minLevelOrList)) {
$acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList); $acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList);
} else { } else {
$minLevelOrList = Logger::toMonologLevel($minLevelOrList); $minLevelOrList = Logger::toMonologLevel($minLevelOrList);
@@ -140,8 +140,8 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
} }
} }
if (count($filtered) > 0) { if (\count($filtered) > 0) {
$this->getHandler($filtered[count($filtered) - 1])->handleBatch($filtered); $this->getHandler($filtered[\count($filtered) - 1])->handleBatch($filtered);
} }
} }
@@ -175,7 +175,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
return $this; return $this;
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.');
} }
/** /**
@@ -188,7 +188,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
return $handler->getFormatter(); return $handler->getFormatter();
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.');
} }
public function reset(): void public function reset(): void

View File

@@ -130,7 +130,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
if ($this->buffering) { if ($this->buffering) {
$this->buffer[] = $record; $this->buffer[] = $record;
if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) { if ($this->bufferSize > 0 && \count($this->buffer) > $this->bufferSize) {
array_shift($this->buffer); array_shift($this->buffer);
} }
if ($this->activationStrategy->isHandlerActivated($record)) { if ($this->activationStrategy->isHandlerActivated($record)) {
@@ -185,7 +185,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
$this->buffer = array_filter($this->buffer, static function ($record) use ($passthruLevel) { $this->buffer = array_filter($this->buffer, static function ($record) use ($passthruLevel) {
return $passthruLevel->includes($record->level); return $passthruLevel->includes($record->level);
}); });
if (count($this->buffer) > 0) { if (\count($this->buffer) > 0) {
$this->getHandler(end($this->buffer))->handleBatch($this->buffer); $this->getHandler(end($this->buffer))->handleBatch($this->buffer);
} }
} }
@@ -224,7 +224,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
return $this; return $this;
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.');
} }
/** /**
@@ -237,6 +237,6 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
return $handler->getFormatter(); return $handler->getFormatter();
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.');
} }
} }

View File

@@ -54,7 +54,7 @@ class FleepHookHandler extends SocketHandler
?float $connectionTimeout = null, ?float $connectionTimeout = null,
?int $chunkSize = null ?int $chunkSize = null
) { ) {
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');
} }
@@ -112,7 +112,7 @@ class FleepHookHandler extends SocketHandler
$header = "POST " . static::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n"; $header = "POST " . static::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n";
$header .= "Host: " . static::FLEEP_HOST . "\r\n"; $header .= "Host: " . static::FLEEP_HOST . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($content) . "\r\n"; $header .= "Content-Length: " . \strlen($content) . "\r\n";
$header .= "\r\n"; $header .= "\r\n";
return $header; return $header;

View File

@@ -46,7 +46,7 @@ class FlowdockHandler extends SocketHandler
?float $connectionTimeout = null, ?float $connectionTimeout = null,
?int $chunkSize = null ?int $chunkSize = null
) { ) {
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');
} }
@@ -119,7 +119,7 @@ class FlowdockHandler extends SocketHandler
$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";
$header .= "Content-Type: application/json\r\n"; $header .= "Content-Type: application/json\r\n";
$header .= "Content-Length: " . strlen($content) . "\r\n"; $header .= "Content-Length: " . \strlen($content) . "\r\n";
$header .= "\r\n"; $header .= "\r\n";
return $header; return $header;

View File

@@ -39,7 +39,7 @@ class IFTTTHandler extends AbstractProcessingHandler
*/ */
public function __construct(string $eventName, string $secretKey, int|string|Level $level = Level::Error, bool $bubble = true) public function __construct(string $eventName, string $secretKey, int|string|Level $level = Level::Error, bool $bubble = true)
{ {
if (!extension_loaded('curl')) { if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler');
} }

View File

@@ -43,7 +43,7 @@ class InsightOpsHandler extends SocketHandler
?float $connectionTimeout = null, ?float $connectionTimeout = null,
?int $chunkSize = null ?int $chunkSize = null
) { ) {
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 InsightOpsHandler'); throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for InsightOpsHandler');
} }

View File

@@ -40,7 +40,7 @@ class LogEntriesHandler extends SocketHandler
?float $connectionTimeout = null, ?float $connectionTimeout = null,
?int $chunkSize = null ?int $chunkSize = null
) { ) {
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');
} }

View File

@@ -50,7 +50,7 @@ class LogglyHandler extends AbstractProcessingHandler
*/ */
public function __construct(string $token, int|string|Level $level = Level::Debug, bool $bubble = true) public function __construct(string $token, int|string|Level $level = Level::Debug, bool $bubble = true)
{ {
if (!extension_loaded('curl')) { if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler');
} }
@@ -64,7 +64,7 @@ class LogglyHandler extends AbstractProcessingHandler
*/ */
protected function getCurlHandler(string $endpoint): CurlHandle protected function getCurlHandler(string $endpoint): CurlHandle
{ {
if (!array_key_exists($endpoint, $this->curlHandlers)) { if (!\array_key_exists($endpoint, $this->curlHandlers)) {
$this->curlHandlers[$endpoint] = $this->loadCurlHandle($endpoint); $this->curlHandlers[$endpoint] = $this->loadCurlHandle($endpoint);
} }
@@ -96,7 +96,7 @@ class LogglyHandler extends AbstractProcessingHandler
if ('' === $tag || [] === $tag) { if ('' === $tag || [] === $tag) {
$this->tag = []; $this->tag = [];
} else { } else {
$this->tag = is_array($tag) ? $tag : [$tag]; $this->tag = \is_array($tag) ? $tag : [$tag];
} }
return $this; return $this;
@@ -109,7 +109,7 @@ class LogglyHandler extends AbstractProcessingHandler
public function addTag(string|array $tag): self public function addTag(string|array $tag): self
{ {
if ('' !== $tag) { if ('' !== $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));
} }

View File

@@ -48,7 +48,7 @@ class LogmaticHandler extends SocketHandler
?float $connectionTimeout = null, ?float $connectionTimeout = null,
?int $chunkSize = null ?int $chunkSize = null
) { ) {
if ($useSSL && !extension_loaded('openssl')) { if ($useSSL && !\extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use SSL encrypted connection for LogmaticHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use SSL encrypted connection for LogmaticHandler');
} }

View File

@@ -79,9 +79,9 @@ class NewRelicHandler extends AbstractProcessingHandler
newrelic_notice_error($record->message); newrelic_notice_error($record->message);
} }
if (isset($record->formatted['context']) && is_array($record->formatted['context'])) { if (isset($record->formatted['context']) && \is_array($record->formatted['context'])) {
foreach ($record->formatted['context'] as $key => $parameter) { foreach ($record->formatted['context'] as $key => $parameter) {
if (is_array($parameter) && $this->explodeArrays) { if (\is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) { foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue); $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue);
} }
@@ -91,9 +91,9 @@ class NewRelicHandler extends AbstractProcessingHandler
} }
} }
if (isset($record->formatted['extra']) && is_array($record->formatted['extra'])) { if (isset($record->formatted['extra']) && \is_array($record->formatted['extra'])) {
foreach ($record->formatted['extra'] as $key => $parameter) { foreach ($record->formatted['extra'] as $key => $parameter) {
if (is_array($parameter) && $this->explodeArrays) { if (\is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) { foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue); $this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue);
} }
@@ -109,7 +109,7 @@ class NewRelicHandler extends AbstractProcessingHandler
*/ */
protected function isNewRelicEnabled(): bool protected function isNewRelicEnabled(): bool
{ {
return extension_loaded('newrelic'); return \extension_loaded('newrelic');
} }
/** /**
@@ -163,7 +163,7 @@ class NewRelicHandler extends AbstractProcessingHandler
*/ */
protected function setNewRelicParameter(string $key, $value): void 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);
} else { } else {
newrelic_add_custom_parameter($key, Utils::jsonEncode($value, null, true)); newrelic_add_custom_parameter($key, Utils::jsonEncode($value, null, true));

View File

@@ -122,7 +122,7 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter
return $this; return $this;
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.');
} }
/** /**
@@ -134,6 +134,6 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter
return $this->handler->getFormatter(); return $this->handler->getFormatter();
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($this->handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($this->handler).' does not support formatters.');
} }
} }

View File

@@ -96,7 +96,7 @@ class ProcessHandler extends AbstractProcessingHandler
*/ */
private function ensureProcessIsStarted(): void private function ensureProcessIsStarted(): void
{ {
if (is_resource($this->process) === false) { if (\is_resource($this->process) === false) {
$this->startProcess(); $this->startProcess();
$this->handleStartupErrors(); $this->handleStartupErrors();
@@ -129,7 +129,7 @@ class ProcessHandler extends AbstractProcessingHandler
$errors = $this->readProcessErrors(); $errors = $this->readProcessErrors();
if (is_resource($this->process) === false || $errors !== '') { if (\is_resource($this->process) === false || $errors !== '') {
throw new \UnexpectedValueException( throw new \UnexpectedValueException(
sprintf('The process "%s" could not be opened: ' . $errors, $this->command) sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
); );
@@ -175,7 +175,7 @@ class ProcessHandler extends AbstractProcessingHandler
*/ */
public function close(): void public function close(): void
{ {
if (is_resource($this->process)) { if (\is_resource($this->process)) {
foreach ($this->pipes as $pipe) { foreach ($this->pipes as $pipe) {
fclose($pipe); fclose($pipe);
} }

View File

@@ -145,7 +145,7 @@ class PushoverHandler extends SocketHandler
private function buildContent(LogRecord $record): string private function buildContent(LogRecord $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);
$message = ($this->useFormattedMessage) ? $record->formatted : $record->message; $message = ($this->useFormattedMessage) ? $record->formatted : $record->message;
$message = Utils::substr($message, 0, $maxMessageLength); $message = Utils::substr($message, 0, $maxMessageLength);
@@ -176,7 +176,7 @@ class PushoverHandler extends SocketHandler
$dataArray = array_merge($extra, $context, $dataArray); $dataArray = array_merge($extra, $context, $dataArray);
// Only pass sounds that are supported by the API // Only pass sounds that are supported by the API
if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds, true)) { if (isset($dataArray['sound']) && !\in_array($dataArray['sound'], $this->sounds, true)) {
unset($dataArray['sound']); unset($dataArray['sound']);
} }
@@ -188,7 +188,7 @@ class PushoverHandler extends SocketHandler
$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";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($content) . "\r\n"; $header .= "Content-Length: " . \strlen($content) . "\r\n";
$header .= "\r\n"; $header .= "\r\n";
return $header; return $header;

View File

@@ -69,7 +69,7 @@ class RedisHandler extends AbstractProcessingHandler
protected function writeCapped(LogRecord $record): void protected function writeCapped(LogRecord $record): void
{ {
if ($this->redisClient instanceof Redis) { if ($this->redisClient instanceof Redis) {
$mode = defined('Redis::MULTI') ? Redis::MULTI : 1; $mode = \defined('Redis::MULTI') ? Redis::MULTI : 1;
$this->redisClient->multi($mode) $this->redisClient->multi($mode)
->rPush($this->redisKey, $record->formatted) ->rPush($this->redisKey, $record->formatted)
->lTrim($this->redisKey, -$this->capSize, -1) ->lTrim($this->redisKey, -$this->capSize, -1)

View File

@@ -133,7 +133,7 @@ class RotatingFileHandler extends StreamHandler
return; return;
} }
if ($this->maxFiles >= count($logFiles)) { if ($this->maxFiles >= \count($logFiles)) {
// no files to remove // no files to remove
return; return;
} }
@@ -143,7 +143,7 @@ class RotatingFileHandler extends StreamHandler
return strcmp($b, $a); return strcmp($b, $a);
}); });
foreach (array_slice($logFiles, $this->maxFiles) as $file) { foreach (\array_slice($logFiles, $this->maxFiles) as $file) {
if (is_writable($file)) { if (is_writable($file)) {
// suppress errors here as unlink() might fail if two processes // suppress errors here as unlink() might fail if two processes
// are cleaning up/rotating at the same time // are cleaning up/rotating at the same time

View File

@@ -103,7 +103,7 @@ class SamplingHandler extends AbstractHandler implements ProcessableHandlerInter
return $this; return $this;
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.');
} }
/** /**
@@ -116,6 +116,6 @@ class SamplingHandler extends AbstractHandler implements ProcessableHandlerInter
return $handler->getFormatter(); return $handler->getFormatter();
} }
throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); throw new \UnexpectedValueException('The nested handler of type '.\get_class($handler).' does not support formatters.');
} }
} }

View File

@@ -57,7 +57,7 @@ class SendGridHandler extends MailHandler
*/ */
public function __construct(string $apiUser, string $apiKey, string $from, string|array $to, string $subject, int|string|Level $level = Level::Error, bool $bubble = true) public function __construct(string $apiUser, string $apiKey, string $from, string|array $to, string $subject, int|string|Level $level = Level::Error, bool $bubble = true)
{ {
if (!extension_loaded('curl')) { if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler');
} }

View File

@@ -321,7 +321,7 @@ class SlackRecord
*/ */
private function generateAttachmentField(string $title, $value): array private function generateAttachmentField(string $title, $value): array
{ {
$value = is_array($value) $value = \is_array($value)
? sprintf('```%s```', substr($this->stringify($value), 0, 1990)) ? sprintf('```%s```', substr($this->stringify($value), 0, 1990))
: $value; : $value;

View File

@@ -63,7 +63,7 @@ class SlackHandler extends SocketHandler
?float $connectionTimeout = null, ?float $connectionTimeout = null,
?int $chunkSize = null ?int $chunkSize = null
) { ) {
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');
} }
@@ -129,7 +129,7 @@ class SlackHandler extends SocketHandler
$dataArray = $this->slackRecord->getSlackData($record); $dataArray = $this->slackRecord->getSlackData($record);
$dataArray['token'] = $this->token; $dataArray['token'] = $this->token;
if (isset($dataArray['attachments']) && is_array($dataArray['attachments']) && \count($dataArray['attachments']) > 0) { if (isset($dataArray['attachments']) && \is_array($dataArray['attachments']) && \count($dataArray['attachments']) > 0) {
$dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']); $dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']);
} }
@@ -144,7 +144,7 @@ class SlackHandler extends SocketHandler
$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";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($content) . "\r\n"; $header .= "Content-Length: " . \strlen($content) . "\r\n";
$header .= "\r\n"; $header .= "\r\n";
return $header; return $header;
@@ -168,7 +168,7 @@ class SlackHandler extends SocketHandler
protected function finalizeWrite(): void protected function finalizeWrite(): void
{ {
$res = $this->getResource(); $res = $this->getResource();
if (is_resource($res)) { if (\is_resource($res)) {
@fread($res, 2048); @fread($res, 2048);
} }
$this->closeSocket(); $this->closeSocket();

View File

@@ -59,7 +59,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
bool $bubble = true, bool $bubble = true,
array $excludeFields = [] array $excludeFields = []
) { ) {
if (!extension_loaded('curl')) { if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler'); throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler');
} }

View File

@@ -63,7 +63,7 @@ class SocketHandler extends AbstractProcessingHandler
$this->validateTimeout($connectionTimeout); $this->validateTimeout($connectionTimeout);
} }
$this->connectionTimeout = $connectionTimeout ?? (float) ini_get('default_socket_timeout'); $this->connectionTimeout = $connectionTimeout ?? (float) \ini_get('default_socket_timeout');
$this->persistent = $persistent; $this->persistent = $persistent;
$this->validateTimeout($timeout); $this->validateTimeout($timeout);
$this->timeout = $timeout; $this->timeout = $timeout;
@@ -102,7 +102,7 @@ class SocketHandler extends AbstractProcessingHandler
*/ */
public function closeSocket(): void public function closeSocket(): void
{ {
if (is_resource($this->resource)) { if (\is_resource($this->resource)) {
fclose($this->resource); fclose($this->resource);
$this->resource = null; $this->resource = null;
} }
@@ -229,7 +229,7 @@ class SocketHandler extends AbstractProcessingHandler
*/ */
public function isConnected(): bool public function isConnected(): bool
{ {
return is_resource($this->resource) return \is_resource($this->resource)
&& !feof($this->resource); // on TCP - other party can close connection. && !feof($this->resource); // on TCP - other party can close connection.
} }
@@ -263,7 +263,7 @@ class SocketHandler extends AbstractProcessingHandler
$seconds = floor($this->timeout); $seconds = floor($this->timeout);
$microseconds = round(($this->timeout - $seconds) * 1e6); $microseconds = round(($this->timeout - $seconds) * 1e6);
if (!is_resource($this->resource)) { if (!\is_resource($this->resource)) {
throw new \LogicException('streamSetTimeout called but $this->resource is not a resource'); throw new \LogicException('streamSetTimeout called but $this->resource is not a resource');
} }
@@ -279,7 +279,7 @@ class SocketHandler extends AbstractProcessingHandler
*/ */
protected function streamSetChunkSize(): int|bool protected function streamSetChunkSize(): int|bool
{ {
if (!is_resource($this->resource)) { if (!\is_resource($this->resource)) {
throw new \LogicException('streamSetChunkSize called but $this->resource is not a resource'); throw new \LogicException('streamSetChunkSize called but $this->resource is not a resource');
} }
@@ -297,7 +297,7 @@ class SocketHandler extends AbstractProcessingHandler
*/ */
protected function fwrite(string $data): int|bool protected function fwrite(string $data): int|bool
{ {
if (!is_resource($this->resource)) { if (!\is_resource($this->resource)) {
throw new \LogicException('fwrite called but $this->resource is not a resource'); throw new \LogicException('fwrite called but $this->resource is not a resource');
} }
@@ -311,7 +311,7 @@ class SocketHandler extends AbstractProcessingHandler
*/ */
protected function streamGetMetadata(): array|bool protected function streamGetMetadata(): array|bool
{ {
if (!is_resource($this->resource)) { if (!\is_resource($this->resource)) {
throw new \LogicException('streamGetMetadata called but $this->resource is not a resource'); throw new \LogicException('streamGetMetadata called but $this->resource is not a resource');
} }
@@ -360,7 +360,7 @@ class SocketHandler extends AbstractProcessingHandler
} else { } else {
$resource = $this->fsockopen(); $resource = $this->fsockopen();
} }
if (is_bool($resource)) { if (\is_bool($resource)) {
throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)"); throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)");
} }
$this->resource = $resource; $this->resource = $resource;
@@ -382,7 +382,7 @@ class SocketHandler extends AbstractProcessingHandler
private function writeToSocket(string $data): void private function writeToSocket(string $data): void
{ {
$length = strlen($data); $length = \strlen($data);
$sent = 0; $sent = 0;
$this->lastSentBytes = $sent; $this->lastSentBytes = $sent;
while ($this->isConnected() && $sent < $length) { while ($this->isConnected() && $sent < $length) {
@@ -396,7 +396,7 @@ class SocketHandler extends AbstractProcessingHandler
} }
$sent += $chunk; $sent += $chunk;
$socketInfo = $this->streamGetMetadata(); $socketInfo = $this->streamGetMetadata();
if (is_array($socketInfo) && (bool) $socketInfo['timed_out']) { if (\is_array($socketInfo) && (bool) $socketInfo['timed_out']) {
throw new \RuntimeException("Write timed-out"); throw new \RuntimeException("Write timed-out");
} }

View File

@@ -44,12 +44,12 @@ class SqsHandler extends AbstractProcessingHandler
*/ */
protected function write(LogRecord $record): void protected function write(LogRecord $record): void
{ {
if (!isset($record->formatted) || 'string' !== gettype($record->formatted)) { if (!isset($record->formatted) || 'string' !== \gettype($record->formatted)) {
throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record)); throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record));
} }
$messageBody = $record->formatted; $messageBody = $record->formatted;
if (strlen($messageBody) >= static::MAX_MESSAGE_SIZE) { if (\strlen($messageBody) >= static::MAX_MESSAGE_SIZE) {
$messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE); $messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE);
} }

View File

@@ -48,7 +48,7 @@ class StreamHandler extends AbstractProcessingHandler
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
if (($phpMemoryLimit = Utils::expandIniShorthandBytes(ini_get('memory_limit'))) !== false) { if (($phpMemoryLimit = Utils::expandIniShorthandBytes(\ini_get('memory_limit'))) !== false) {
if ($phpMemoryLimit > 0) { if ($phpMemoryLimit > 0) {
// use max 10% of allowed memory for the chunk size, and at least 100KB // use max 10% of allowed memory for the chunk size, and at least 100KB
$this->streamChunkSize = min(static::MAX_CHUNK_SIZE, max((int) ($phpMemoryLimit / 10), 100 * 1024)); $this->streamChunkSize = min(static::MAX_CHUNK_SIZE, max((int) ($phpMemoryLimit / 10), 100 * 1024));
@@ -61,11 +61,11 @@ class StreamHandler extends AbstractProcessingHandler
$this->streamChunkSize = static::DEFAULT_CHUNK_SIZE; $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE;
} }
if (is_resource($stream)) { if (\is_resource($stream)) {
$this->stream = $stream; $this->stream = $stream;
stream_set_chunk_size($this->stream, $this->streamChunkSize); stream_set_chunk_size($this->stream, $this->streamChunkSize);
} elseif (is_string($stream)) { } elseif (\is_string($stream)) {
$this->url = Utils::canonicalizePath($stream); $this->url = Utils::canonicalizePath($stream);
} else { } else {
throw new \InvalidArgumentException('A stream must either be a resource or a string.'); throw new \InvalidArgumentException('A stream must either be a resource or a string.');
@@ -80,7 +80,7 @@ class StreamHandler extends AbstractProcessingHandler
*/ */
public function close(): void public function close(): void
{ {
if (null !== $this->url && is_resource($this->stream)) { if (null !== $this->url && \is_resource($this->stream)) {
fclose($this->stream); fclose($this->stream);
} }
$this->stream = null; $this->stream = null;
@@ -115,7 +115,7 @@ class StreamHandler extends AbstractProcessingHandler
*/ */
protected function write(LogRecord $record): void protected function write(LogRecord $record): void
{ {
if (!is_resource($this->stream)) { if (!\is_resource($this->stream)) {
$url = $this->url; $url = $this->url;
if (null === $url || '' === $url) { if (null === $url || '' === $url) {
throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().' . Utils::getRecordMessageForException($record)); throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().' . Utils::getRecordMessageForException($record));
@@ -133,7 +133,7 @@ class StreamHandler extends AbstractProcessingHandler
} finally { } finally {
restore_error_handler(); restore_error_handler();
} }
if (!is_resource($stream)) { if (!\is_resource($stream)) {
$this->stream = null; $this->stream = null;
throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url) . Utils::getRecordMessageForException($record)); throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url) . Utils::getRecordMessageForException($record));
@@ -175,11 +175,11 @@ class StreamHandler extends AbstractProcessingHandler
{ {
$pos = strpos($stream, '://'); $pos = strpos($stream, '://');
if ($pos === false) { if ($pos === false) {
return dirname($stream); return \dirname($stream);
} }
if ('file://' === substr($stream, 0, 7)) { if ('file://' === substr($stream, 0, 7)) {
return dirname(substr($stream, 7)); return \dirname(substr($stream, 7));
} }
return null; return null;

View File

@@ -76,7 +76,7 @@ class SymfonyMailerHandler extends MailHandler
$message = null; $message = null;
if ($this->emailTemplate instanceof Email) { if ($this->emailTemplate instanceof Email) {
$message = clone $this->emailTemplate; $message = clone $this->emailTemplate;
} elseif (is_callable($this->emailTemplate)) { } elseif (\is_callable($this->emailTemplate)) {
$message = ($this->emailTemplate)($content, $records); $message = ($this->emailTemplate)($content, $records);
} }

View File

@@ -65,12 +65,12 @@ class UdpSocket
protected function send(string $chunk): void protected function send(string $chunk): void
{ {
socket_sendto($this->getSocket(), $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port); socket_sendto($this->getSocket(), $chunk, \strlen($chunk), $flags = 0, $this->ip, $this->port);
} }
protected function assembleMessage(string $line, string $header): string protected function assembleMessage(string $line, string $header): string
{ {
$chunkSize = static::DATAGRAM_MAX_LENGTH - strlen($header); $chunkSize = static::DATAGRAM_MAX_LENGTH - \strlen($header);
return $header . Utils::substr($line, 0, $chunkSize); return $header . Utils::substr($line, 0, $chunkSize);
} }

View File

@@ -54,7 +54,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
*/ */
public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424)
{ {
if (!extension_loaded('sockets')) { if (!\extension_loaded('sockets')) {
throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler'); throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler');
} }
@@ -88,7 +88,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
*/ */
private function splitMessageIntoLines($message): array private function splitMessageIntoLines($message): array
{ {
if (is_array($message)) { if (\is_array($message)) {
$message = implode("\n", $message); $message = implode("\n", $message);
} }

View File

@@ -118,7 +118,7 @@ class TelegramBotHandler extends AbstractProcessingHandler
bool $delayBetweenMessages = false, bool $delayBetweenMessages = false,
int $topic = null int $topic = null
) { ) {
if (!extension_loaded('curl')) { if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler'); throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler');
} }
@@ -139,7 +139,7 @@ class TelegramBotHandler extends AbstractProcessingHandler
*/ */
public function setParseMode(string|null $parseMode = null): self public function setParseMode(string|null $parseMode = null): self
{ {
if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES, true)) { if ($parseMode !== null && !\in_array($parseMode, self::AVAILABLE_PARSE_MODES, true)) {
throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.'); throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.');
} }
@@ -271,7 +271,7 @@ class TelegramBotHandler extends AbstractProcessingHandler
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
$result = Curl\Util::execute($ch); $result = Curl\Util::execute($ch);
if (!is_string($result)) { if (!\is_string($result)) {
throw new RuntimeException('Telegram API error. Description: No response'); throw new RuntimeException('Telegram API error. Description: No response');
} }
$result = json_decode($result, true); $result = json_decode($result, true);
@@ -288,8 +288,8 @@ class TelegramBotHandler extends AbstractProcessingHandler
private function handleMessageLength(string $message): array private function handleMessageLength(string $message): array
{ {
$truncatedMarker = ' (...truncated)'; $truncatedMarker = ' (...truncated)';
if (!$this->splitLongMessages && strlen($message) > self::MAX_MESSAGE_LENGTH) { if (!$this->splitLongMessages && \strlen($message) > self::MAX_MESSAGE_LENGTH) {
return [Utils::substr($message, 0, self::MAX_MESSAGE_LENGTH - strlen($truncatedMarker)) . $truncatedMarker]; return [Utils::substr($message, 0, self::MAX_MESSAGE_LENGTH - \strlen($truncatedMarker)) . $truncatedMarker];
} }
return str_split($message, self::MAX_MESSAGE_LENGTH); return str_split($message, self::MAX_MESSAGE_LENGTH);

View File

@@ -119,7 +119,7 @@ class TestHandler extends AbstractProcessingHandler
*/ */
public function hasRecord(string|array $recordAssertions, Level $level): bool public function hasRecord(string|array $recordAssertions, Level $level): bool
{ {
if (is_string($recordAssertions)) { if (\is_string($recordAssertions)) {
$recordAssertions = ['message' => $recordAssertions]; $recordAssertions = ['message' => $recordAssertions];
} }
@@ -181,15 +181,15 @@ class TestHandler extends AbstractProcessingHandler
{ {
if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
$genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3];
$level = constant(Level::class.'::' . $matches[2]); $level = \constant(Level::class.'::' . $matches[2]);
$callback = [$this, $genericMethod]; $callback = [$this, $genericMethod];
if (is_callable($callback)) { if (\is_callable($callback)) {
$args[] = $level; $args[] = $level;
return call_user_func_array($callback, $args); return \call_user_func_array($callback, $args);
} }
} }
throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()'); throw new \BadMethodCallException('Call to undefined method ' . \get_class($this) . '::' . $method . '()');
} }
} }

View File

@@ -29,7 +29,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
*/ */
public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true)
{ {
if (!function_exists('zend_monitor_custom_event')) { if (!\function_exists('zend_monitor_custom_event')) {
throw new MissingExtensionException( throw new MissingExtensionException(
'You must have Zend Server installed with Zend Monitor enabled in order to use this handler' 'You must have Zend Server installed with Zend Monitor enabled in order to use this handler'
); );

View File

@@ -42,7 +42,7 @@ class LogRecord implements ArrayAccess
public function offsetSet(mixed $offset, mixed $value): void public function offsetSet(mixed $offset, mixed $value): void
{ {
if ($offset === 'extra') { if ($offset === 'extra') {
if (!is_array($value)) { if (!\is_array($value)) {
throw new \InvalidArgumentException('extra must be an array'); throw new \InvalidArgumentException('extra must be an array');
} }

View File

@@ -330,7 +330,7 @@ class Logger implements LoggerInterface, ResettableInterface
*/ */
public function addRecord(int|Level $level, string $message, array $context = [], DateTimeImmutable|null $datetime = null): bool public function addRecord(int|Level $level, string $message, array $context = [], DateTimeImmutable|null $datetime = null): bool
{ {
if (is_int($level) && isset(self::RFC_5424_LEVELS[$level])) { if (\is_int($level) && isset(self::RFC_5424_LEVELS[$level])) {
$level = self::RFC_5424_LEVELS[$level]; $level = self::RFC_5424_LEVELS[$level];
} }
@@ -352,7 +352,7 @@ class Logger implements LoggerInterface, ResettableInterface
} }
try { try {
$recordInitialized = count($this->processors) === 0; $recordInitialized = \count($this->processors) === 0;
$record = new LogRecord( $record = new LogRecord(
datetime: $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), datetime: $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
@@ -482,7 +482,7 @@ class Logger implements LoggerInterface, ResettableInterface
} }
if (\is_string($level)) { if (\is_string($level)) {
if (\is_numeric($level)) { if (is_numeric($level)) {
$levelEnum = Level::tryFrom((int) $level); $levelEnum = Level::tryFrom((int) $level);
if ($levelEnum === null) { if ($levelEnum === null) {
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES));
@@ -494,8 +494,8 @@ class Logger implements LoggerInterface, ResettableInterface
// Contains first char of all log levels and avoids using strtoupper() which may have // Contains first char of all log levels and avoids using strtoupper() which may have
// strange results depending on locale (for example, "i" will become "İ" in Turkish locale) // strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
$upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1)); $upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1));
if (defined(Level::class.'::'.$upper)) { if (\defined(Level::class.'::'.$upper)) {
return constant(Level::class . '::' . $upper); return \constant(Level::class . '::' . $upper);
} }
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES));
@@ -565,7 +565,7 @@ class Logger implements LoggerInterface, ResettableInterface
public function log($level, string|\Stringable $message, array $context = []): void public function log($level, string|\Stringable $message, array $context = []): void
{ {
if (!$level instanceof Level) { if (!$level instanceof Level) {
if (!is_string($level) && !is_int($level)) { if (!\is_string($level) && !\is_int($level)) {
throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance'); throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance');
} }

View File

@@ -63,7 +63,7 @@ class GitProcessor implements ProcessorInterface
} }
$branches = shell_exec('git branch -v --no-abbrev'); $branches = shell_exec('git branch -v --no-abbrev');
if (is_string($branches) && 1 === preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { if (\is_string($branches) && 1 === preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) {
return self::$cache = [ return self::$cache = [
'branch' => $matches[1], 'branch' => $matches[1],
'commit' => $matches[2], 'commit' => $matches[2],

View File

@@ -82,7 +82,7 @@ class IntrospectionProcessor implements ProcessorInterface
continue 2; continue 2;
} }
} }
} elseif (in_array($trace[$i]['function'], self::SKIP_FUNCTIONS, true)) { } elseif (\in_array($trace[$i]['function'], self::SKIP_FUNCTIONS, true)) {
$i++; $i++;
continue; continue;
@@ -117,6 +117,6 @@ class IntrospectionProcessor implements ProcessorInterface
return false; return false;
} }
return isset($trace[$index]['class']) || in_array($trace[$index]['function'], self::SKIP_FUNCTIONS, true); return isset($trace[$index]['class']) || \in_array($trace[$index]['function'], self::SKIP_FUNCTIONS, true);
} }
} }

View File

@@ -40,7 +40,7 @@ class LoadAverageProcessor implements ProcessorInterface
*/ */
public function __construct(int $avgSystemLoad = self::LOAD_1_MINUTE) public function __construct(int $avgSystemLoad = self::LOAD_1_MINUTE)
{ {
if (!in_array($avgSystemLoad, self::AVAILABLE_LOAD, true)) { if (!\in_array($avgSystemLoad, self::AVAILABLE_LOAD, true)) {
throw new \InvalidArgumentException(sprintf('Invalid average system load: `%s`', $avgSystemLoad)); throw new \InvalidArgumentException(sprintf('Invalid average system load: `%s`', $avgSystemLoad));
} }
$this->avgSystemLoad = $avgSystemLoad; $this->avgSystemLoad = $avgSystemLoad;
@@ -51,7 +51,7 @@ class LoadAverageProcessor implements ProcessorInterface
*/ */
public function __invoke(LogRecord $record): LogRecord public function __invoke(LogRecord $record): LogRecord
{ {
if (!function_exists('sys_getloadavg')) { if (!\function_exists('sys_getloadavg')) {
return $record; return $record;
} }
$usage = sys_getloadavg(); $usage = sys_getloadavg();

View File

@@ -63,7 +63,7 @@ class MercurialProcessor implements ProcessorInterface
$result = explode(' ', trim((string) shell_exec('hg id -nb'))); $result = explode(' ', trim((string) shell_exec('hg id -nb')));
if (count($result) >= 3) { if (\count($result) >= 3) {
return self::$cache = [ return self::$cache = [
'branch' => $result[1], 'branch' => $result[1],
'revision' => $result[2], 'revision' => $result[2],

View File

@@ -57,7 +57,7 @@ class PsrLogMessageProcessor implements ProcessorInterface
continue; continue;
} }
if (null === $val || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { if (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, "__toString"))) {
$replacements[$placeholder] = $val; $replacements[$placeholder] = $val;
} elseif ($val instanceof \DateTimeInterface) { } elseif ($val instanceof \DateTimeInterface) {
if (null === $this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) { if (null === $this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) {
@@ -69,12 +69,12 @@ class PsrLogMessageProcessor implements ProcessorInterface
} }
} elseif ($val instanceof \UnitEnum) { } elseif ($val instanceof \UnitEnum) {
$replacements[$placeholder] = $val instanceof \BackedEnum ? $val->value : $val->name; $replacements[$placeholder] = $val instanceof \BackedEnum ? $val->value : $val->name;
} elseif (is_object($val)) { } elseif (\is_object($val)) {
$replacements[$placeholder] = '[object '.Utils::getClass($val).']'; $replacements[$placeholder] = '[object '.Utils::getClass($val).']';
} elseif (is_array($val)) { } elseif (\is_array($val)) {
$replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true); $replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true);
} else { } else {
$replacements[$placeholder] = '['.gettype($val).']'; $replacements[$placeholder] = '['.\gettype($val).']';
} }
if ($this->removeUsedContextFields) { if ($this->removeUsedContextFields) {

View File

@@ -53,7 +53,7 @@ class UidProcessor implements ProcessorInterface, ResettableInterface
public function reset(): void public function reset(): void
{ {
$this->uid = $this->generateUid(strlen($this->uid)); $this->uid = $this->generateUid(\strlen($this->uid));
} }
/** /**

View File

@@ -65,7 +65,7 @@ class WebProcessor implements ProcessorInterface
} }
if (isset($extraFields[0])) { if (isset($extraFields[0])) {
foreach (array_keys($this->extraFields) as $fieldName) { foreach (array_keys($this->extraFields) as $fieldName) {
if (!in_array($fieldName, $extraFields, true)) { if (!\in_array($fieldName, $extraFields, true)) {
unset($this->extraFields[$fieldName]); unset($this->extraFields[$fieldName]);
} }
} }

View File

@@ -44,7 +44,7 @@ class SignalHandler
*/ */
public function registerSignalHandler(int $signo, int|string|Level $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self public function registerSignalHandler(int $signo, int|string|Level $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self
{ {
if (!extension_loaded('pcntl') || !function_exists('pcntl_signal')) { if (!\extension_loaded('pcntl') || !\function_exists('pcntl_signal')) {
return $this; return $this;
} }
@@ -76,10 +76,10 @@ class SignalHandler
/** @var array<int, string> $signals */ /** @var array<int, string> $signals */
static $signals = []; static $signals = [];
if (\count($signals) === 0 && extension_loaded('pcntl')) { if (\count($signals) === 0 && \extension_loaded('pcntl')) {
$pcntl = new ReflectionExtension('pcntl'); $pcntl = new ReflectionExtension('pcntl');
foreach ($pcntl->getConstants() as $name => $value) { foreach ($pcntl->getConstants() as $name => $value) {
if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && is_int($value)) { if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && \is_int($value)) {
$signals[$value] = $name; $signals[$value] = $name;
} }
} }
@@ -95,8 +95,8 @@ class SignalHandler
} }
if ($this->previousSignalHandler[$signo] === SIG_DFL) { if ($this->previousSignalHandler[$signo] === SIG_DFL) {
if (extension_loaded('pcntl') && function_exists('pcntl_signal') && function_exists('pcntl_sigprocmask') && function_exists('pcntl_signal_dispatch') if (\extension_loaded('pcntl') && \function_exists('pcntl_signal') && \function_exists('pcntl_sigprocmask') && \function_exists('pcntl_signal_dispatch')
&& extension_loaded('posix') && function_exists('posix_getpid') && function_exists('posix_kill') && \extension_loaded('posix') && \function_exists('posix_getpid') && \function_exists('posix_kill')
) { ) {
$restartSyscalls = $this->signalRestartSyscalls[$signo] ?? true; $restartSyscalls = $this->signalRestartSyscalls[$signo] ?? true;
pcntl_signal($signo, SIG_DFL, $restartSyscalls); pcntl_signal($signo, SIG_DFL, $restartSyscalls);
@@ -106,7 +106,7 @@ class SignalHandler
pcntl_sigprocmask(SIG_SETMASK, $oldset); pcntl_sigprocmask(SIG_SETMASK, $oldset);
pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls); pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls);
} }
} elseif (is_callable($this->previousSignalHandler[$signo])) { } elseif (\is_callable($this->previousSignalHandler[$signo])) {
$this->previousSignalHandler[$signo]($signo, $siginfo); $this->previousSignalHandler[$signo]($signo, $siginfo);
} }
} }

View File

@@ -19,12 +19,12 @@ final class Utils
{ {
$class = \get_class($object); $class = \get_class($object);
if (false === ($pos = \strpos($class, "@anonymous\0"))) { if (false === ($pos = strpos($class, "@anonymous\0"))) {
return $class; return $class;
} }
if (false === ($parent = \get_parent_class($class))) { if (false === ($parent = get_parent_class($class))) {
return \substr($class, 0, $pos + 10); return substr($class, 0, $pos + 10);
} }
return $parent . '@anonymous'; return $parent . '@anonymous';
@@ -32,11 +32,11 @@ final class Utils
public static function substr(string $string, int $start, ?int $length = null): string public static function substr(string $string, int $start, ?int $length = null): string
{ {
if (extension_loaded('mbstring')) { if (\extension_loaded('mbstring')) {
return mb_strcut($string, $start, $length); return mb_strcut($string, $start, $length);
} }
return substr($string, $start, (null === $length) ? strlen($string) : $length); return substr($string, $start, (null === $length) ? \strlen($string) : $length);
} }
/** /**
@@ -119,9 +119,9 @@ final class Utils
self::throwEncodeError($code, $data); self::throwEncodeError($code, $data);
} }
if (is_string($data)) { if (\is_string($data)) {
self::detectAndCleanUtf8($data); self::detectAndCleanUtf8($data);
} elseif (is_array($data)) { } elseif (\is_array($data)) {
array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']); array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']);
} else { } else {
self::throwEncodeError($code, $data); self::throwEncodeError($code, $data);
@@ -196,15 +196,15 @@ final class Utils
*/ */
private static function detectAndCleanUtf8(&$data): void private static function detectAndCleanUtf8(&$data): void
{ {
if (is_string($data) && preg_match('//u', $data) !== 1) { if (\is_string($data) && preg_match('//u', $data) !== 1) {
$data = preg_replace_callback( $data = preg_replace_callback(
'/[\x80-\xFF]+/', '/[\x80-\xFF]+/',
function (array $m): string { function (array $m): string {
return function_exists('mb_convert_encoding') ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') : utf8_encode($m[0]); return \function_exists('mb_convert_encoding') ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') : utf8_encode($m[0]);
}, },
$data $data
); );
if (!is_string($data)) { if (!\is_string($data)) {
$pcreErrorCode = preg_last_error(); $pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode)); throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode));
@@ -225,7 +225,7 @@ final class Utils
*/ */
public static function expandIniShorthandBytes($val) public static function expandIniShorthandBytes($val)
{ {
if (!is_string($val)) { if (!\is_string($val)) {
return false; return false;
} }

View File

@@ -37,7 +37,7 @@ class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
try { try {
$errHandler->registerErrorHandler([], true); $errHandler->registerErrorHandler([], true);
$prop = $this->getPrivatePropertyValue($errHandler, 'previousErrorHandler'); $prop = $this->getPrivatePropertyValue($errHandler, 'previousErrorHandler');
$this->assertTrue(is_callable($prop)); $this->assertTrue(\is_callable($prop));
$this->assertSame($prevHandler, $prop); $this->assertSame($prevHandler, $prop);
$resHandler = $errHandler->registerErrorHandler([E_USER_NOTICE => LogLevel::EMERGENCY], false); $resHandler = $errHandler->registerErrorHandler([E_USER_NOTICE => LogLevel::EMERGENCY], false);
@@ -66,7 +66,7 @@ class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
protected function getPrivatePropertyValue($instance, $property) protected function getPrivatePropertyValue($instance, $property)
{ {
$ref = new \ReflectionClass(get_class($instance)); $ref = new \ReflectionClass(\get_class($instance));
$prop = $ref->getProperty($property); $prop = $ref->getProperty($property);
$prop->setAccessible(true); $prop->setAccessible(true);
@@ -105,7 +105,7 @@ class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
$errHandler->registerExceptionHandler([], true); $errHandler->registerExceptionHandler([], true);
$prop = $this->getPrivatePropertyValue($errHandler, 'previousExceptionHandler'); $prop = $this->getPrivatePropertyValue($errHandler, 'previousExceptionHandler');
$this->assertTrue(is_callable($prop)); $this->assertTrue(\is_callable($prop));
} }
public function testCodeToString() public function testCodeToString()

View File

@@ -193,8 +193,8 @@ class GelfMessageFormatterTest extends TestCase
$length = 200; $length = 200;
foreach ($messageArray as $key => $value) { foreach ($messageArray as $key => $value) {
if (!in_array($key, ['level', 'timestamp']) && is_string($value)) { if (!\in_array($key, ['level', 'timestamp']) && \is_string($value)) {
$length += strlen($value); $length += \strlen($value);
} }
} }
@@ -219,8 +219,8 @@ class GelfMessageFormatterTest extends TestCase
$length = 200; $length = 200;
foreach ($messageArray as $key => $value) { foreach ($messageArray as $key => $value) {
if (!in_array($key, ['level', 'timestamp'])) { if (!\in_array($key, ['level', 'timestamp'])) {
$length += strlen($value); $length += \strlen($value);
} }
} }

View File

@@ -244,7 +244,7 @@ class JsonFormatterTest extends TestCase
private function formatException($exception, ?string $previous = null): string private function formatException($exception, ?string $previous = null): string
{ {
$formattedException = $formattedException =
'{"class":"' . get_class($exception) . '{"class":"' . \get_class($exception) .
'","message":"' . $exception->getMessage() . '","message":"' . $exception->getMessage() .
'","code":' . $exception->getCode() . '","code":' . $exception->getCode() .
',"file":"' . $this->formatExceptionFilePathWithLine($exception) . ',"file":"' . $this->formatExceptionFilePathWithLine($exception) .

View File

@@ -296,7 +296,7 @@ class LineFormatterTest extends TestCase
{ {
$formatter = new LineFormatter(); $formatter = new LineFormatter();
$formatter->includeStacktraces(); $formatter->includeStacktraces();
$formatter->setBasePath(dirname(dirname(dirname(__DIR__)))); $formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
$formatter->indentStackTraces(' '); $formatter->indentStackTraces(' ');
$message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')])); $message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));

View File

@@ -67,13 +67,13 @@ class NormalizerFormatterTest extends TestCase
'exception' => $e2, 'exception' => $e2,
]); ]);
$this->assertGreaterThan(5, count($formatted['exception']['trace'])); $this->assertGreaterThan(5, \count($formatted['exception']['trace']));
$this->assertTrue(isset($formatted['exception']['previous'])); $this->assertTrue(isset($formatted['exception']['previous']));
unset($formatted['exception']['trace'], $formatted['exception']['previous']); unset($formatted['exception']['trace'], $formatted['exception']['previous']);
$this->assertEquals([ $this->assertEquals([
'exception' => [ 'exception' => [
'class' => get_class($e2), 'class' => \get_class($e2),
'message' => $e2->getMessage(), 'message' => $e2->getMessage(),
'code' => $e2->getCode(), 'code' => $e2->getCode(),
'file' => $e2->getFile().':'.$e2->getLine(), 'file' => $e2->getFile().':'.$e2->getLine(),
@@ -416,7 +416,7 @@ class NormalizerFormatterTest extends TestCase
{ {
try { try {
$arg = new TestInfoLeak; $arg = new TestInfoLeak;
call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime()); \call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
} catch (\Exception $e) { } catch (\Exception $e) {
} }

View File

@@ -69,7 +69,7 @@ class ScalarFormatterTest extends TestCase
'bat' => ['foo' => 'bar'], 'bat' => ['foo' => 'bar'],
'bap' => (string) $dt, 'bap' => (string) $dt,
'ban' => [ 'ban' => [
'class' => get_class($exception), 'class' => \get_class($exception),
'message' => $exception->getMessage(), 'message' => $exception->getMessage(),
'code' => $exception->getCode(), 'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(), 'file' => $exception->getFile() . ':' . $exception->getLine(),
@@ -97,7 +97,7 @@ class ScalarFormatterTest extends TestCase
$this->assertSame($this->encodeJson([ $this->assertSame($this->encodeJson([
'exception' => [ 'exception' => [
'class' => get_class($exception), 'class' => \get_class($exception),
'message' => $exception->getMessage(), 'message' => $exception->getMessage(),
'code' => $exception->getCode(), 'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(), 'file' => $exception->getFile() . ':' . $exception->getLine(),

View File

@@ -87,7 +87,7 @@ class AbstractProcessingHandlerTest extends TestCase
}) })
; ;
$handler->handle($this->getRecord()); $handler->handle($this->getRecord());
$this->assertEquals(6, count($handledRecord['extra'])); $this->assertEquals(6, \count($handledRecord['extra']));
} }
/** /**

View File

@@ -27,7 +27,7 @@ class DynamoDbHandlerTest extends TestCase
$this->markTestSkipped('aws/aws-sdk-php not installed'); $this->markTestSkipped('aws/aws-sdk-php not installed');
} }
$this->isV3 = defined('Aws\Sdk::VERSION') && version_compare(\Aws\Sdk::VERSION, '3.0', '>='); $this->isV3 = \defined('Aws\Sdk::VERSION') && version_compare(\Aws\Sdk::VERSION, '3.0', '>=');
$implementedMethods = ['__call']; $implementedMethods = ['__call'];

View File

@@ -17,7 +17,7 @@ use Monolog\Formatter\LineFormatter;
function error_log() function error_log()
{ {
$GLOBALS['error_log'][] = func_get_args(); $GLOBALS['error_log'][] = \func_get_args();
} }
class ErrorLogHandlerTest extends TestCase class ErrorLogHandlerTest extends TestCase

View File

@@ -31,7 +31,7 @@ class FleepHookHandlerTest extends TestCase
{ {
parent::setUp(); parent::setUp();
if (!extension_loaded('openssl')) { if (!\extension_loaded('openssl')) {
$this->markTestSkipped('This test requires openssl extension to run'); $this->markTestSkipped('This test requires openssl extension to run');
} }

View File

@@ -30,7 +30,7 @@ class FlowdockHandlerTest extends TestCase
public function setUp(): void public function setUp(): void
{ {
if (!extension_loaded('openssl')) { if (!\extension_loaded('openssl')) {
$this->markTestSkipped('This test requires openssl to run'); $this->markTestSkipped('This test requires openssl to run');
} }
} }

View File

@@ -59,7 +59,7 @@ class InsightOpsHandlerTest extends TestCase
private function createHandler() private function createHandler()
{ {
$useSSL = extension_loaded('openssl'); $useSSL = \extension_loaded('openssl');
$args = ['testToken', 'us', $useSSL, Level::Debug, true]; $args = ['testToken', 'us', $useSSL, Level::Debug, true];
$this->resource = fopen('php://memory', 'a'); $this->resource = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder(InsightOpsHandler::class) $this->handler = $this->getMockBuilder(InsightOpsHandler::class)

View File

@@ -63,7 +63,7 @@ class LogEntriesHandlerTest extends TestCase
private function createHandler() private function createHandler()
{ {
$useSSL = extension_loaded('openssl'); $useSSL = \extension_loaded('openssl');
$args = ['testToken', $useSSL, Level::Debug, true]; $args = ['testToken', $useSSL, Level::Debug, true];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder('Monolog\Handler\LogEntriesHandler') $this->handler = $this->getMockBuilder('Monolog\Handler\LogEntriesHandler')

View File

@@ -63,7 +63,7 @@ class LogmaticHandlerTest extends TestCase
private function createHandler() private function createHandler()
{ {
$useSSL = extension_loaded('openssl'); $useSSL = \extension_loaded('openssl');
$args = ['testToken', 'testHostname', 'testAppname', $useSSL, Level::Debug, true]; $args = ['testToken', 'testHostname', 'testAppname', $useSSL, Level::Debug, true];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder('Monolog\Handler\LogmaticHandler') $this->handler = $this->getMockBuilder('Monolog\Handler\LogmaticHandler')

View File

@@ -16,7 +16,7 @@ use Monolog\Test\TestCase;
function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
{ {
$GLOBALS['mail'][] = func_get_args(); $GLOBALS['mail'][] = \func_get_args();
} }
class NativeMailerHandlerTest extends TestCase class NativeMailerHandlerTest extends TestCase

View File

@@ -143,7 +143,7 @@ class PHPConsoleHandlerTest extends TestCase
$message = 'test'; $message = 'test';
$tag = 'tag'; $tag = 'tag';
$context = [$tag, 'custom' => mt_rand()]; $context = [$tag, 'custom' => mt_rand()];
$expectedMessage = $message . ' ' . json_encode(array_slice($context, 1)); $expectedMessage = $message . ' ' . json_encode(\array_slice($context, 1));
$this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with( $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
$this->equalTo($expectedMessage), $this->equalTo($expectedMessage),
$this->equalTo($tag) $this->equalTo($tag)
@@ -197,7 +197,7 @@ class PHPConsoleHandlerTest extends TestCase
$handler = $this->initLogger(); $handler = $this->initLogger();
$handler->log( $handler->log(
\Psr\Log\LogLevel::ERROR, \Psr\Log\LogLevel::ERROR,
sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), sprintf('Uncaught Exception %s: "%s" at %s line %s', \get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
['exception' => $e] ['exception' => $e]
); );
} }

View File

@@ -190,11 +190,11 @@ class ProcessHandlerTest extends TestCase
$handler->handle($this->getRecord(Level::Warning, '21 is only the half truth')); $handler->handle($this->getRecord(Level::Warning, '21 is only the half truth'));
$process = $property->getValue($handler); $process = $property->getValue($handler);
$this->assertTrue(is_resource($process), 'Process is not running although it should.'); $this->assertTrue(\is_resource($process), 'Process is not running although it should.');
$handler->close(); $handler->close();
$process = $property->getValue($handler); $process = $property->getValue($handler);
$this->assertFalse(is_resource($process), 'Process is still running although it should not.'); $this->assertFalse(\is_resource($process), 'Process is still running although it should not.');
} }
} }

View File

@@ -64,7 +64,7 @@ class RotatingFileHandlerTest extends TestCase
throw new InvalidArgumentException("$directory must be a directory"); throw new InvalidArgumentException("$directory must be a directory");
} }
if (substr($directory, strlen($directory) - 1, 1) !== '/') { if (substr($directory, \strlen($directory) - 1, 1) !== '/') {
$directory .= '/'; $directory .= '/';
} }
@@ -169,7 +169,7 @@ class RotatingFileHandlerTest extends TestCase
private function createDeep($file) private function createDeep($file)
{ {
mkdir(dirname($file), 0777, true); mkdir(\dirname($file), 0777, true);
touch($file); touch($file);
return $file; return $file;

View File

@@ -25,7 +25,7 @@ class SamplingHandlerTest extends TestCase
for ($i = 0; $i < 10000; $i++) { for ($i = 0; $i < 10000; $i++) {
$handler->handle($this->getRecord()); $handler->handle($this->getRecord());
} }
$count = count($testHandler->getRecords()); $count = \count($testHandler->getRecords());
// $count should be half of 10k, so between 4k and 6k // $count should be half of 10k, so between 4k and 6k
$this->assertLessThan(6000, $count); $this->assertLessThan(6000, $count);
$this->assertGreaterThan(4000, $count); $this->assertGreaterThan(4000, $count);

View File

@@ -32,7 +32,7 @@ class SlackHandlerTest extends TestCase
public function setUp(): void public function setUp(): void
{ {
if (!extension_loaded('openssl')) { if (!\extension_loaded('openssl')) {
$this->markTestSkipped('This test requires openssl to run'); $this->markTestSkipped('This test requires openssl to run');
} }
} }

View File

@@ -198,7 +198,7 @@ class SocketHandlerTest extends TestCase
$callback = function ($string) use ($res) { $callback = function ($string) use ($res) {
fclose($res); fclose($res);
return strlen('Hello'); return \strlen('Hello');
}; };
$this->handler->expects($this->exactly(1)) $this->handler->expects($this->exactly(1))
@@ -249,7 +249,7 @@ class SocketHandlerTest extends TestCase
$this->writeRecord('Hello world'); $this->writeRecord('Hello world');
$this->assertIsResource($this->res); $this->assertIsResource($this->res);
$this->handler->close(); $this->handler->close();
$this->assertFalse(is_resource($this->res), "Expected resource to be closed after closing handler"); $this->assertFalse(\is_resource($this->res), "Expected resource to be closed after closing handler");
} }
public function testCloseDoesNotClosePersistentSocket() public function testCloseDoesNotClosePersistentSocket()
@@ -257,9 +257,9 @@ class SocketHandlerTest extends TestCase
$this->setMockHandler(); $this->setMockHandler();
$this->handler->setPersistent(true); $this->handler->setPersistent(true);
$this->writeRecord('Hello world'); $this->writeRecord('Hello world');
$this->assertTrue(is_resource($this->res)); $this->assertTrue(\is_resource($this->res));
$this->handler->close(); $this->handler->close();
$this->assertTrue(is_resource($this->res)); $this->assertTrue(\is_resource($this->res));
} }
public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds() public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds()
@@ -308,25 +308,25 @@ class SocketHandlerTest extends TestCase
->setConstructorArgs(['localhost:1234']) ->setConstructorArgs(['localhost:1234'])
->getMock(); ->getMock();
if (!in_array('fsockopen', $methods)) { if (!\in_array('fsockopen', $methods)) {
$this->handler->expects($this->any()) $this->handler->expects($this->any())
->method('fsockopen') ->method('fsockopen')
->willReturn($this->res); ->willReturn($this->res);
} }
if (!in_array('pfsockopen', $methods)) { if (!\in_array('pfsockopen', $methods)) {
$this->handler->expects($this->any()) $this->handler->expects($this->any())
->method('pfsockopen') ->method('pfsockopen')
->willReturn($this->res); ->willReturn($this->res);
} }
if (!in_array('streamSetTimeout', $methods)) { if (!\in_array('streamSetTimeout', $methods)) {
$this->handler->expects($this->any()) $this->handler->expects($this->any())
->method('streamSetTimeout') ->method('streamSetTimeout')
->willReturn(true); ->willReturn(true);
} }
if (!in_array('streamSetChunkSize', $methods)) { if (!\in_array('streamSetChunkSize', $methods)) {
$this->handler->expects($this->any()) $this->handler->expects($this->any())
->method('streamSetChunkSize') ->method('streamSetChunkSize')
->willReturn(8192); ->willReturn(8192);

View File

@@ -40,9 +40,9 @@ class StreamHandlerTest extends TestCase
{ {
$handle = fopen('php://memory', 'a+'); $handle = fopen('php://memory', 'a+');
$handler = new StreamHandler($handle); $handler = new StreamHandler($handle);
$this->assertTrue(is_resource($handle)); $this->assertTrue(\is_resource($handle));
$handler->close(); $handler->close();
$this->assertTrue(is_resource($handle)); $this->assertTrue(\is_resource($handle));
} }
/** /**
@@ -54,9 +54,9 @@ class StreamHandlerTest extends TestCase
$handler->handle($this->getRecord(Level::Warning, 'test')); $handler->handle($this->getRecord(Level::Warning, 'test'));
$stream = $handler->getStream(); $stream = $handler->getStream();
$this->assertTrue(is_resource($stream)); $this->assertTrue(\is_resource($stream));
$handler->close(); $handler->close();
$this->assertFalse(is_resource($stream)); $this->assertFalse(\is_resource($stream));
} }
/** /**
@@ -69,17 +69,17 @@ class StreamHandlerTest extends TestCase
$handler->handle($this->getRecord(Level::Warning, 'testfoo')); $handler->handle($this->getRecord(Level::Warning, 'testfoo'));
$stream = $handler->getStream(); $stream = $handler->getStream();
$this->assertTrue(is_resource($stream)); $this->assertTrue(\is_resource($stream));
fseek($stream, 0); fseek($stream, 0);
$this->assertStringContainsString('testfoo', stream_get_contents($stream)); $this->assertStringContainsString('testfoo', stream_get_contents($stream));
$serialized = serialize($handler); $serialized = serialize($handler);
$this->assertFalse(is_resource($stream)); $this->assertFalse(\is_resource($stream));
$handler = unserialize($serialized); $handler = unserialize($serialized);
$handler->handle($this->getRecord(Level::Warning, 'testbar')); $handler->handle($this->getRecord(Level::Warning, 'testbar'));
$stream = $handler->getStream(); $stream = $handler->getStream();
$this->assertTrue(is_resource($stream)); $this->assertTrue(\is_resource($stream));
fseek($stream, 0); fseek($stream, 0);
$contents = stream_get_contents($stream); $contents = stream_get_contents($stream);
$this->assertStringNotContainsString('testfoo', $contents); $this->assertStringNotContainsString('testfoo', $contents);
@@ -212,7 +212,7 @@ STRING;
#[DataProvider('provideNonExistingAndNotCreatablePath')] #[DataProvider('provideNonExistingAndNotCreatablePath')]
public function testWriteNonExistingAndNotCreatablePath($nonExistingAndNotCreatablePath) public function testWriteNonExistingAndNotCreatablePath($nonExistingAndNotCreatablePath)
{ {
if (defined('PHP_WINDOWS_VERSION_BUILD')) { if (\defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->markTestSkipped('Permissions checks can not run on windows'); $this->markTestSkipped('Permissions checks can not run on windows');
} }

View File

@@ -68,7 +68,7 @@ class SymfonyMailerHandlerTest extends TestCase
// Callback dynamically changes subject based on number of logged records // Callback dynamically changes subject based on number of logged records
$callback = function ($content, array $records) use ($expectedMessage) { $callback = function ($content, array $records) use ($expectedMessage) {
$subject = count($records) > 0 ? 'Emergency' : 'Normal'; $subject = \count($records) > 0 ? 'Emergency' : 'Normal';
return $expectedMessage->subject($subject); return $expectedMessage->subject($subject);
}; };
$handler = new SymfonyMailerHandler($this->mailer, $callback); $handler = new SymfonyMailerHandler($this->mailer, $callback);

View File

@@ -17,7 +17,7 @@ class ZendMonitorHandlerTest extends TestCase
{ {
public function setUp(): void public function setUp(): void
{ {
if (!function_exists('zend_monitor_custom_event')) { if (!\function_exists('zend_monitor_custom_event')) {
$this->markTestSkipped('ZendServer is not installed'); $this->markTestSkipped('ZendServer is not installed');
} }
} }

View File

@@ -746,7 +746,7 @@ class LoggerTest extends TestCase
$logger->pushProcessor($processorUid2); $logger->pushProcessor($processorUid2);
$getProperty = function ($object, $property) { $getProperty = function ($object, $property) {
$reflectionProperty = new \ReflectionProperty(get_class($object), $property); $reflectionProperty = new \ReflectionProperty(\get_class($object), $property);
$reflectionProperty->setAccessible(true); $reflectionProperty->setAccessible(true);
return $reflectionProperty->getValue($object); return $reflectionProperty->getValue($object);

View File

@@ -25,7 +25,7 @@ class GitProcessorTest extends TestCase
$record = $processor($this->getRecord()); $record = $processor($this->getRecord());
$this->assertArrayHasKey('git', $record->extra); $this->assertArrayHasKey('git', $record->extra);
$this->assertTrue(!is_array($record->extra['git']['branch'])); $this->assertTrue(!\is_array($record->extra['git']['branch']));
} }
/** /**

View File

@@ -20,7 +20,7 @@ class MercurialProcessorTest extends TestCase
*/ */
public function testProcessor() public function testProcessor()
{ {
if (defined('PHP_WINDOWS_VERSION_BUILD')) { if (\defined('PHP_WINDOWS_VERSION_BUILD')) {
exec("where hg 2>NUL", $output, $result); exec("where hg 2>NUL", $output, $result);
} else { } else {
exec("which hg 2>/dev/null >/dev/null", $output, $result); exec("which hg 2>/dev/null >/dev/null", $output, $result);
@@ -36,7 +36,7 @@ class MercurialProcessorTest extends TestCase
$record = $processor($this->getRecord()); $record = $processor($this->getRecord());
$this->assertArrayHasKey('hg', $record->extra); $this->assertArrayHasKey('hg', $record->extra);
$this->assertTrue(!is_array($record->extra['hg']['branch'])); $this->assertTrue(!\is_array($record->extra['hg']['branch']));
$this->assertTrue(!is_array($record->extra['hg']['revision'])); $this->assertTrue(!\is_array($record->extra['hg']['revision']));
} }
} }

View File

@@ -28,6 +28,6 @@ class UidProcessorTest extends TestCase
public function testGetUid() public function testGetUid()
{ {
$processor = new UidProcessor(10); $processor = new UidProcessor(10);
$this->assertEquals(10, strlen($processor->getUid())); $this->assertEquals(10, \strlen($processor->getUid()));
} }
} }

View File

@@ -30,11 +30,11 @@ class SignalHandlerTest extends TestCase
protected function setUp(): void protected function setUp(): void
{ {
$this->signalHandlers = []; $this->signalHandlers = [];
if (extension_loaded('pcntl')) { if (\extension_loaded('pcntl')) {
if (function_exists('pcntl_async_signals')) { if (\function_exists('pcntl_async_signals')) {
$this->asyncSignalHandling = pcntl_async_signals(); $this->asyncSignalHandling = pcntl_async_signals();
} }
if (function_exists('pcntl_sigprocmask')) { if (\function_exists('pcntl_sigprocmask')) {
pcntl_sigprocmask(SIG_SETMASK, [], $this->blockedSignals); pcntl_sigprocmask(SIG_SETMASK, [], $this->blockedSignals);
} }
} }
@@ -62,7 +62,7 @@ class SignalHandlerTest extends TestCase
private function setSignalHandler($signo, $handler = SIG_DFL) private function setSignalHandler($signo, $handler = SIG_DFL)
{ {
if (function_exists('pcntl_signal_get_handler')) { if (\function_exists('pcntl_signal_get_handler')) {
$this->signalHandlers[$signo] = pcntl_signal_get_handler($signo); $this->signalHandlers[$signo] = pcntl_signal_get_handler($signo);
} else { } else {
$this->signalHandlers[$signo] = SIG_DFL; $this->signalHandlers[$signo] = SIG_DFL;
@@ -95,7 +95,7 @@ class SignalHandlerTest extends TestCase
public function testRegisterSignalHandler() public function testRegisterSignalHandler()
{ {
// SIGCONT and SIGURG should be ignored by default. // SIGCONT and SIGURG should be ignored by default.
if (!defined('SIGCONT') || !defined('SIGURG')) { if (!\defined('SIGCONT') || !\defined('SIGURG')) {
$this->markTestSkipped('This test requires the SIGCONT and SIGURG pcntl constants.'); $this->markTestSkipped('This test requires the SIGCONT and SIGURG pcntl constants.');
} }
@@ -162,7 +162,7 @@ class SignalHandlerTest extends TestCase
public static function defaultPreviousProvider() public static function defaultPreviousProvider()
{ {
if (!defined('SIGCONT') || !defined('SIGINT') || !defined('SIGURG')) { if (!\defined('SIGCONT') || !\defined('SIGINT') || !\defined('SIGURG')) {
return []; return [];
} }