1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-18 23:26:20 +02:00
This commit is contained in:
Jordi Boggiano
2022-04-19 22:10:02 +02:00
parent e4bb5c5cf3
commit 2695fa86cd
85 changed files with 350 additions and 398 deletions

View File

@@ -21,9 +21,10 @@ $config = new PhpCsFixer\Config();
return $config->setRules(array(
'@PSR2' => true,
// some rules disabled as long as 1.x branch is maintained
'binary_operator_spaces' => array(
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'default' => null,
),
],
'blank_line_before_statement' => ['statements' => ['continue', 'declare', 'return', 'throw', 'try']],
'cast_spaces' => ['space' => 'single'],
'header_comment' => ['header' => $header],
@@ -35,6 +36,7 @@ return $config->setRules(array(
'no_extra_blank_lines' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true],
'no_trailing_comma_in_singleline_array' => true,
'no_unused_imports' => true,
'no_whitespace_in_blank_line' => true,
@@ -48,7 +50,6 @@ return $config->setRules(array(
'phpdoc_trim' => true,
//'phpdoc_types' => true,
'psr_autoloading' => ['dir' => 'src'],
//'array_syntax' => array('syntax' => 'short'),
'declare_strict_types' => true,
'single_blank_line_before_namespace' => true,
'standardize_not_equals' => true,

View File

@@ -61,7 +61,6 @@ class ErrorHandler
*
* By default it will handle errors, exceptions and fatal errors
*
* @param LoggerInterface $logger
* @param array<int, LogLevel::*>|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
* @param array<class-string, LogLevel::*>|false $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling
* @param LogLevel::*|null|false $fatalLevel a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling

View File

@@ -12,7 +12,6 @@
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger;
use Monolog\LogRecord;
/**

View File

@@ -56,8 +56,6 @@ class ElasticsearchFormatter extends NormalizerFormatter
/**
* Getter index
*
* @return string
*/
public function getIndex(): string
{
@@ -66,8 +64,6 @@ class ElasticsearchFormatter extends NormalizerFormatter
/**
* Getter type
*
* @return string
*/
public function getType(): string
{

View File

@@ -12,7 +12,6 @@
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger;
use Gelf\Message;
use Monolog\Utils;
use Monolog\LogRecord;

View File

@@ -12,7 +12,6 @@
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger;
use Monolog\Utils;
use Monolog\LogRecord;
@@ -71,7 +70,6 @@ class HtmlFormatter extends NormalizerFormatter
* Create a HTML h1 tag
*
* @param string $title Text to be in the h1
* @return string
*/
protected function addTitle(string $title, Level $level): string
{

View File

@@ -105,7 +105,6 @@ class JsonFormatter extends NormalizerFormatter
}
/**
* @return self
*/
public function includeStacktraces(bool $include = true): self
{
@@ -142,10 +141,6 @@ class JsonFormatter extends NormalizerFormatter
/**
* Normalizes given $data.
*
* @param mixed $data
*
* @return mixed
*/
protected function normalize(mixed $data, int $depth = 0): mixed
{

View File

@@ -39,7 +39,6 @@ class LineFormatter extends NormalizerFormatter
* @param string|null $format The format of the message
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
* @param bool $ignoreEmptyContextAndExtra
*/
public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false)
{
@@ -119,6 +118,7 @@ class LineFormatter extends NormalizerFormatter
$output = preg_replace('/%(?:extra|context)\..+?%/', '', $output);
if (null === $output) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode));
}
}
@@ -177,7 +177,7 @@ class LineFormatter extends NormalizerFormatter
{
if ($this->allowInlineLineBreaks) {
if (0 === strpos($str, '{')) {
return str_replace(array('\r', '\n'), array("\r", "\n"), $str);
return str_replace(['\r', '\n'], ["\r", "\n"], $str);
}
return $str;

View File

@@ -149,7 +149,6 @@ class NormalizerFormatter implements FormatterInterface
}
/**
* @param mixed $data
* @return null|scalar|array<mixed[]|scalar|null>
*/
protected function normalize(mixed $data, int $depth = 0): mixed

View File

@@ -12,7 +12,6 @@
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Logger;
use Monolog\LogRecord;
/**
@@ -56,8 +55,6 @@ class WildfireFormatter extends NormalizerFormatter
/**
* {@inheritDoc}
*
* @return string
*/
public function format(LogRecord $record): string
{

View File

@@ -53,7 +53,6 @@ abstract class AbstractHandler extends Handler implements ResettableInterface
* Sets minimum logging level at which this handler will be triggered.
*
* @param Level|LevelName|LogLevel::* $level Level or level name
* @return self
*
* @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $level
*/
@@ -77,7 +76,6 @@ abstract class AbstractHandler extends Handler implements ResettableInterface
*
* @param bool $bubble true means that this handler allows bubbling.
* false means that bubbling is not permitted.
* @return self
*/
public function setBubble(bool $bubble): self
{

View File

@@ -19,9 +19,6 @@ use Monolog\LogRecord;
use function count;
use function headers_list;
use function stripos;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* Handler sending logs to browser's javascript console with no browser extension required
@@ -235,6 +232,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
if (null === $style) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to run preg_replace_callback: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode));
}

View File

@@ -35,8 +35,6 @@ final class Util
* Executes a CURL request with optional retries and exception on failure
*
* @param CurlHandle $ch curl handler
* @param int $retries
* @param bool $closeAfterDone
* @return bool|string @see curl_exec
*/
public static function execute($ch, int $retries = 5, bool $closeAfterDone = true)

View File

@@ -83,6 +83,7 @@ class ErrorLogHandler extends AbstractProcessingHandler
$lines = preg_split('{[\r\n]+}', (string) $record->formatted);
if ($lines === false) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to preg_split formatted string: ' . $pcreErrorCode . ' / '. Utils::pcreLastErrorMessage($pcreErrorCode));
}
foreach ($lines as $line) {

View File

@@ -81,7 +81,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
*/
public function getAcceptedLevels(): array
{
return array_map(fn(int $level) => Level::from($level), array_keys($this->acceptedLevels));
return array_map(fn (int $level) => Level::from($level), array_keys($this->acceptedLevels));
}
/**

View File

@@ -23,15 +23,12 @@ interface FormattableHandlerInterface
/**
* Sets the formatter.
*
* @param FormatterInterface $formatter
* @return HandlerInterface self
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface;
/**
* Gets the formatter.
*
* @return FormatterInterface
*/
public function getFormatter(): FormatterInterface;
}

View File

@@ -30,8 +30,6 @@ interface HandlerInterface
* for a given record.
*
* @param LogRecord $record Partial log record having only a level initialized
*
* @return bool
*/
public function isHandling(LogRecord $record): bool;

View File

@@ -63,7 +63,6 @@ class LogglyHandler extends AbstractProcessingHandler
/**
* Loads and returns the shared curl handler for the given endpoint.
*
* @param string $endpoint
*
* @return CurlHandle
*/
@@ -79,7 +78,6 @@ class LogglyHandler extends AbstractProcessingHandler
/**
* Starts a fresh curl session for the given endpoint and returns its handler.
*
* @param string $endpoint
*
* @return CurlHandle
*/

View File

@@ -83,8 +83,6 @@ abstract class MailHandler extends AbstractProcessingHandler
/**
* Gets the default formatter.
*
* @return FormatterInterface
*/
protected function getDefaultFormatter(): FormatterInterface
{

View File

@@ -52,10 +52,6 @@ class NewRelicHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*
* @param string|null $appName
* @param bool $explodeArrays
* @param string|null $transactionName
*/
public function __construct(
$level = Level::Error,
@@ -123,8 +119,6 @@ class NewRelicHandler extends AbstractProcessingHandler
/**
* Checks whether the NewRelic extension is enabled in the system.
*
* @return bool
*/
protected function isNewRelicEnabled(): bool
{
@@ -178,7 +172,6 @@ class NewRelicHandler extends AbstractProcessingHandler
}
/**
* @param string $key
* @param mixed $value
*/
protected function setNewRelicParameter(string $key, $value): void

View File

@@ -51,7 +51,6 @@ class OverflowHandler extends AbstractHandler implements FormattableHandlerInter
private $buffer = [];
/**
* @param HandlerInterface $handler
* @param array<int, int> $thresholdMap Dictionary of log level value => threshold
*/
public function __construct(

View File

@@ -70,8 +70,6 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
/**
* Sets the formatter.
*
* @param FormatterInterface $formatter
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
@@ -82,8 +80,6 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
/**
* Gets the formatter.
*
* @return FormatterInterface
*/
public function getFormatter(): FormatterInterface
{

View File

@@ -86,7 +86,7 @@ class RollbarHandler extends AbstractProcessingHandler
{
if (!$this->initialized) {
// __destructor() doesn't get called on Fatal errors
register_shutdown_function(array($this, 'close'));
register_shutdown_function([$this, 'close']);
$this->initialized = true;
}

View File

@@ -45,7 +45,6 @@ class RotatingFileHandler extends StreamHandler
protected $dateFormat;
/**
* @param string $filename
* @param int $maxFiles The maximal amount of files to keep (0 means unlimited)
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param bool $useLocking Try to lock log file before doing any writes

View File

@@ -97,7 +97,7 @@ class SlackRecord
?string $userIcon = null,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
array $excludeFields = array(),
array $excludeFields = [],
FormatterInterface $formatter = null
) {
$this
@@ -123,7 +123,7 @@ class SlackRecord
*/
public function getSlackData(LogRecord $record): array
{
$dataArray = array();
$dataArray = [];
if ($this->username) {
$dataArray['username'] = $this->username;
@@ -142,16 +142,16 @@ class SlackRecord
$recordData = $this->removeExcludedFields($record);
if ($this->useAttachment) {
$attachment = array(
$attachment = [
'fallback' => $message,
'text' => $message,
'color' => $this->getAttachmentColor($record->level),
'fields' => array(),
'mrkdwn_in' => array('fields'),
'fields' => [],
'mrkdwn_in' => ['fields'],
'ts' => $recordData['datetime']->getTimestamp(),
'footer' => $this->username,
'footer_icon' => $this->userIcon,
);
];
if ($this->useShortAttachment) {
$attachment['title'] = $recordData['level_name'];
@@ -161,7 +161,7 @@ class SlackRecord
}
if ($this->includeContextAndExtra) {
foreach (array('extra', 'context') as $key) {
foreach (['extra', 'context'] as $key) {
if (empty($recordData[$key])) {
continue;
}
@@ -181,7 +181,7 @@ class SlackRecord
}
}
$dataArray['attachments'] = array($attachment);
$dataArray['attachments'] = [$attachment];
} else {
$dataArray['text'] = $message;
}
@@ -323,11 +323,11 @@ class SlackRecord
? sprintf('```%s```', substr($this->stringify($value), 0, 1990))
: $value;
return array(
return [
'title' => ucfirst($title),
'value' => $value,
'short' => false,
);
];
}
/**
@@ -342,7 +342,7 @@ class SlackRecord
/** @var array<mixed> $normalized */
$normalized = $this->normalizerFormatter->normalizeValue($data);
$fields = array();
$fields = [];
foreach ($normalized as $key => $value) {
$fields[] = $this->generateAttachmentField((string) $key, $value);
}

View File

@@ -58,7 +58,7 @@ class SlackHandler extends SocketHandler
bool $bubble = true,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
array $excludeFields = array(),
array $excludeFields = [],
bool $persistent = false,
float $timeout = 0.0,
float $writingTimeout = 10.0,

View File

@@ -57,7 +57,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
bool $includeContextAndExtra = false,
$level = Level::Critical,
bool $bubble = true,
array $excludeFields = array()
array $excludeFields = []
) {
if (!extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler');
@@ -97,13 +97,13 @@ class SlackWebhookHandler extends AbstractProcessingHandler
$postString = Utils::jsonEncode($postData);
$ch = curl_init();
$options = array(
$options = [
CURLOPT_URL => $this->webhookUrl,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_HTTPHEADER => ['Content-type: application/json'],
CURLOPT_POSTFIELDS => $postString,
);
];
if (defined('CURLOPT_SAFE_UPLOAD')) {
$options[CURLOPT_SAFE_UPLOAD] = true;
}

View File

@@ -211,8 +211,6 @@ class SocketHandler extends AbstractProcessingHandler
/**
* Get current local writing timeout
*
* @return float
*/
public function getWritingTimeout(): float
{

View File

@@ -105,8 +105,6 @@ class StreamHandler extends AbstractProcessingHandler
/**
* Return the stream URL if it was configured with a URL and not an active resource
*
* @return string|null
*/
public function getUrl(): ?string
{
@@ -114,7 +112,6 @@ class StreamHandler extends AbstractProcessingHandler
}
/**
* @return int
*/
public function getStreamChunkSize(): int
{

View File

@@ -36,7 +36,6 @@ class SyslogHandler extends AbstractSyslogHandler
protected $logopts;
/**
* @param string $ident
* @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param int $logopts Option flags for the openlog() call, defaults to LOG_PID
*/

View File

@@ -30,11 +30,11 @@ class SyslogUdpHandler extends AbstractSyslogHandler
const RFC5424e = 2;
/** @var array<self::RFC*, string> */
private $dateFormats = array(
private $dateFormats = [
self::RFC3164 => 'M d H:i:s',
self::RFC5424 => \DateTime::RFC3339,
self::RFC5424e => \DateTime::RFC3339_EXTENDED,
);
];
/** @var UdpSocket */
protected $socket;
@@ -97,6 +97,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
$lines = preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY);
if (false === $lines) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode));
}

View File

@@ -112,8 +112,7 @@ class TelegramBotHandler extends AbstractProcessingHandler
bool $disableNotification = null,
bool $splitLongMessages = false,
bool $delayBetweenMessages = false
)
{
) {
if (!extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler');
}
@@ -157,7 +156,6 @@ class TelegramBotHandler extends AbstractProcessingHandler
/**
* True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages.
* False - truncates a message that is too long.
* @param bool $splitLongMessages
* @return $this
*/
public function splitLongMessages(bool $splitLongMessages = false): self
@@ -169,7 +167,6 @@ class TelegramBotHandler extends AbstractProcessingHandler
/**
* Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests).
* @param bool $delayBetweenMessages
* @return $this
*/
public function delayBetweenMessages(bool $delayBetweenMessages = false): self
@@ -199,7 +196,7 @@ class TelegramBotHandler extends AbstractProcessingHandler
}
if (!empty($messages)) {
$this->send((string)$this->getFormatter()->formatBatch($messages));
$this->send((string) $this->getFormatter()->formatBatch($messages));
}
}
@@ -213,7 +210,6 @@ class TelegramBotHandler extends AbstractProcessingHandler
/**
* Send request to @link https://api.telegram.org/bot on SendMessage action.
* @param string $message
*/
protected function send(string $message): void
{
@@ -256,7 +252,6 @@ class TelegramBotHandler extends AbstractProcessingHandler
/**
* Handle a message that is too long: truncates or splits into several
* @param string $message
* @return string[]
*/
private function handleMessageLength(string $message): array

View File

@@ -198,6 +198,7 @@ class TestHandler extends AbstractProcessingHandler
$callback = [$this, $genericMethod];
if (is_callable($callback)) {
$args[] = $level;
return call_user_func_array($callback, $args);
}
}

View File

@@ -15,7 +15,6 @@ trait WebRequestRecognizerTrait
{
/**
* Checks if PHP's serving a web request
* @return bool
*/
protected function isWebRequest(): bool
{

View File

@@ -48,7 +48,7 @@ class WhatFailureGroupHandler extends GroupHandler
public function handleBatch(array $records): void
{
if ($this->processors) {
$processed = array();
$processed = [];
foreach ($records as $record) {
$processed[] = $this->processRecord($record);
}

View File

@@ -55,7 +55,6 @@ class ZendMonitorHandler extends AbstractProcessingHandler
};
}
/**
* {@inheritDoc}
*/

View File

@@ -1,4 +1,13 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
@@ -97,7 +106,6 @@ enum Level: int
}
/**
* @return string
* @phpstan-return \Psr\Log\LogLevel::*
*/
public function toPsrLogLevel(): string

View File

@@ -1,4 +1,13 @@
<?php
<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;

View File

@@ -50,11 +50,13 @@ class LogRecord implements ArrayAccess
}
$this->extra = $value;
return;
}
if ($offset === 'formatted') {
$this->formatted = $value;
return;
}

View File

@@ -237,7 +237,6 @@ class Logger implements LoggerInterface, ResettableInterface
* Removes the processor on top of the stack and returns it.
*
* @throws \LogicException If empty processor stack
* @return callable
*/
public function popProcessor(): callable
{

View File

@@ -41,7 +41,6 @@ abstract class MemoryProcessor implements ProcessorInterface
/**
* Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
*
* @param int $bytes
* @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int
*/
protected function formatBytes(int $bytes)

View File

@@ -39,9 +39,6 @@ class SignalHandler
/**
* @param int|string|Level|LevelName $level Level or level name
* @param bool $callPrevious
* @param bool $restartSyscalls
* @param bool|null $async
* @return $this
*
* @phpstan-param value-of<Level::VALUES>|value-of<LevelName::VALUES>|Level|LevelName|LogLevel::* $level

View File

@@ -122,7 +122,7 @@ final class Utils
if (is_string($data)) {
self::detectAndCleanUtf8($data);
} elseif (is_array($data)) {
array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8'));
array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']);
} else {
self::throwEncodeError($code, $data);
}
@@ -206,6 +206,7 @@ final class Utils
);
if (!is_string($data)) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode));
}
$data = str_replace(
@@ -241,8 +242,10 @@ final class Utils
switch (strtolower($match['unit'] ?? '')) {
case 'g':
$val *= 1024;
// no break
case 'm':
$val *= 1024;
// no break
case 'k':
$val *= 1024;
}
@@ -254,6 +257,7 @@ final class Utils
{
$context = '';
$extra = '';
try {
if ($record->context) {
$context = "\nContext: " . json_encode($record->context, JSON_THROW_ON_ERROR);

View File

@@ -12,7 +12,6 @@
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Test\TestCase;
class ElasticaFormatterTest extends TestCase

View File

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

View File

@@ -205,9 +205,6 @@ class JsonFormatterTest extends TestCase
}
/**
* @param JsonFormatter $formatter
* @param \Throwable $exception
*
* @return string
*/
private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
@@ -265,7 +262,7 @@ class JsonFormatterTest extends TestCase
Level::Critical,
'bar',
channel: 'test',
context: array($largeArray),
context: [$largeArray],
));
$this->assertCount(1000, $res['context'][0]);
@@ -281,7 +278,7 @@ class JsonFormatterTest extends TestCase
Level::Critical,
'bar',
channel: 'test',
context: array($largeArray),
context: [$largeArray],
));
$this->assertCount(1001, $res['context'][0]);

View File

@@ -274,6 +274,5 @@ class MongoDBFormatterTest extends TestCase
$this->assertInstanceOf(ObjectId::class, $formattedRecord['context']['objectid']);
$this->assertInstanceOf(UTCDateTime::class, $formattedRecord['context']['nest']['timestamp']);
$this->assertInstanceOf(Regex::class, $formattedRecord['context']['nest']['regex']);
}
}

View File

@@ -338,7 +338,7 @@ class NormalizerFormatterTest extends TestCase
'message' => 'Foo',
'code' => 0,
]],
"..." => "Over 2 items (7 total), aborting normalization"
"..." => "Over 2 items (7 total), aborting normalization",
],
$message
);
@@ -372,9 +372,6 @@ class NormalizerFormatterTest extends TestCase
}
/**
* @param NormalizerFormatter $formatter
* @param \Throwable $exception
*
* @return string
*/
private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
@@ -393,7 +390,7 @@ class NormalizerFormatterTest extends TestCase
{
try {
$arg = new TestInfoLeak;
call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
} catch (\Exception $e) {
}

View File

@@ -95,7 +95,7 @@ class ScalarFormatterTest extends TestCase
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception),
]
],
]), $formatted['context']);
}
}

View File

@@ -54,12 +54,12 @@ class ChromePHPHandlerTest extends TestCase
public static function agentsProvider()
{
return array(
array('Monolog Test; Chrome/1.0'),
array('Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'),
array('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36'),
array('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome Safari/537.36'),
);
return [
['Monolog Test; Chrome/1.0'],
['Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'],
['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36'],
['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome Safari/537.36'],
];
}
public function testHeadersOverflow()

View File

@@ -70,7 +70,7 @@ class DynamoDbHandlerTest extends TestCase
$handler->setFormatter($formatter);
if ($this->isV3) {
$expFormatted = array('foo' => array('N' => 1), 'bar' => array('N' => 2));
$expFormatted = ['foo' => ['N' => 1], 'bar' => ['N' => 2]];
} else {
$expFormatted = $formatted;
}

View File

@@ -15,7 +15,6 @@ use Monolog\Formatter\ElasticaFormatter;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Test\TestCase;
use Monolog\Level;
use Monolog\LogRecord;
use Elastica\Client;
use Elastica\Request;
use Elastica\Response;

View File

@@ -178,8 +178,8 @@ class FilterHandlerTest extends TestCase
{
$test = new TestHandler();
$handler = new FilterHandler($test);
$handler->handleBatch(array());
$this->assertSame(array(), $test->getRecords());
$handler->handleBatch([]);
$this->assertSame([], $test->getRecords());
}
/**
@@ -202,6 +202,6 @@ class FilterHandlerTest extends TestCase
$this->assertFalse($test->hasInfoRecords());
$this->assertFalse($test->hasInfoRecords());
$this->assertSame(array(), $test->getRecords());
$this->assertSame([], $test->getRecords());
}
}

View File

@@ -55,10 +55,10 @@ class InsightOpsHandlerTest extends TestCase
private function createHandler()
{
$useSSL = extension_loaded('openssl');
$args = array('testToken', 'us', $useSSL, Level::Debug, true);
$args = ['testToken', 'us', $useSSL, Level::Debug, true];
$this->resource = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder(InsightOpsHandler::class)
->onlyMethods(array('fsockopen', 'streamSetTimeout', 'closeSocket'))
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->setConstructorArgs($args)
->getMock();

View File

@@ -24,7 +24,7 @@ class PsrHandlerTest extends TestCase
public function logLevelProvider()
{
return array_map(
fn(Level $level) => [$level->toLevelName(), $level],
fn (Level $level) => [$level->toLevelName(), $level],
Level::cases()
);
}

View File

@@ -59,14 +59,14 @@ class RollbarHandlerTest extends TestCase
private function setupRollbarLoggerMock()
{
$config = array(
$config = [
'access_token' => 'ad865e76e7fb496fab096ac07b1dbabb',
'environment' => 'test',
);
];
$this->rollbarLogger = $this->getMockBuilder(RollbarLogger::class)
->setConstructorArgs(array($config))
->onlyMethods(array('log'))
->setConstructorArgs([$config])
->onlyMethods(['log'])
->getMock();
$this->rollbarLogger

View File

@@ -218,16 +218,16 @@ class RotatingFileHandlerTest extends TestCase
public function rotationWhenSimilarFilesExistTests()
{
return array(
return [
'Rotation is triggered when the file of the current day is not present but similar exists'
=> array(RotatingFileHandler::FILE_PER_DAY),
=> [RotatingFileHandler::FILE_PER_DAY],
'Rotation is triggered when the file of the current month is not present but similar exists'
=> array(RotatingFileHandler::FILE_PER_MONTH),
=> [RotatingFileHandler::FILE_PER_MONTH],
'Rotation is triggered when the file of the current year is not present but similar exists'
=> array(RotatingFileHandler::FILE_PER_YEAR),
);
=> [RotatingFileHandler::FILE_PER_YEAR],
];
}
public function testReuseCurrentFile()

View File

@@ -22,16 +22,16 @@ class SlackRecordTest extends TestCase
{
public function dataGetAttachmentColor()
{
return array(
array(Level::Debug, SlackRecord::COLOR_DEFAULT),
array(Level::Info, SlackRecord::COLOR_GOOD),
array(Level::Notice, SlackRecord::COLOR_GOOD),
array(Level::Warning, SlackRecord::COLOR_WARNING),
array(Level::Error, SlackRecord::COLOR_DANGER),
array(Level::Critical, SlackRecord::COLOR_DANGER),
array(Level::Alert, SlackRecord::COLOR_DANGER),
array(Level::Emergency, SlackRecord::COLOR_DANGER),
);
return [
[Level::Debug, SlackRecord::COLOR_DEFAULT],
[Level::Info, SlackRecord::COLOR_GOOD],
[Level::Notice, SlackRecord::COLOR_GOOD],
[Level::Warning, SlackRecord::COLOR_WARNING],
[Level::Error, SlackRecord::COLOR_DANGER],
[Level::Critical, SlackRecord::COLOR_DANGER],
[Level::Alert, SlackRecord::COLOR_DANGER],
[Level::Emergency, SlackRecord::COLOR_DANGER],
];
}
/**
@@ -70,16 +70,16 @@ class SlackRecordTest extends TestCase
*/
public function dataStringify()
{
$multipleDimensions = array(array(1, 2));
$numericKeys = array('library' => 'monolog');
$singleDimension = array(1, 'Hello', 'Jordi');
$multipleDimensions = [[1, 2]];
$numericKeys = ['library' => 'monolog'];
$singleDimension = [1, 'Hello', 'Jordi'];
return array(
array(array(), '[]'),
array($multipleDimensions, json_encode($multipleDimensions, JSON_PRETTY_PRINT)),
array($numericKeys, json_encode($numericKeys, JSON_PRETTY_PRINT)),
array($singleDimension, json_encode($singleDimension)),
);
return [
[[], '[]'],
[$multipleDimensions, json_encode($multipleDimensions, JSON_PRETTY_PRINT)],
[$numericKeys, json_encode($numericKeys, JSON_PRETTY_PRINT)],
[$singleDimension, json_encode($singleDimension)],
];
}
/**
@@ -179,7 +179,7 @@ class SlackRecordTest extends TestCase
}));
$message = 'Test message';
$record = new SlackRecord(null, null, false, null, false, false, array(), $formatter);
$record = new SlackRecord(null, null, false, null, false, false, [], $formatter);
$data = $record->getSlackData($this->getRecord(Level::Warning, $message));
$this->assertArrayHasKey('text', $data);
@@ -232,21 +232,21 @@ class SlackRecordTest extends TestCase
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$record = new SlackRecord(null, null, true, null, true);
$data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1)));
$data = $record->getSlackData($this->getRecord($level, 'test', ['test' => 1]));
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
$this->assertArrayHasKey('fields', $attachment);
$this->assertSame($levelName, $attachment['title']);
$this->assertSame(array(), $attachment['fields']);
$this->assertSame([], $attachment['fields']);
}
public function testAddsShortAttachmentWithContextAndExtra()
{
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$context = array('test' => 1);
$extra = array('tags' => array('web'));
$context = ['test' => 1];
$extra = ['tags' => ['web']];
$record = new SlackRecord(null, null, true, null, true, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
@@ -258,18 +258,18 @@ class SlackRecordTest extends TestCase
$this->assertCount(2, $attachment['fields']);
$this->assertSame($levelName, $attachment['title']);
$this->assertSame(
array(
array(
[
[
'title' => 'Extra',
'value' => sprintf('```%s```', json_encode($extra, JSON_PRETTY_PRINT)),
'short' => false,
),
array(
],
[
'title' => 'Context',
'value' => sprintf('```%s```', json_encode($context, JSON_PRETTY_PRINT)),
'short' => false,
),
),
],
],
$attachment['fields']
);
}
@@ -279,7 +279,7 @@ class SlackRecordTest extends TestCase
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$record = new SlackRecord(null, null, true, null);
$data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1)));
$data = $record->getSlackData($this->getRecord($level, 'test', ['test' => 1]));
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
@@ -287,11 +287,11 @@ class SlackRecordTest extends TestCase
$this->assertCount(1, $attachment['fields']);
$this->assertSame('Message', $attachment['title']);
$this->assertSame(
array(array(
[[
'title' => 'Level',
'value' => $levelName,
'short' => false,
)),
]],
$attachment['fields']
);
}
@@ -300,30 +300,30 @@ class SlackRecordTest extends TestCase
{
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$context = array('test' => 1);
$extra = array('tags' => array('web'));
$context = ['test' => 1];
$extra = ['tags' => ['web']];
$record = new SlackRecord(null, null, true, null, false, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
$data = $record->getSlackData($loggerRecord);
$expectedFields = array(
array(
$expectedFields = [
[
'title' => 'Level',
'value' => $levelName,
'short' => false,
),
array(
],
[
'title' => 'Tags',
'value' => sprintf('```%s```', json_encode($extra['tags'])),
'short' => false,
),
array(
],
[
'title' => 'Test',
'value' => $context['test'],
'short' => false,
),
);
],
];
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
@@ -349,7 +349,7 @@ class SlackRecordTest extends TestCase
public function testContextHasException()
{
$record = $this->getRecord(Level::Critical, 'This is a critical message.', array('exception' => new \Exception()));
$record = $this->getRecord(Level::Critical, 'This is a critical message.', ['exception' => new \Exception()]);
$slackRecord = new SlackRecord(null, null, true, null, false, true);
$data = $slackRecord->getSlackData($record);
$this->assertIsString($data['attachments'][0]['fields'][1]['value']);
@@ -360,26 +360,26 @@ class SlackRecordTest extends TestCase
$record = $this->getRecord(
Level::Warning,
'test',
context: array('info' => array('library' => 'monolog', 'author' => 'Jordi')),
extra: array('tags' => array('web', 'cli')),
context: ['info' => ['library' => 'monolog', 'author' => 'Jordi']],
extra: ['tags' => ['web', 'cli']],
);
$slackRecord = new SlackRecord(null, null, true, null, false, true, array('context.info.library', 'extra.tags.1'));
$slackRecord = new SlackRecord(null, null, true, null, false, true, ['context.info.library', 'extra.tags.1']);
$data = $slackRecord->getSlackData($record);
$attachment = $data['attachments'][0];
$expected = array(
array(
$expected = [
[
'title' => 'Info',
'value' => sprintf('```%s```', json_encode(array('author' => 'Jordi'), JSON_PRETTY_PRINT)),
'value' => sprintf('```%s```', json_encode(['author' => 'Jordi'], JSON_PRETTY_PRINT)),
'short' => false,
),
array(
],
[
'title' => 'Tags',
'value' => sprintf('```%s```', json_encode(array('web'))),
'value' => sprintf('```%s```', json_encode(['web'])),
'short' => false,
),
);
],
];
foreach ($expected as $field) {
$this->assertNotFalse(array_search($field, $attachment['fields']));

View File

@@ -114,16 +114,16 @@ class SlackHandlerTest extends TestCase
public function provideLevelColors()
{
return array(
array(Level::Debug, urlencode(SlackRecord::COLOR_DEFAULT)),
array(Level::Info, SlackRecord::COLOR_GOOD),
array(Level::Notice, SlackRecord::COLOR_GOOD),
array(Level::Warning, SlackRecord::COLOR_WARNING),
array(Level::Error, SlackRecord::COLOR_DANGER),
array(Level::Critical, SlackRecord::COLOR_DANGER),
array(Level::Alert, SlackRecord::COLOR_DANGER),
array(Level::Emergency,SlackRecord::COLOR_DANGER),
);
return [
[Level::Debug, urlencode(SlackRecord::COLOR_DEFAULT)],
[Level::Info, SlackRecord::COLOR_GOOD],
[Level::Notice, SlackRecord::COLOR_GOOD],
[Level::Warning, SlackRecord::COLOR_WARNING],
[Level::Error, SlackRecord::COLOR_DANGER],
[Level::Critical, SlackRecord::COLOR_DANGER],
[Level::Alert, SlackRecord::COLOR_DANGER],
[Level::Emergency,SlackRecord::COLOR_DANGER],
];
}
private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false)

View File

@@ -36,27 +36,27 @@ class SlackWebhookHandlerTest extends TestCase
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array(
'attachments' => array(
array(
$this->assertEquals([
'attachments' => [
[
'fallback' => 'test',
'text' => 'test',
'color' => SlackRecord::COLOR_WARNING,
'fields' => array(
array(
'fields' => [
[
'title' => 'Level',
'value' => 'WARNING',
'short' => false,
),
),
],
],
'title' => 'Message',
'mrkdwn_in' => array('fields'),
'mrkdwn_in' => ['fields'],
'ts' => $record->datetime->getTimestamp(),
'footer' => null,
'footer_icon' => null,
),
),
), $slackRecord->getSlackData($record));
],
],
], $slackRecord->getSlackData($record));
}
/**
@@ -79,12 +79,12 @@ class SlackWebhookHandlerTest extends TestCase
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array(
$this->assertEquals([
'username' => 'test-username',
'text' => 'test',
'channel' => 'test-channel',
'icon_emoji' => ':ghost:',
), $slackRecord->getSlackData($this->getRecord()));
], $slackRecord->getSlackData($this->getRecord()));
}
/**
@@ -108,30 +108,30 @@ class SlackWebhookHandlerTest extends TestCase
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array(
$this->assertEquals([
'username' => 'test-username-with-attachment',
'channel' => 'test-channel-with-attachment',
'attachments' => array(
array(
'attachments' => [
[
'fallback' => 'test',
'text' => 'test',
'color' => SlackRecord::COLOR_WARNING,
'fields' => array(
array(
'fields' => [
[
'title' => 'Level',
'value' => LevelName::Warning->value,
'short' => false,
),
),
'mrkdwn_in' => array('fields'),
],
],
'mrkdwn_in' => ['fields'],
'ts' => $record['datetime']->getTimestamp(),
'footer' => 'test-username-with-attachment',
'footer_icon' => 'https://www.example.com/example.png',
'title' => 'Message',
),
),
],
],
'icon_url' => 'https://www.example.com/example.png',
), $slackRecord->getSlackData($record));
], $slackRecord->getSlackData($record));
}
/**

View File

@@ -128,7 +128,7 @@ class SocketHandlerTest extends TestCase
public function testExceptionIsThrownIfCannotSetChunkSize()
{
$this->setMockHandler(array('streamSetChunkSize'));
$this->setMockHandler(['streamSetChunkSize']);
$this->handler->setChunkSize(8192);
$this->handler->expects($this->once())
->method('streamSetChunkSize')

View File

@@ -11,7 +11,6 @@
namespace Monolog\Handler;
use Monolog\Handler\StreamHandler;
use Monolog\Test\TestCase;
use Monolog\Level;

View File

@@ -75,15 +75,15 @@ class SyslogUdpHandlerTest extends TestCase
$host = gethostname();
$handler = $this->getMockBuilder('\Monolog\Handler\SyslogUdpHandler')
->setConstructorArgs(array("127.0.0.1", 514, "authpriv", 'debug', true, "php", \Monolog\Handler\SyslogUdpHandler::RFC3164))
->setConstructorArgs(["127.0.0.1", 514, "authpriv", 'debug', true, "php", \Monolog\Handler\SyslogUdpHandler::RFC3164])
->onlyMethods([])
->getMock();
$handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());
$socket = $this->getMockBuilder('\Monolog\Handler\SyslogUdp\UdpSocket')
->setConstructorArgs(array('lol', 999))
->onlyMethods(array('write'))
->setConstructorArgs(['lol', 999])
->onlyMethods(['write'])
->getMock();
$socket->expects($this->atLeast(2))
->method('write')

View File

@@ -32,8 +32,6 @@ class TelegramBotHandlerTest extends TestCase
}
/**
* @param string $apiKey
* @param string $channel
*/
private function createHandler(
string $apiKey = 'testKey',

View File

@@ -93,7 +93,7 @@ class WhatFailureGroupHandlerTest extends TestCase
*/
public function testHandleBatchUsesProcessors()
{
$testHandlers = array(new TestHandler(), new TestHandler());
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
@@ -105,7 +105,7 @@ class WhatFailureGroupHandlerTest extends TestCase
return $record;
});
$handler->handleBatch(array($this->getRecord(Level::Debug), $this->getRecord(Level::Info)));
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());

View File

@@ -12,7 +12,6 @@
namespace Monolog\Handler;
use Monolog\Test\TestCase;
use Monolog\Level;
class ZendMonitorHandlerTest extends TestCase
{

View File

@@ -276,7 +276,7 @@ class LoggerTest extends TestCase
public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresent()
{
$logger = new Logger(__METHOD__);
$logger->pushProcessor(fn($record) => $record);
$logger->pushProcessor(fn ($record) => $record);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never())
@@ -348,7 +348,7 @@ class LoggerTest extends TestCase
;
$logger = new Logger(__METHOD__, ['last' => $handler3, 'second' => $handler2, 'first' => $handler1]);
$logger->pushProcessor(fn($record) => $record);
$logger->pushProcessor(fn ($record) => $record);
$logger->debug('test');
}
@@ -652,7 +652,7 @@ class LoggerTest extends TestCase
$testHandler = new Handler\TestHandler();
$testHandler->setSkipReset(true);
$bufferHandler = new Handler\BufferHandler($testHandler);
$groupHandler = new Handler\GroupHandler(array($bufferHandler));
$groupHandler = new Handler\GroupHandler([$bufferHandler]);
$fingersCrossedHandler = new Handler\FingersCrossedHandler($groupHandler);
$logger->pushHandler($fingersCrossedHandler);

View File

@@ -90,15 +90,15 @@ class WebProcessorTest extends TestCase
public function testProcessorAddsOnlyRequestedExtraFieldsIncludingOptionalFields()
{
$server = array(
$server = [
'REQUEST_URI' => 'A',
'UNIQUE_ID' => 'X',
);
];
$processor = new WebProcessor($server, array('url'));
$processor = new WebProcessor($server, ['url']);
$record = $processor($this->getRecord());
$this->assertSame(array('url' => 'A'), $record->extra);
$this->assertSame(['url' => 'A'], $record->extra);
}
public function testProcessorConfiguringOfExtraFields()

View File

@@ -19,7 +19,6 @@ use PHPUnit\Framework\TestCase;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Psr\Log\Test\LoggerInterfaceTest;
class PsrLogCompatTest extends TestCase
{
@@ -61,28 +60,28 @@ class PsrLogCompatTest extends TestCase
public function testLogsAtAllLevels($level, $message)
{
$logger = $this->getLogger();
$logger->{$level}($message, array('user' => 'Bob'));
$logger->log($level, $message, array('user' => 'Bob'));
$logger->{$level}($message, ['user' => 'Bob']);
$logger->log($level, $message, ['user' => 'Bob']);
$expected = array(
$expected = [
"$level message of level $level with context: Bob",
"$level message of level $level with context: Bob",
);
];
$this->assertEquals($expected, $this->getLogs());
}
public function provideLevelsAndMessages()
{
return array(
LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
);
return [
LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
];
}
public function testThrowsOnInvalidLevel()
@@ -96,9 +95,9 @@ class PsrLogCompatTest extends TestCase
public function testContextReplacement()
{
$logger = $this->getLogger();
$logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
$logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
$expected = array('info {Message {nothing} Bob Bar a}');
$expected = ['info {Message {nothing} Bob Bar a}'];
$this->assertEquals($expected, $this->getLogs());
}
@@ -111,7 +110,7 @@ class PsrLogCompatTest extends TestCase
$this->getLogger()->warning($dummy);
$expected = array("warning $string");
$expected = ["warning $string"];
$this->assertEquals($expected, $this->getLogs());
}
@@ -120,34 +119,34 @@ class PsrLogCompatTest extends TestCase
$closed = fopen('php://memory', 'r');
fclose($closed);
$context = array(
$context = [
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => array('with object' => $this->createStringable()),
'nested' => ['with object' => $this->createStringable()],
'object' => new \DateTime('now', new DateTimeZone('Europe/London')),
'resource' => fopen('php://memory', 'r'),
'closed' => $closed,
);
];
$this->getLogger()->warning('Crazy context data', $context);
$expected = array('warning Crazy context data');
$expected = ['warning Crazy context data'];
$this->assertEquals($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->getLogger();
$logger->warning('Random message', array('exception' => 'oops'));
$logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
$logger->warning('Random message', ['exception' => 'oops']);
$logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
$expected = array(
$expected = [
'warning Random message',
'critical Uncaught Exception!'
);
'critical Uncaught Exception!',
];
$this->assertEquals($expected, $this->getLogs());
}
@@ -160,7 +159,7 @@ class PsrLogCompatTest extends TestCase
protected function createStringable($string = '')
{
$mock = $this->getMockBuilder('Stringable')
->setMethods(array('__toString'))
->setMethods(['__toString'])
->getMock();
$mock->method('__toString')

View File

@@ -28,13 +28,13 @@ class SignalHandlerTest extends TestCase
protected function setUp(): void
{
$this->signalHandlers = array();
$this->signalHandlers = [];
if (extension_loaded('pcntl')) {
if (function_exists('pcntl_async_signals')) {
$this->asyncSignalHandling = pcntl_async_signals();
}
if (function_exists('pcntl_sigprocmask')) {
pcntl_sigprocmask(SIG_BLOCK, array(), $this->blockedSignals);
pcntl_sigprocmask(SIG_BLOCK, [], $this->blockedSignals);
}
}
}
@@ -67,10 +67,10 @@ class SignalHandlerTest extends TestCase
public function testHandleSignal()
{
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$signo = 2; // SIGINT.
$siginfo = array('signo' => $signo, 'errno' => 0, 'code' => 0);
$siginfo = ['signo' => $signo, 'errno' => 0, 'code' => 0];
$errHandler->handleSignal($signo, $siginfo);
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasCriticalRecords());
@@ -97,7 +97,7 @@ class SignalHandlerTest extends TestCase
$this->setSignalHandler(SIGCONT, SIG_IGN);
$this->setSignalHandler(SIGURG, SIG_IGN);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$pid = posix_getpid();
@@ -135,14 +135,14 @@ class SignalHandlerTest extends TestCase
if ($pid === 0) { // Child.
$streamHandler = new StreamHandler($path);
$streamHandler->setFormatter($this->getIdentityFormatter());
$logger = new Logger('test', array($streamHandler));
$logger = new Logger('test', [$streamHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler($signo, LogLevel::INFO, $callPrevious, false, false);
pcntl_sigprocmask(SIG_SETMASK, array(SIGCONT));
pcntl_sigprocmask(SIG_SETMASK, [SIGCONT]);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
// If $callPrevious is true, SIGINT should terminate by this line.
pcntl_sigprocmask(SIG_BLOCK, array(), $oldset);
pcntl_sigprocmask(SIG_BLOCK, [], $oldset);
file_put_contents($path, implode(' ', $oldset), FILE_APPEND);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
@@ -158,15 +158,15 @@ class SignalHandlerTest extends TestCase
public function defaultPreviousProvider()
{
if (!defined('SIGCONT') || !defined('SIGINT') || !defined('SIGURG')) {
return array();
return [];
}
return array(
array(SIGINT, false, 'Program received signal SIGINT'.SIGCONT.'Program received signal SIGINT'),
array(SIGINT, true, 'Program received signal SIGINT'),
array(SIGURG, false, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'),
array(SIGURG, true, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'),
);
return [
[SIGINT, false, 'Program received signal SIGINT'.SIGCONT.'Program received signal SIGINT'],
[SIGINT, true, 'Program received signal SIGINT'],
[SIGURG, false, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'],
[SIGURG, true, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'],
];
}
/**
@@ -178,7 +178,7 @@ class SignalHandlerTest extends TestCase
{
$this->setSignalHandler(SIGURG, SIG_IGN);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$previousCalled = 0;
pcntl_signal(SIGURG, function ($signo, array $siginfo = null) use (&$previousCalled) {
@@ -194,10 +194,10 @@ class SignalHandlerTest extends TestCase
public function callablePreviousProvider()
{
return array(
array(false),
array(true),
);
return [
[false],
[true],
];
}
/**
@@ -222,7 +222,7 @@ class SignalHandlerTest extends TestCase
}
$this->assertNotSame(-1, $pid);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, $restartSyscalls, false);
if ($restartSyscalls) {
@@ -246,12 +246,12 @@ class SignalHandlerTest extends TestCase
public function restartSyscallsProvider()
{
return array(
array(false),
array(true),
array(false),
array(true),
);
return [
[false],
[true],
[false],
[true],
];
}
/**
@@ -264,7 +264,7 @@ class SignalHandlerTest extends TestCase
$this->setSignalHandler(SIGURG, SIG_IGN);
pcntl_async_signals($initialAsync);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, false, $desiredAsync);
$this->assertTrue(posix_kill(posix_getpid(), SIGURG));
@@ -275,13 +275,13 @@ class SignalHandlerTest extends TestCase
public function asyncProvider()
{
return array(
array(false, false, 0, 1),
array(false, null, 0, 1),
array(false, true, 1, 1),
array(true, false, 0, 1),
array(true, null, 1, 1),
array(true, true, 1, 1),
);
return [
[false, false, 0, 1],
[false, null, 0, 1],
[false, true, 1, 1],
[true, false, 0, 1],
[true, null, 1, 1],
[true, true, 1, 1],
];
}
}

View File

@@ -27,8 +27,10 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
{
return [
['stdClass', new \stdClass()],
['class@anonymous', new class {}],
['stdClass@anonymous', new class extends \stdClass {}],
['class@anonymous', new class {
}],
['stdClass@anonymous', new class extends \stdClass {
}],
];
}
@@ -44,15 +46,15 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
public function providePathsToCanonicalize()
{
return array(
array('/foo/bar', '/foo/bar'),
array('file://'.getcwd().'/bla', 'file://bla'),
array(getcwd().'/bla', 'bla'),
array(getcwd().'/./bla', './bla'),
array('file:///foo/bar', 'file:///foo/bar'),
array('any://foo', 'any://foo'),
array('\\\\network\path', '\\\\network\path'),
);
return [
['/foo/bar', '/foo/bar'],
['file://'.getcwd().'/bla', 'file://bla'],
[getcwd().'/bla', 'bla'],
[getcwd().'/./bla', './bla'],
['file:///foo/bar', 'file:///foo/bar'],
['any://foo', 'any://foo'],
['\\\\network\path', '\\\\network\path'],
];
}
/**
@@ -119,6 +121,7 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
{
if (PHP_VERSION_ID >= 80000) {
$this->assertSame('No error', Utils::pcreLastErrorMessage($code));
return;
}