1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-24 18:16:10 +02:00
This commit is contained in:
Jordi Boggiano
2016-05-26 20:54:06 +01:00
parent 85e43a5e7b
commit f200e79879
115 changed files with 1138 additions and 1123 deletions

10
.php_cs
View File

@@ -9,7 +9,7 @@ For the full copyright and license information, please view the LICENSE
file that was distributed with this source code. file that was distributed with this source code.
EOF; EOF;
$finder = Symfony\CS\Finder::create() $finder = PhpCsFixer\Finder::create()
->files() ->files()
->name('*.php') ->name('*.php')
->exclude('Fixtures') ->exclude('Fixtures')
@@ -17,7 +17,7 @@ $finder = Symfony\CS\Finder::create()
->in(__DIR__.'/tests') ->in(__DIR__.'/tests')
; ;
return Symfony\CS\Config::create() return PhpCsFixer\Config::create()
->setUsingCache(true) ->setUsingCache(true)
//->setUsingLinter(false) //->setUsingLinter(false)
->setRiskyAllowed(true) ->setRiskyAllowed(true)
@@ -25,9 +25,9 @@ return Symfony\CS\Config::create()
'@PSR2' => true, '@PSR2' => true,
'binary_operator_spaces' => true, 'binary_operator_spaces' => true,
'blank_line_before_return' => true, 'blank_line_before_return' => true,
'cast_spaces' => true,
'header_comment' => array('header' => $header), 'header_comment' => array('header' => $header),
'include' => true, 'include' => true,
'long_array_syntax' => false,
'method_separation' => true, 'method_separation' => 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,
@@ -38,6 +38,7 @@ return Symfony\CS\Config::create()
'no_leading_namespace_whitespace' => true, 'no_leading_namespace_whitespace' => true,
'no_trailing_comma_in_singleline_array' => true, 'no_trailing_comma_in_singleline_array' => true,
'no_unused_imports' => true, 'no_unused_imports' => true,
'no_whitespace_in_blank_lines' => true,
'object_operator_without_whitespace' => true, 'object_operator_without_whitespace' => true,
'phpdoc_align' => true, 'phpdoc_align' => true,
'phpdoc_indent' => true, 'phpdoc_indent' => true,
@@ -48,12 +49,11 @@ return Symfony\CS\Config::create()
'phpdoc_trim' => true, 'phpdoc_trim' => true,
'phpdoc_type_to_var' => true, 'phpdoc_type_to_var' => true,
'psr0' => true, 'psr0' => true,
'short_array_syntax' => true,
'single_blank_line_before_namespace' => true, 'single_blank_line_before_namespace' => true,
'spaces_cast' => true,
'standardize_not_equals' => true, 'standardize_not_equals' => true,
'ternary_operator_spaces' => true, 'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true, 'trailing_comma_in_multiline_array' => true,
'whitespacy_lines' => true,
)) ))
->finder($finder) ->finder($finder)
; ;

View File

@@ -36,7 +36,7 @@ class ErrorHandler
private $hasFatalErrorHandler; private $hasFatalErrorHandler;
private $fatalLevel; private $fatalLevel;
private $reservedMemory; private $reservedMemory;
private static $fatalErrors = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR); private static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
public function __construct(LoggerInterface $logger) public function __construct(LoggerInterface $logger)
{ {
@@ -54,7 +54,7 @@ class ErrorHandler
* @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling * @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling
* @return ErrorHandler * @return ErrorHandler
*/ */
public static function register(LoggerInterface $logger, $errorLevelMap = array(), $exceptionLevelMap = array(), $fatalLevel = null) public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null)
{ {
$handler = new static($logger); $handler = new static($logger);
if ($errorLevelMap !== false) { if ($errorLevelMap !== false) {
@@ -70,18 +70,18 @@ class ErrorHandler
return $handler; return $handler;
} }
public function registerExceptionHandler($levelMap = array(), $callPrevious = true) public function registerExceptionHandler($levelMap = [], $callPrevious = true)
{ {
$prev = set_exception_handler(array($this, 'handleException')); $prev = set_exception_handler([$this, 'handleException']);
$this->uncaughtExceptionLevelMap = array_replace($this->defaultExceptionLevelMap(), $levelMap); $this->uncaughtExceptionLevelMap = array_replace($this->defaultExceptionLevelMap(), $levelMap);
if ($callPrevious && $prev) { if ($callPrevious && $prev) {
$this->previousExceptionHandler = $prev; $this->previousExceptionHandler = $prev;
} }
} }
public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1) public function registerErrorHandler(array $levelMap = [], $callPrevious = true, $errorTypes = -1)
{ {
$prev = set_error_handler(array($this, 'handleError'), $errorTypes); $prev = set_error_handler([$this, 'handleError'], $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap); $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) { if ($callPrevious) {
$this->previousErrorHandler = $prev ?: true; $this->previousErrorHandler = $prev ?: true;
@@ -90,7 +90,7 @@ class ErrorHandler
public function registerFatalHandler($level = null, $reservedMemorySize = 20) public function registerFatalHandler($level = null, $reservedMemorySize = 20)
{ {
register_shutdown_function(array($this, 'handleFatalError')); register_shutdown_function([$this, 'handleFatalError']);
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = $level; $this->fatalLevel = $level;
@@ -99,15 +99,15 @@ class ErrorHandler
protected function defaultExceptionLevelMap() protected function defaultExceptionLevelMap()
{ {
return array( return [
'ParseError' => LogLevel::CRITICAL, 'ParseError' => LogLevel::CRITICAL,
'Throwable' => LogLevel::ERROR, 'Throwable' => LogLevel::ERROR,
); ];
} }
protected function defaultErrorLevelMap() protected function defaultErrorLevelMap()
{ {
return array( return [
E_ERROR => LogLevel::CRITICAL, E_ERROR => LogLevel::CRITICAL,
E_WARNING => LogLevel::WARNING, E_WARNING => LogLevel::WARNING,
E_PARSE => LogLevel::ALERT, E_PARSE => LogLevel::ALERT,
@@ -123,7 +123,7 @@ class ErrorHandler
E_RECOVERABLE_ERROR => LogLevel::ERROR, E_RECOVERABLE_ERROR => LogLevel::ERROR,
E_DEPRECATED => LogLevel::NOTICE, E_DEPRECATED => LogLevel::NOTICE,
E_USER_DEPRECATED => LogLevel::NOTICE, E_USER_DEPRECATED => LogLevel::NOTICE,
); ];
} }
/** /**
@@ -142,7 +142,7 @@ class ErrorHandler
$this->logger->log( $this->logger->log(
$level, $level,
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()),
array('exception' => $e) ['exception' => $e]
); );
if ($this->previousExceptionHandler) { if ($this->previousExceptionHandler) {
@@ -155,7 +155,7 @@ class ErrorHandler
/** /**
* @private * @private
*/ */
public function handleError($code, $message, $file = '', $line = 0, $context = array()) public function handleError($code, $message, $file = '', $line = 0, $context = [])
{ {
if (!(error_reporting() & $code)) { if (!(error_reporting() & $code)) {
return; return;
@@ -164,7 +164,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::$fatalErrors, true)) { if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) {
$level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : LogLevel::CRITICAL; $level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : LogLevel::CRITICAL;
$this->logger->log($level, self::codeToString($code).': '.$message, array('code' => $code, 'message' => $message, 'file' => $file, 'line' => $line)); $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]);
} }
if ($this->previousErrorHandler === true) { if ($this->previousErrorHandler === true) {
@@ -186,7 +186,7 @@ class ErrorHandler
$this->logger->log( $this->logger->log(
$this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel, $this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel,
'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'], 'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
array('code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line']) ['code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line']]
); );
if ($this->logger instanceof Logger) { if ($this->logger instanceof Logger) {

View File

@@ -23,7 +23,7 @@ class ChromePHPFormatter implements FormatterInterface
/** /**
* Translates Monolog log levels to Wildfire levels. * Translates Monolog log levels to Wildfire levels.
*/ */
private $logLevels = array( private $logLevels = [
Logger::DEBUG => 'log', Logger::DEBUG => 'log',
Logger::INFO => 'info', Logger::INFO => 'info',
Logger::NOTICE => 'info', Logger::NOTICE => 'info',
@@ -32,7 +32,7 @@ class ChromePHPFormatter implements FormatterInterface
Logger::CRITICAL => 'error', Logger::CRITICAL => 'error',
Logger::ALERT => 'error', Logger::ALERT => 'error',
Logger::EMERGENCY => 'error', Logger::EMERGENCY => 'error',
); ];
/** /**
* {@inheritdoc} * {@inheritdoc}
@@ -46,7 +46,7 @@ class ChromePHPFormatter implements FormatterInterface
unset($record['extra']['file'], $record['extra']['line']); unset($record['extra']['file'], $record['extra']['line']);
} }
$message = array('message' => $record['message']); $message = ['message' => $record['message']];
if ($record['context']) { if ($record['context']) {
$message['context'] = $record['context']; $message['context'] = $record['context'];
} }
@@ -57,17 +57,17 @@ class ChromePHPFormatter implements FormatterInterface
$message = reset($message); $message = reset($message);
} }
return array( return [
$record['channel'], $record['channel'],
$message, $message,
$backtrace, $backtrace,
$this->logLevels[$record['level']], $this->logLevels[$record['level']],
); ];
} }
public function formatBatch(array $records) public function formatBatch(array $records)
{ {
$formatted = array(); $formatted = [];
foreach ($records as $record) { foreach ($records as $record) {
$formatted[] = $this->format($record); $formatted[] = $this->format($record);

View File

@@ -43,11 +43,11 @@ class FlowdockFormatter implements FormatterInterface
*/ */
public function format(array $record) public function format(array $record)
{ {
$tags = array( $tags = [
'#logs', '#logs',
'#' . strtolower($record['level_name']), '#' . strtolower($record['level_name']),
'#' . $record['channel'], '#' . $record['channel'],
); ];
foreach ($record['extra'] as $value) { foreach ($record['extra'] as $value) {
$tags[] = '#' . $value; $tags[] = '#' . $value;
@@ -60,14 +60,14 @@ class FlowdockFormatter implements FormatterInterface
$this->getShortMessage($record['message']) $this->getShortMessage($record['message'])
); );
$record['flowdock'] = array( $record['flowdock'] = [
'source' => $this->source, 'source' => $this->source,
'from_address' => $this->sourceEmail, 'from_address' => $this->sourceEmail,
'subject' => $subject, 'subject' => $subject,
'content' => $record['message'], 'content' => $record['message'],
'tags' => $tags, 'tags' => $tags,
'project' => $this->source, 'project' => $this->source,
); ];
return $record; return $record;
} }
@@ -77,7 +77,7 @@ class FlowdockFormatter implements FormatterInterface
*/ */
public function formatBatch(array $records) public function formatBatch(array $records)
{ {
$formatted = array(); $formatted = [];
foreach ($records as $record) { foreach ($records as $record) {
$formatted[] = $this->format($record); $formatted[] = $this->format($record);

View File

@@ -60,17 +60,17 @@ class FluentdFormatter implements FormatterInterface
$tag .= '.' . strtolower($record['level_name']); $tag .= '.' . strtolower($record['level_name']);
} }
$message = array( $message = [
'message' => $record['message'], 'message' => $record['message'],
'extra' => $record['extra'], 'extra' => $record['extra'],
); ];
if (!$this->levelTag) { if (!$this->levelTag) {
$message['level'] = $record['level']; $message['level'] = $record['level'];
$message['level_name'] = $record['level_name']; $message['level_name'] = $record['level_name'];
} }
return json_encode(array($tag, $record['datetime']->getTimestamp(), $message)); return json_encode([$tag, $record['datetime']->getTimestamp(), $message]);
} }
public function formatBatch(array $records) public function formatBatch(array $records)

View File

@@ -42,7 +42,7 @@ class GelfMessageFormatter extends NormalizerFormatter
/** /**
* Translates Monolog log levels to Graylog2 log priorities. * Translates Monolog log levels to Graylog2 log priorities.
*/ */
private $logLevels = array( private $logLevels = [
Logger::DEBUG => 7, Logger::DEBUG => 7,
Logger::INFO => 6, Logger::INFO => 6,
Logger::NOTICE => 5, Logger::NOTICE => 5,
@@ -51,7 +51,7 @@ class GelfMessageFormatter extends NormalizerFormatter
Logger::CRITICAL => 2, Logger::CRITICAL => 2,
Logger::ALERT => 1, Logger::ALERT => 1,
Logger::EMERGENCY => 0, Logger::EMERGENCY => 0,
); ];
public function __construct($systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_') public function __construct($systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_')
{ {

View File

@@ -24,7 +24,7 @@ class HtmlFormatter extends NormalizerFormatter
/** /**
* Translates Monolog log levels to html color priorities. * Translates Monolog log levels to html color priorities.
*/ */
protected $logLevels = array( protected $logLevels = [
Logger::DEBUG => '#cccccc', Logger::DEBUG => '#cccccc',
Logger::INFO => '#468847', Logger::INFO => '#468847',
Logger::NOTICE => '#3a87ad', Logger::NOTICE => '#3a87ad',
@@ -33,7 +33,7 @@ class HtmlFormatter extends NormalizerFormatter
Logger::CRITICAL => '#FF7708', Logger::CRITICAL => '#FF7708',
Logger::ALERT => '#C12A19', Logger::ALERT => '#C12A19',
Logger::EMERGENCY => '#000000', Logger::EMERGENCY => '#000000',
); ];
/** /**
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format * @param string $dateFormat The format of the timestamp: one supported by DateTime::format

View File

@@ -138,7 +138,7 @@ class JsonFormatter extends NormalizerFormatter
protected function normalize($data) protected function normalize($data)
{ {
if (is_array($data) || $data instanceof \Traversable) { if (is_array($data) || $data instanceof \Traversable) {
$normalized = array(); $normalized = [];
$count = 1; $count = 1;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
@@ -169,12 +169,12 @@ class JsonFormatter extends NormalizerFormatter
*/ */
protected function normalizeException(\Throwable $e) protected function normalizeException(\Throwable $e)
{ {
$data = array( $data = [
'class' => get_class($e), 'class' => get_class($e),
'message' => $e->getMessage(), 'message' => $e->getMessage(),
'code' => $e->getCode(), 'code' => $e->getCode(),
'file' => $e->getFile().':'.$e->getLine(), 'file' => $e->getFile().':'.$e->getLine(),
); ];
if ($this->includeStacktraces) { if ($this->includeStacktraces) {
$trace = $e->getTrace(); $trace = $e->getTrace();

View File

@@ -155,6 +155,6 @@ class LineFormatter extends NormalizerFormatter
return $str; return $str;
} }
return str_replace(array("\r\n", "\r", "\n"), ' ', $str); return str_replace(["\r\n", "\r", "\n"], ' ', $str);
} }
} }

View File

@@ -69,11 +69,11 @@ class LogstashFormatter extends NormalizerFormatter
if (empty($record['datetime'])) { if (empty($record['datetime'])) {
$record['datetime'] = gmdate('c'); $record['datetime'] = gmdate('c');
} }
$message = array( $message = [
'@timestamp' => $record['datetime'], '@timestamp' => $record['datetime'],
'@version' => 1, '@version' => 1,
'host' => $this->systemName, 'host' => $this->systemName,
); ];
if (isset($record['message'])) { if (isset($record['message'])) {
$message['message'] = $record['message']; $message['message'] = $record['message'];
} }

View File

@@ -84,12 +84,12 @@ class MongoDBFormatter implements FormatterInterface
protected function formatException(\Throwable $exception, $nestingLevel) protected function formatException(\Throwable $exception, $nestingLevel)
{ {
$formattedException = array( $formattedException = [
'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(),
); ];
if ($this->exceptionTraceAsString === true) { if ($this->exceptionTraceAsString === true) {
$formattedException['trace'] = $exception->getTraceAsString(); $formattedException['trace'] = $exception->getTraceAsString();

View File

@@ -72,7 +72,7 @@ class NormalizerFormatter implements FormatterInterface
} }
if (is_array($data) || $data instanceof \Traversable) { if (is_array($data) || $data instanceof \Traversable) {
$normalized = array(); $normalized = [];
$count = 1; $count = 1;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
@@ -90,6 +90,7 @@ class NormalizerFormatter implements FormatterInterface
if ($data instanceof DateTimeImmutable) { if ($data instanceof DateTimeImmutable) {
return (string) $data; return (string) $data;
} }
return $data->format($this->dateFormat ?: static::SIMPLE_DATE); return $data->format($this->dateFormat ?: static::SIMPLE_DATE);
} }
@@ -124,12 +125,12 @@ class NormalizerFormatter implements FormatterInterface
protected function normalizeException(Throwable $e) protected function normalizeException(Throwable $e)
{ {
$data = array( $data = [
'class' => get_class($e), 'class' => get_class($e),
'message' => $e->getMessage(), 'message' => $e->getMessage(),
'code' => $e->getCode(), 'code' => $e->getCode(),
'file' => $e->getFile().':'.$e->getLine(), 'file' => $e->getFile().':'.$e->getLine(),
); ];
$trace = $e->getTrace(); $trace = $e->getTrace();
foreach ($trace as $frame) { foreach ($trace as $frame) {
@@ -176,7 +177,7 @@ class NormalizerFormatter implements FormatterInterface
} }
/** /**
* @param mixed $data * @param mixed $data
* @return string|bool JSON encoded data or false on failure * @return string|bool JSON encoded data or false on failure
*/ */
private function jsonEncode($data) private function jsonEncode($data)
@@ -206,7 +207,7 @@ class NormalizerFormatter implements FormatterInterface
if (is_string($data)) { if (is_string($data)) {
$this->detectAndCleanUtf8($data); $this->detectAndCleanUtf8($data);
} elseif (is_array($data)) { } elseif (is_array($data)) {
array_walk_recursive($data, array($this, 'detectAndCleanUtf8')); array_walk_recursive($data, [$this, 'detectAndCleanUtf8']);
} else { } else {
$this->throwEncodeError($code, $data); $this->throwEncodeError($code, $data);
} }
@@ -274,8 +275,8 @@ class NormalizerFormatter implements FormatterInterface
$data $data
); );
$data = str_replace( $data = str_replace(
array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'), ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'), ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
$data $data
); );
} }

View File

@@ -27,7 +27,7 @@ class WildfireFormatter extends NormalizerFormatter
/** /**
* Translates Monolog log levels to Wildfire levels. * Translates Monolog log levels to Wildfire levels.
*/ */
private $logLevels = array( private $logLevels = [
Logger::DEBUG => 'LOG', Logger::DEBUG => 'LOG',
Logger::INFO => 'INFO', Logger::INFO => 'INFO',
Logger::NOTICE => 'INFO', Logger::NOTICE => 'INFO',
@@ -36,7 +36,7 @@ class WildfireFormatter extends NormalizerFormatter
Logger::CRITICAL => 'ERROR', Logger::CRITICAL => 'ERROR',
Logger::ALERT => 'ERROR', Logger::ALERT => 'ERROR',
Logger::EMERGENCY => 'ERROR', Logger::EMERGENCY => 'ERROR',
); ];
/** /**
* {@inheritdoc} * {@inheritdoc}
@@ -55,7 +55,7 @@ class WildfireFormatter extends NormalizerFormatter
} }
$record = $this->normalize($record); $record = $this->normalize($record);
$message = array('message' => $record['message']); $message = ['message' => $record['message']];
$handleError = false; $handleError = false;
if ($record['context']) { if ($record['context']) {
$message['context'] = $record['context']; $message['context'] = $record['context'];
@@ -79,15 +79,15 @@ class WildfireFormatter extends NormalizerFormatter
} }
// Create JSON object describing the appearance of the message in the console // Create JSON object describing the appearance of the message in the console
$json = $this->toJson(array( $json = $this->toJson([
array( [
'Type' => $type, 'Type' => $type,
'File' => $file, 'File' => $file,
'Line' => $line, 'Line' => $line,
'Label' => $label, 'Label' => $label,
), ],
$message, $message,
), $handleError); ], $handleError);
// 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(

View File

@@ -25,7 +25,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
/** /**
* Translates Monolog log levels to syslog log priorities. * Translates Monolog log levels to syslog log priorities.
*/ */
protected $logLevels = array( protected $logLevels = [
Logger::DEBUG => LOG_DEBUG, Logger::DEBUG => LOG_DEBUG,
Logger::INFO => LOG_INFO, Logger::INFO => LOG_INFO,
Logger::NOTICE => LOG_NOTICE, Logger::NOTICE => LOG_NOTICE,
@@ -34,12 +34,12 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
Logger::CRITICAL => LOG_CRIT, Logger::CRITICAL => LOG_CRIT,
Logger::ALERT => LOG_ALERT, Logger::ALERT => LOG_ALERT,
Logger::EMERGENCY => LOG_EMERG, Logger::EMERGENCY => LOG_EMERG,
); ];
/** /**
* List of valid log facility names. * List of valid log facility names.
*/ */
protected $facilities = array( protected $facilities = [
'auth' => LOG_AUTH, 'auth' => LOG_AUTH,
'authpriv' => LOG_AUTHPRIV, 'authpriv' => LOG_AUTHPRIV,
'cron' => LOG_CRON, 'cron' => LOG_CRON,
@@ -51,7 +51,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
'syslog' => LOG_SYSLOG, 'syslog' => LOG_SYSLOG,
'user' => LOG_USER, 'user' => LOG_USER,
'uucp' => LOG_UUCP, 'uucp' => LOG_UUCP,
); ];
/** /**
* @param mixed $facility * @param mixed $facility

View File

@@ -61,10 +61,10 @@ class AmqpHandler extends AbstractProcessingHandler
$data, $data,
$routingKey, $routingKey,
0, 0,
array( [
'delivery_mode' => 2, 'delivery_mode' => 2,
'content_type' => 'application/json', 'content_type' => 'application/json',
) ]
); );
} else { } else {
$this->exchange->basic_publish( $this->exchange->basic_publish(
@@ -125,10 +125,10 @@ class AmqpHandler extends AbstractProcessingHandler
{ {
return new AMQPMessage( return new AMQPMessage(
(string) $data, (string) $data,
array( [
'delivery_mode' => 2, 'delivery_mode' => 2,
'content_type' => 'application/json', 'content_type' => 'application/json',
) ]
); );
} }

View File

@@ -22,7 +22,7 @@ use Monolog\Formatter\FormatterInterface;
class BrowserConsoleHandler extends AbstractProcessingHandler class BrowserConsoleHandler extends AbstractProcessingHandler
{ {
protected static $initialized = false; protected static $initialized = false;
protected static $records = array(); protected static $records = [];
/** /**
* {@inheritDoc} * {@inheritDoc}
@@ -79,7 +79,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
*/ */
public static function reset() public static function reset()
{ {
self::$records = array(); self::$records = [];
} }
/** /**
@@ -88,7 +88,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
protected function registerShutdownFunction() protected function registerShutdownFunction()
{ {
if (PHP_SAPI !== 'cli') { if (PHP_SAPI !== 'cli') {
register_shutdown_function(array('Monolog\Handler\BrowserConsoleHandler', 'send')); register_shutdown_function(['Monolog\Handler\BrowserConsoleHandler', 'send']);
} }
} }
@@ -133,7 +133,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function generateScript() private static function generateScript()
{ {
$script = array(); $script = [];
foreach (self::$records as $record) { foreach (self::$records as $record) {
$context = self::dump('Context', $record['context']); $context = self::dump('Context', $record['context']);
$extra = self::dump('Extra', $record['extra']); $extra = self::dump('Extra', $record['extra']);
@@ -142,10 +142,10 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
$script[] = self::call_array('log', self::handleStyles($record['formatted'])); $script[] = self::call_array('log', self::handleStyles($record['formatted']));
} else { } else {
$script = array_merge($script, $script = array_merge($script,
array(self::call_array('groupCollapsed', self::handleStyles($record['formatted']))), [self::call_array('groupCollapsed', self::handleStyles($record['formatted']))],
$context, $context,
$extra, $extra,
array(self::call('groupEnd')) [self::call('groupEnd')]
); );
} }
} }
@@ -155,7 +155,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function handleStyles($formatted) private static function handleStyles($formatted)
{ {
$args = array(self::quote('font-weight: normal')); $args = [self::quote('font-weight: normal')];
$format = '%c' . $formatted; $format = '%c' . $formatted;
preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
@@ -174,8 +174,8 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function handleCustomStyles($style, $string) private static function handleCustomStyles($style, $string)
{ {
static $colors = array('blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey'); static $colors = ['blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey'];
static $labels = array(); static $labels = [];
return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) { return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) {
if (trim($m[1]) === 'autolabel') { if (trim($m[1]) === 'autolabel') {
@@ -194,7 +194,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function dump($title, array $dict) private static function dump($title, array $dict)
{ {
$script = array(); $script = [];
$dict = array_filter($dict); $dict = array_filter($dict);
if (empty($dict)) { if (empty($dict)) {
return $script; return $script;

View File

@@ -29,7 +29,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
protected $bufferSize = 0; protected $bufferSize = 0;
protected $bufferLimit; protected $bufferLimit;
protected $flushOnOverflow; protected $flushOnOverflow;
protected $buffer = array(); protected $buffer = [];
protected $initialized = false; protected $initialized = false;
/** /**
@@ -58,7 +58,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
if (!$this->initialized) { if (!$this->initialized) {
// __destructor() doesn't get called on Fatal errors // __destructor() doesn't get called on Fatal errors
register_shutdown_function(array($this, 'close')); register_shutdown_function([$this, 'close']);
$this->initialized = true; $this->initialized = true;
} }
@@ -112,6 +112,6 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
public function clear() public function clear()
{ {
$this->bufferSize = 0; $this->bufferSize = 0;
$this->buffer = array(); $this->buffer = [];
} }
} }

View File

@@ -50,11 +50,11 @@ class ChromePHPHandler extends AbstractProcessingHandler
*/ */
protected static $overflowed = false; protected static $overflowed = false;
protected static $json = array( protected static $json = [
'version' => self::VERSION, 'version' => self::VERSION,
'columns' => array('label', 'log', 'backtrace', 'type'), 'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => array(), 'rows' => [],
); ];
protected static $sendHeaders = true; protected static $sendHeaders = true;
@@ -75,7 +75,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
*/ */
public function handleBatch(array $records) public function handleBatch(array $records)
{ {
$messages = array(); $messages = [];
foreach ($records as $record) { foreach ($records as $record) {
if ($record['level'] < $this->level) { if ($record['level'] < $this->level) {
@@ -140,15 +140,15 @@ class ChromePHPHandler extends AbstractProcessingHandler
if (strlen($data) > 240 * 1024) { if (strlen($data) > 240 * 1024) {
self::$overflowed = true; self::$overflowed = true;
$record = array( $record = [
'message' => 'Incomplete logs, chrome header size limit reached', 'message' => 'Incomplete logs, chrome header size limit reached',
'context' => array(), 'context' => [],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'monolog', 'channel' => 'monolog',
'datetime' => new \DateTimeImmutable(), 'datetime' => new \DateTimeImmutable(),
'extra' => array(), 'extra' => [],
); ];
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 = @json_encode(self::$json); $json = @json_encode(self::$json);
$data = base64_encode(utf8_encode($json)); $data = base64_encode(utf8_encode($json));

View File

@@ -24,15 +24,15 @@ class CouchDBHandler extends AbstractProcessingHandler
{ {
private $options; private $options;
public function __construct(array $options = array(), $level = Logger::DEBUG, $bubble = true) public function __construct(array $options = [], $level = Logger::DEBUG, $bubble = true)
{ {
$this->options = array_merge(array( $this->options = array_merge([
'host' => 'localhost', 'host' => 'localhost',
'port' => 5984, 'port' => 5984,
'dbname' => 'logger', 'dbname' => 'logger',
'username' => null, 'username' => null,
'password' => null, 'password' => null,
), $options); ], $options);
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
} }
@@ -48,15 +48,15 @@ class CouchDBHandler extends AbstractProcessingHandler
} }
$url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname']; $url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname'];
$context = stream_context_create(array( $context = stream_context_create([
'http' => array( 'http' => [
'method' => 'POST', 'method' => 'POST',
'content' => $record['formatted'], 'content' => $record['formatted'],
'ignore_errors' => true, 'ignore_errors' => true,
'max_redirects' => 0, 'max_redirects' => 0,
'header' => 'Content-type: application/json', 'header' => 'Content-type: application/json',
), ],
)); ]);
if (false === @file_get_contents($url, null, $context)) { if (false === @file_get_contents($url, null, $context)) {
throw new \RuntimeException(sprintf('Could not connect to %s', $url)); throw new \RuntimeException(sprintf('Could not connect to %s', $url));

View File

@@ -26,7 +26,7 @@ class CubeHandler extends AbstractProcessingHandler
private $scheme; private $scheme;
private $host; private $host;
private $port; private $port;
private $acceptedSchemes = array('http', 'udp'); private $acceptedSchemes = ['http', 'udp'];
/** /**
* Create a Cube handler * Create a Cube handler
@@ -105,7 +105,7 @@ class CubeHandler extends AbstractProcessingHandler
{ {
$date = $record['datetime']; $date = $record['datetime'];
$data = array('time' => $date->format('Y-m-d\TH:i:s.uO')); $data = ['time' => $date->format('Y-m-d\TH:i:s.uO')];
unset($record['datetime']); unset($record['datetime']);
if (isset($record['context']['type'])) { if (isset($record['context']['type'])) {
@@ -141,10 +141,10 @@ class CubeHandler extends AbstractProcessingHandler
} }
curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']'); curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']');
curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, array( 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

@@ -13,7 +13,7 @@ namespace Monolog\Handler\Curl;
class Util class Util
{ {
private static $retriableErrorCodes = array( private static $retriableErrorCodes = [
CURLE_COULDNT_RESOLVE_HOST, CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT, CURLE_COULDNT_CONNECT,
CURLE_HTTP_NOT_FOUND, CURLE_HTTP_NOT_FOUND,
@@ -21,7 +21,7 @@ class Util
CURLE_OPERATION_TIMEOUTED, CURLE_OPERATION_TIMEOUTED,
CURLE_HTTP_POST_ERROR, CURLE_HTTP_POST_ERROR,
CURLE_SSL_CONNECT_ERROR, CURLE_SSL_CONNECT_ERROR,
); ];
/** /**
* Executes a CURL request with optional retries and exception on failure * Executes a CURL request with optional retries and exception on failure

View File

@@ -81,7 +81,6 @@ class DeduplicationHandler extends BufferHandler
foreach ($this->buffer as $record) { foreach ($this->buffer as $record) {
if ($record['level'] >= $this->deduplicationLevel) { if ($record['level'] >= $this->deduplicationLevel) {
$passthru = $passthru || !$this->isDuplicate($record); $passthru = $passthru || !$this->isDuplicate($record);
if ($passthru) { if ($passthru) {
$this->appendRecord($record); $this->appendRecord($record);
@@ -139,7 +138,7 @@ class DeduplicationHandler extends BufferHandler
$handle = fopen($this->deduplicationStore, 'rw+'); $handle = fopen($this->deduplicationStore, 'rw+');
flock($handle, LOCK_EX); flock($handle, LOCK_EX);
$validLogs = array(); $validLogs = [];
$timestampValidity = time() - $this->time; $timestampValidity = time() - $this->time;

View File

@@ -63,10 +63,10 @@ class DynamoDbHandler extends AbstractProcessingHandler
$filtered = $this->filterEmptyFields($record['formatted']); $filtered = $this->filterEmptyFields($record['formatted']);
$formatted = $this->client->formatAttributes($filtered); $formatted = $this->client->formatAttributes($filtered);
$this->client->putItem(array( $this->client->putItem([
'TableName' => $this->table, 'TableName' => $this->table,
'Item' => $formatted, 'Item' => $formatted,
)); ]);
} }
/** /**

View File

@@ -43,7 +43,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/** /**
* @var array Handler config options * @var array Handler config options
*/ */
protected $options = array(); protected $options = [];
/** /**
* @param Client $client Elastica Client object * @param Client $client Elastica Client object
@@ -51,16 +51,16 @@ class ElasticSearchHandler extends AbstractProcessingHandler
* @param int $level The minimum logging level at which this handler will be triggered * @param int $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(Client $client, array $options = array(), $level = Logger::DEBUG, $bubble = true) public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->client = $client; $this->client = $client;
$this->options = array_merge( $this->options = array_merge(
array( [
'index' => 'monolog', // Elastic index name 'index' => 'monolog', // Elastic index name
'type' => 'record', // Elastic document type 'type' => 'record', // Elastic document type
'ignore_error' => false, // Suppress Elastica exceptions 'ignore_error' => false, // Suppress Elastica exceptions
), ],
$options $options
); );
} }
@@ -70,7 +70,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
*/ */
protected function write(array $record) protected function write(array $record)
{ {
$this->bulkSend(array($record['formatted'])); $this->bulkSend([$record['formatted']]);
} }
/** /**

View File

@@ -52,10 +52,10 @@ class ErrorLogHandler extends AbstractProcessingHandler
*/ */
public static function getAvailableTypes() public static function getAvailableTypes()
{ {
return array( return [
self::OPERATING_SYSTEM, self::OPERATING_SYSTEM,
self::SAPI, self::SAPI,
); ];
} }
/** /**

View File

@@ -128,7 +128,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface
*/ */
public function handleBatch(array $records) public function handleBatch(array $records)
{ {
$filtered = array(); $filtered = [];
foreach ($records as $record) { foreach ($records as $record) {
if ($this->isHandling($record)) { if ($this->isHandling($record)) {
$filtered[] = $record; $filtered[] = $record;

View File

@@ -42,7 +42,7 @@ class ChannelLevelActivationStrategy implements ActivationStrategyInterface
* @param int $defaultActionLevel The default action level to be used if the record's category doesn't match any * @param int $defaultActionLevel The default action level to be used if the record's category doesn't match any
* @param array $channelToActionLevel An array that maps channel names to action levels. * @param array $channelToActionLevel An array that maps channel names to action levels.
*/ */
public function __construct($defaultActionLevel, $channelToActionLevel = array()) public function __construct($defaultActionLevel, $channelToActionLevel = [])
{ {
$this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel);
$this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel); $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel);

View File

@@ -35,7 +35,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
protected $activationStrategy; protected $activationStrategy;
protected $buffering = true; protected $buffering = true;
protected $bufferSize; protected $bufferSize;
protected $buffer = array(); protected $buffer = [];
protected $stopBuffering; protected $stopBuffering;
protected $passthruLevel; protected $passthruLevel;
@@ -98,7 +98,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
} }
} }
$this->handler->handleBatch($this->buffer); $this->handler->handleBatch($this->buffer);
$this->buffer = array(); $this->buffer = [];
} }
/** /**
@@ -137,7 +137,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
}); });
if (count($this->buffer) > 0) { if (count($this->buffer) > 0) {
$this->handler->handleBatch($this->buffer); $this->handler->handleBatch($this->buffer);
$this->buffer = array(); $this->buffer = [];
} }
} }
} }
@@ -157,7 +157,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
*/ */
public function clear() public function clear()
{ {
$this->buffer = array(); $this->buffer = [];
$this->reset(); $this->reset();
} }
} }

View File

@@ -65,7 +65,7 @@ class FirePHPHandler extends AbstractProcessingHandler
{ {
$header = sprintf('%s-%s', self::HEADER_PREFIX, join('-', $meta)); $header = sprintf('%s-%s', self::HEADER_PREFIX, join('-', $meta));
return array($header => $message); return [$header => $message];
} }
/** /**
@@ -80,7 +80,7 @@ class FirePHPHandler extends AbstractProcessingHandler
// Wildfire is extensible to support multiple protocols & plugins in a single request, // Wildfire is extensible to support multiple protocols & plugins in a single request,
// but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake. // but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake.
return $this->createHeader( return $this->createHeader(
array(1, 1, 1, self::$messageIndex++), [1, 1, 1, self::$messageIndex++],
$record['formatted'] $record['formatted']
); );
} }
@@ -104,9 +104,9 @@ class FirePHPHandler extends AbstractProcessingHandler
{ {
// Initial payload consists of required headers for Wildfire // Initial payload consists of required headers for Wildfire
return array_merge( return array_merge(
$this->createHeader(array('Protocol', 1), self::PROTOCOL_URI), $this->createHeader(['Protocol', 1], self::PROTOCOL_URI),
$this->createHeader(array(1, 'Structure', 1), self::STRUCTURE_URI), $this->createHeader([1, 'Structure', 1], self::STRUCTURE_URI),
$this->createHeader(array(1, 'Plugin', 1), self::PLUGIN_URI) $this->createHeader([1, 'Plugin', 1], self::PLUGIN_URI)
); );
} }

View File

@@ -118,9 +118,9 @@ class FleepHookHandler extends SocketHandler
*/ */
private function buildContent($record) private function buildContent($record)
{ {
$dataArray = array( $dataArray = [
'message' => $record['formatted'], 'message' => $record['formatted'],
); ];
return http_build_query($dataArray); return http_build_query($dataArray);
} }

View File

@@ -12,7 +12,6 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Gelf\PublisherInterface; use Gelf\PublisherInterface;
use InvalidArgumentException;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Formatter\GelfMessageFormatter; use Monolog\Formatter\GelfMessageFormatter;
use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\FormatterInterface;

View File

@@ -70,15 +70,15 @@ class HipChatHandler extends SocketHandler
private $host; private $host;
/** /**
* @param string $token HipChat API Token * @param string $token HipChat API Token
* @param string $room The room that should be alerted of the message (Id or Name) * @param string $room The room that should be alerted of the message (Id or Name)
* @param string $name Name used in the "from" field. * @param string $name Name used in the "from" field.
* @param bool $notify Trigger a notification in clients or not * @param bool $notify Trigger a notification in clients or not
* @param int $level The minimum logging level at which this handler will be triggered * @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useSSL Whether to connect via SSL. * @param bool $useSSL Whether to connect via SSL.
* @param string $format The format of the messages (default to text, can be set to html if you have html in the messages) * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
* @param string $host The HipChat server hostname. * @param string $host The HipChat server hostname.
*/ */
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com') public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com')
{ {
@@ -114,12 +114,12 @@ class HipChatHandler extends SocketHandler
*/ */
private function buildContent($record) private function buildContent($record)
{ {
$dataArray = array( $dataArray = [
'notify' => $this->notify ? 'true' : 'false', 'notify' => $this->notify ? 'true' : 'false',
'message' => $record['formatted'], 'message' => $record['formatted'],
'message_format' => $this->format, 'message_format' => $this->format,
'color' => $this->getAlertColor($record['level']), 'color' => $this->getAlertColor($record['level']),
); ];
if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) { if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) {
if (function_exists('mb_substr')) { if (function_exists('mb_substr')) {
@@ -228,9 +228,9 @@ class HipChatHandler extends SocketHandler
private function combineRecords($records) private function combineRecords($records)
{ {
$batchRecord = null; $batchRecord = null;
$batchRecords = array(); $batchRecords = [];
$messages = array(); $messages = [];
$formattedMessages = array(); $formattedMessages = [];
$level = 0; $level = 0;
$levelName = null; $levelName = null;
$datetime = null; $datetime = null;
@@ -252,12 +252,12 @@ class HipChatHandler extends SocketHandler
$formattedMessages[] = $this->getFormatter()->format($record); $formattedMessages[] = $this->getFormatter()->format($record);
$formattedMessageStr = implode('', $formattedMessages); $formattedMessageStr = implode('', $formattedMessages);
$batchRecord = array( $batchRecord = [
'message' => $messageStr, 'message' => $messageStr,
'formatted' => $formattedMessageStr, 'formatted' => $formattedMessageStr,
'context' => array(), 'context' => [],
'extra' => array(), 'extra' => [],
); ];
if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) { if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
// Pop the last message and implode the remaining messages // Pop the last message and implode the remaining messages
@@ -267,8 +267,8 @@ class HipChatHandler extends SocketHandler
$batchRecord['formatted'] = implode('', $formattedMessages); $batchRecord['formatted'] = implode('', $formattedMessages);
$batchRecords[] = $batchRecord; $batchRecords[] = $batchRecord;
$messages = array($lastMessage); $messages = [$lastMessage];
$formattedMessages = array($lastFormattedMessage); $formattedMessages = [$lastFormattedMessage];
$batchRecord = null; $batchRecord = null;
} }
@@ -282,11 +282,11 @@ class HipChatHandler extends SocketHandler
foreach ($batchRecords as &$batchRecord) { foreach ($batchRecords as &$batchRecord) {
$batchRecord = array_merge( $batchRecord = array_merge(
$batchRecord, $batchRecord,
array( [
'level' => $level, 'level' => $level,
'level_name' => $levelName, 'level_name' => $levelName,
'datetime' => $datetime, 'datetime' => $datetime,
) ]
); );
} }

View File

@@ -48,11 +48,11 @@ class IFTTTHandler extends AbstractProcessingHandler
*/ */
public function write(array $record) public function write(array $record)
{ {
$postData = array( $postData = [
"value1" => $record["channel"], "value1" => $record["channel"],
"value2" => $record["level_name"], "value2" => $record["level_name"],
"value3" => $record["message"], "value3" => $record["message"],
); ];
$postString = json_encode($postData); $postString = json_encode($postData);
$ch = curl_init(); $ch = curl_init();
@@ -60,9 +60,9 @@ class IFTTTHandler extends AbstractProcessingHandler
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json", "Content-Type: application/json",
)); ]);
Curl\Util::execute($ch); Curl\Util::execute($ch);
} }

View File

@@ -30,7 +30,7 @@ class LogglyHandler extends AbstractProcessingHandler
protected $token; protected $token;
protected $tag = array(); protected $tag = [];
public function __construct($token, $level = Logger::DEBUG, $bubble = true) public function __construct($token, $level = Logger::DEBUG, $bubble = true)
{ {
@@ -45,14 +45,14 @@ class LogglyHandler extends AbstractProcessingHandler
public function setTag($tag) public function setTag($tag)
{ {
$tag = !empty($tag) ? $tag : array(); $tag = !empty($tag) ? $tag : [];
$this->tag = is_array($tag) ? $tag : array($tag); $this->tag = is_array($tag) ? $tag : [$tag];
} }
public function addTag($tag) public function addTag($tag)
{ {
if (!empty($tag)) { if (!empty($tag)) {
$tag = is_array($tag) ? $tag : array($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));
} }
} }
@@ -79,7 +79,7 @@ class LogglyHandler extends AbstractProcessingHandler
{ {
$url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token); $url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token);
$headers = array('Content-Type: application/json'); $headers = ['Content-Type: application/json'];
if (!empty($this->tag)) { if (!empty($this->tag)) {
$headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag); $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag);

View File

@@ -23,7 +23,7 @@ abstract class MailHandler extends AbstractProcessingHandler
*/ */
public function handleBatch(array $records) public function handleBatch(array $records)
{ {
$messages = array(); $messages = [];
foreach ($records as $record) { foreach ($records as $record) {
if ($record['level'] < $this->level) { if ($record['level'] < $this->level) {
@@ -50,7 +50,7 @@ abstract class MailHandler extends AbstractProcessingHandler
*/ */
protected function write(array $record) protected function write(array $record)
{ {
$this->send((string) $record['formatted'], array($record)); $this->send((string) $record['formatted'], [$record]);
} }
protected function getHighestRecord(array $records) protected function getHighestRecord(array $records)

View File

@@ -57,11 +57,11 @@ class MandrillHandler extends MailHandler
curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json'); curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'key' => $this->apiKey, 'key' => $this->apiKey,
'raw_message' => (string) $message, 'raw_message' => (string) $message,
'async' => false, 'async' => false,
))); ]));
Curl\Util::execute($ch); Curl\Util::execute($ch);
} }

View File

@@ -38,13 +38,13 @@ class NativeMailerHandler extends MailHandler
* Optional headers for the message * Optional headers for the message
* @var array * @var array
*/ */
protected $headers = array(); protected $headers = [];
/** /**
* Optional parameters for the message * Optional parameters for the message
* @var array * @var array
*/ */
protected $parameters = array(); protected $parameters = [];
/** /**
* The wordwrap length for the message * The wordwrap length for the message
@@ -75,7 +75,7 @@ class NativeMailerHandler extends MailHandler
public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70) public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->to = is_array($to) ? $to : array($to); $this->to = (array) $to;
$this->subject = $subject; $this->subject = $subject;
$this->addHeader(sprintf('From: %s', $from)); $this->addHeader(sprintf('From: %s', $from));
$this->maxColumnWidth = $maxColumnWidth; $this->maxColumnWidth = $maxColumnWidth;

View File

@@ -40,10 +40,10 @@ use PhpConsole\Helper;
*/ */
class PHPConsoleHandler extends AbstractProcessingHandler class PHPConsoleHandler extends AbstractProcessingHandler
{ {
private $options = array( private $options = [
'enabled' => true, // bool Is PHP Console server enabled 'enabled' => true, // bool Is PHP Console server enabled
'classesPartialsTraceIgnore' => array('Monolog\\'), // array Hide calls of classes started with... 'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with...
'debugTagsKeysInContext' => array(0, 'tag'), // bool Is PHP Console server enabled 'debugTagsKeysInContext' => [0, 'tag'], // bool Is PHP Console server enabled
'useOwnErrorsHandler' => false, // bool Enable errors handling 'useOwnErrorsHandler' => false, // bool Enable errors handling
'useOwnExceptionsHandler' => false, // bool Enable exceptions handling 'useOwnExceptionsHandler' => false, // bool Enable exceptions handling
'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths 'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths
@@ -52,7 +52,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
'headersLimit' => null, // int|null Set headers size limit for your web-server 'headersLimit' => null, // int|null Set headers size limit for your web-server
'password' => null, // string|null Protect PHP Console connection by password 'password' => null, // string|null Protect PHP Console connection by password
'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed 'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed
'ipMasks' => array(), // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1') 'ipMasks' => [], // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1')
'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required) 'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required)
'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings 'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings
'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level 'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level
@@ -61,7 +61,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON 'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON
'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug 'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug
'dataStorage' => null, // PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ) 'dataStorage' => null, // PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ)
); ];
/** @var Connector */ /** @var Connector */
private $connector; private $connector;
@@ -73,7 +73,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
* @param bool $bubble * @param bool $bubble
* @throws Exception * @throws Exception
*/ */
public function __construct(array $options = array(), Connector $connector = null, $level = Logger::DEBUG, $bubble = true) public function __construct(array $options = [], Connector $connector = null, $level = Logger::DEBUG, $bubble = true)
{ {
if (!class_exists('PhpConsole\Connector')) { if (!class_exists('PhpConsole\Connector')) {
throw new Exception('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); throw new Exception('PHP Console library not found. See https://github.com/barbushin/php-console#installation');

View File

@@ -58,11 +58,11 @@ class ProcessHandler extends AbstractProcessingHandler
]; ];
/** /**
* @param int $command Command for the process to start. Absolute paths are recommended, * @param int $command Command for the process to start. Absolute paths are recommended,
* especially if you do not use the $cwd parameter. * especially if you do not use the $cwd parameter.
* @param bool|int $level The minimum logging level at which this handler will be triggered. * @param bool|int $level The minimum logging level at which this handler will be triggered.
* @param bool|true $bubble Whether the messages that are handled can bubble up the stack or not. * @param bool|true $bubble Whether the messages that are handled can bubble up the stack or not.
* @param string|null $cwd "Current working directory" (CWD) for the process to be executed in. * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function __construct($command, $level = Logger::DEBUG, $bubble = true, $cwd = null) public function __construct($command, $level = Logger::DEBUG, $bubble = true, $cwd = null)
@@ -83,7 +83,7 @@ class ProcessHandler extends AbstractProcessingHandler
/** /**
* Writes the record down to the log of the implementing handler * Writes the record down to the log of the implementing handler
* *
* @param array $record * @param array $record
* @throws \UnexpectedValueException * @throws \UnexpectedValueException
* @return void * @return void
*/ */

View File

@@ -37,7 +37,7 @@ class PushoverHandler extends SocketHandler
* @see https://pushover.net/api * @see https://pushover.net/api
* @var array * @var array
*/ */
private $parameterNames = array( private $parameterNames = [
'token' => true, 'token' => true,
'user' => true, 'user' => true,
'message' => true, 'message' => true,
@@ -51,18 +51,18 @@ class PushoverHandler extends SocketHandler
'retry' => true, 'retry' => true,
'expire' => true, 'expire' => true,
'callback' => true, 'callback' => true,
); ];
/** /**
* Sounds the api supports by default * Sounds the api supports by default
* @see https://pushover.net/api#sounds * @see https://pushover.net/api#sounds
* @var array * @var array
*/ */
private $sounds = array( private $sounds = [
'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming', 'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming',
'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb', 'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb',
'persistent', 'echo', 'updown', 'none', 'persistent', 'echo', 'updown', 'none',
); ];
/** /**
* @param string $token Pushover api token * @param string $token Pushover api token
@@ -110,13 +110,13 @@ class PushoverHandler extends SocketHandler
$timestamp = $record['datetime']->getTimestamp(); $timestamp = $record['datetime']->getTimestamp();
$dataArray = array( $dataArray = [
'token' => $this->token, 'token' => $this->token,
'user' => $this->user, 'user' => $this->user,
'message' => $message, 'message' => $message,
'title' => $this->title, 'title' => $this->title,
'timestamp' => $timestamp, 'timestamp' => $timestamp,
); ];
if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) { if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) {
$dataArray['priority'] = 2; $dataArray['priority'] = 2;

View File

@@ -27,7 +27,7 @@ class RavenHandler extends AbstractProcessingHandler
/** /**
* Translates Monolog log levels to Raven log levels. * Translates Monolog log levels to Raven log levels.
*/ */
private $logLevels = array( private $logLevels = [
Logger::DEBUG => Raven_Client::DEBUG, Logger::DEBUG => Raven_Client::DEBUG,
Logger::INFO => Raven_Client::INFO, Logger::INFO => Raven_Client::INFO,
Logger::NOTICE => Raven_Client::INFO, Logger::NOTICE => Raven_Client::INFO,
@@ -36,7 +36,7 @@ class RavenHandler extends AbstractProcessingHandler
Logger::CRITICAL => Raven_Client::FATAL, Logger::CRITICAL => Raven_Client::FATAL,
Logger::ALERT => Raven_Client::FATAL, Logger::ALERT => Raven_Client::FATAL,
Logger::EMERGENCY => Raven_Client::FATAL, Logger::EMERGENCY => Raven_Client::FATAL,
); ];
/** /**
* @var string should represent the current version of the calling * @var string should represent the current version of the calling
@@ -92,7 +92,7 @@ class RavenHandler extends AbstractProcessingHandler
}); });
// the other ones are added as a context item // the other ones are added as a context item
$logs = array(); $logs = [];
foreach ($records as $r) { foreach ($records as $r) {
$logs[] = $this->processRecord($r); $logs[] = $this->processRecord($r);
} }
@@ -134,9 +134,9 @@ class RavenHandler extends AbstractProcessingHandler
protected function write(array $record) protected function write(array $record)
{ {
$previousUserContext = false; $previousUserContext = false;
$options = array(); $options = [];
$options['level'] = $this->logLevels[$record['level']]; $options['level'] = $this->logLevels[$record['level']];
$options['tags'] = array(); $options['tags'] = [];
if (!empty($record['extra']['tags'])) { if (!empty($record['extra']['tags'])) {
$options['tags'] = array_merge($options['tags'], $record['extra']['tags']); $options['tags'] = array_merge($options['tags'], $record['extra']['tags']);
unset($record['extra']['tags']); unset($record['extra']['tags']);
@@ -156,7 +156,7 @@ class RavenHandler extends AbstractProcessingHandler
$options['logger'] = $record['channel']; $options['logger'] = $record['channel'];
} }
foreach ($this->getExtraParameters() as $key) { foreach ($this->getExtraParameters() as $key) {
foreach (array('extra', 'context') as $source) { foreach (['extra', 'context'] as $source) {
if (!empty($record[$source][$key])) { if (!empty($record[$source][$key])) {
$options[$key] = $record[$source][$key]; $options[$key] = $record[$source][$key];
unset($record[$source][$key]); unset($record[$source][$key]);
@@ -183,7 +183,7 @@ class RavenHandler extends AbstractProcessingHandler
$options['extra']['message'] = $record['formatted']; $options['extra']['message'] = $record['formatted'];
$this->ravenClient->captureException($record['context']['exception'], $options); $this->ravenClient->captureException($record['context']['exception'], $options);
} else { } else {
$this->ravenClient->captureMessage($record['formatted'], array(), $options); $this->ravenClient->captureMessage($record['formatted'], [], $options);
} }
if ($previousUserContext !== false) { if ($previousUserContext !== false) {
@@ -216,7 +216,7 @@ class RavenHandler extends AbstractProcessingHandler
*/ */
protected function getExtraParameters() protected function getExtraParameters()
{ {
return array('checksum', 'release'); return ['checksum', 'release'];
} }
/** /**

View File

@@ -61,7 +61,7 @@ class RollbarHandler extends AbstractProcessingHandler
$exception = $context['exception']; $exception = $context['exception'];
unset($context['exception']); unset($context['exception']);
$payload = array(); $payload = [];
if (isset($context['payload'])) { if (isset($context['payload'])) {
$payload = $context['payload']; $payload = $context['payload'];
unset($context['payload']); unset($context['payload']);
@@ -69,14 +69,14 @@ class RollbarHandler extends AbstractProcessingHandler
$this->rollbarNotifier->report_exception($exception, $context, $payload); $this->rollbarNotifier->report_exception($exception, $context, $payload);
} else { } else {
$extraData = array( $extraData = [
'level' => $record['level'], 'level' => $record['level'],
'channel' => $record['channel'], 'channel' => $record['channel'],
'datetime' => $record['datetime']->format('U'), 'datetime' => $record['datetime']->format('U'),
); ];
$context = $record['context']; $context = $record['context'];
$payload = array(); $payload = [];
if (isset($context['payload'])) { if (isset($context['payload'])) {
$payload = $context['payload']; $payload = $context['payload'];
unset($context['payload']); unset($context['payload']);

View File

@@ -69,7 +69,7 @@ class RotatingFileHandler extends StreamHandler
public function setFilenameFormat($filenameFormat, $dateFormat) public function setFilenameFormat($filenameFormat, $dateFormat)
{ {
if (!in_array($dateFormat, array(self::FILE_PER_DAY, self::FILE_PER_MONTH, self::FILE_PER_YEAR))) { if (!in_array($dateFormat, [self::FILE_PER_DAY, self::FILE_PER_MONTH, self::FILE_PER_YEAR])) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
'Invalid date format - format must be one of '. 'Invalid date format - format must be one of '.
'RotatingFileHandler::FILE_PER_DAY, RotatingFileHandler::FILE_PER_MONTH '. 'RotatingFileHandler::FILE_PER_DAY, RotatingFileHandler::FILE_PER_MONTH '.
@@ -147,8 +147,8 @@ class RotatingFileHandler extends StreamHandler
{ {
$fileInfo = pathinfo($this->filename); $fileInfo = pathinfo($this->filename);
$timedFilename = str_replace( $timedFilename = str_replace(
array('{filename}', '{date}'), ['{filename}', '{date}'],
array($fileInfo['filename'], date($this->dateFormat)), [$fileInfo['filename'], date($this->dateFormat)],
$fileInfo['dirname'] . '/' . $this->filenameFormat $fileInfo['dirname'] . '/' . $this->filenameFormat
); );
@@ -163,8 +163,8 @@ class RotatingFileHandler extends StreamHandler
{ {
$fileInfo = pathinfo($this->filename); $fileInfo = pathinfo($this->filename);
$glob = str_replace( $glob = str_replace(
array('{filename}', '{date}'), ['{filename}', '{date}'],
array($fileInfo['filename'], '*'), [$fileInfo['filename'], '*'],
$fileInfo['dirname'] . '/' . $this->filenameFormat $fileInfo['dirname'] . '/' . $this->filenameFormat
); );
if (!empty($fileInfo['extension'])) { if (!empty($fileInfo['extension'])) {

View File

@@ -51,13 +51,13 @@ class SendGridHandler extends MailHandler
protected $subject; protected $subject;
/** /**
* @param string $apiUser The SendGrid API User * @param string $apiUser The SendGrid API User
* @param string $apiKey The SendGrid API Key * @param string $apiKey The SendGrid API Key
* @param string $from The sender of the email * @param string $from The sender of the email
* @param string|array $to The recipients of the email * @param string|array $to The recipients of the email
* @param string $subject The subject of the mail * @param string $subject The subject of the mail
* @param int $level The minimum logging level at which this handler will be triggered * @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, int $level = Logger::ERROR, bool $bubble = true) public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, int $level = Logger::ERROR, bool $bubble = true)
{ {
@@ -74,7 +74,7 @@ class SendGridHandler extends MailHandler
*/ */
protected function send($content, array $records) protected function send($content, array $records)
{ {
$message = array(); $message = [];
$message['api_user'] = $this->apiUser; $message['api_user'] = $this->apiUser;
$message['api_key'] = $this->apiKey; $message['api_key'] = $this->apiKey;
$message['from'] = $this->from; $message['from'] = $this->from;

View File

@@ -136,20 +136,20 @@ class SlackHandler extends SocketHandler
*/ */
protected function prepareContentData($record) protected function prepareContentData($record)
{ {
$dataArray = array( $dataArray = [
'token' => $this->token, 'token' => $this->token,
'channel' => $this->channel, 'channel' => $this->channel,
'username' => $this->username, 'username' => $this->username,
'text' => '', 'text' => '',
'attachments' => array(), 'attachments' => [],
); ];
if ($this->useAttachment) { if ($this->useAttachment) {
$attachment = array( $attachment = [
'fallback' => $record['message'], 'fallback' => $record['message'],
'color' => $this->getAttachmentColor($record['level']), 'color' => $this->getAttachmentColor($record['level']),
'fields' => array(), 'fields' => [],
); ];
if ($this->useShortAttachment) { if ($this->useShortAttachment) {
$attachment['title'] = $record['level_name']; $attachment['title'] = $record['level_name'];
@@ -157,54 +157,54 @@ class SlackHandler extends SocketHandler
} else { } else {
$attachment['title'] = 'Message'; $attachment['title'] = 'Message';
$attachment['text'] = $record['message']; $attachment['text'] = $record['message'];
$attachment['fields'][] = array( $attachment['fields'][] = [
'title' => 'Level', 'title' => 'Level',
'value' => $record['level_name'], 'value' => $record['level_name'],
'short' => true, 'short' => true,
); ];
} }
if ($this->includeContextAndExtra) { if ($this->includeContextAndExtra) {
if (!empty($record['extra'])) { if (!empty($record['extra'])) {
if ($this->useShortAttachment) { if ($this->useShortAttachment) {
$attachment['fields'][] = array( $attachment['fields'][] = [
'title' => "Extra", 'title' => "Extra",
'value' => $this->stringify($record['extra']), 'value' => $this->stringify($record['extra']),
'short' => $this->useShortAttachment, 'short' => $this->useShortAttachment,
); ];
} else { } else {
// Add all extra fields as individual fields in attachment // Add all extra fields as individual fields in attachment
foreach ($record['extra'] as $var => $val) { foreach ($record['extra'] as $var => $val) {
$attachment['fields'][] = array( $attachment['fields'][] = [
'title' => $var, 'title' => $var,
'value' => $val, 'value' => $val,
'short' => $this->useShortAttachment, 'short' => $this->useShortAttachment,
); ];
} }
} }
} }
if (!empty($record['context'])) { if (!empty($record['context'])) {
if ($this->useShortAttachment) { if ($this->useShortAttachment) {
$attachment['fields'][] = array( $attachment['fields'][] = [
'title' => "Context", 'title' => "Context",
'value' => $this->stringify($record['context']), 'value' => $this->stringify($record['context']),
'short' => $this->useShortAttachment, 'short' => $this->useShortAttachment,
); ];
} else { } else {
// Add all context fields as individual fields in attachment // Add all context fields as individual fields in attachment
foreach ($record['context'] as $var => $val) { foreach ($record['context'] as $var => $val) {
$attachment['fields'][] = array( $attachment['fields'][] = [
'title' => $var, 'title' => $var,
'value' => $val, 'value' => $val,
'short' => $this->useShortAttachment, 'short' => $this->useShortAttachment,
); ];
} }
} }
} }
} }
$dataArray['attachments'] = json_encode(array($attachment)); $dataArray['attachments'] = json_encode([$attachment]);
} else { } else {
$dataArray['text'] = $record['message']; $dataArray['text'] = $record['message'];
} }

View File

@@ -86,7 +86,7 @@ class StreamHandler extends AbstractProcessingHandler
} }
$this->createDir(); $this->createDir();
$this->errorMessage = null; $this->errorMessage = null;
set_error_handler(array($this, 'customErrorHandler')); set_error_handler([$this, 'customErrorHandler']);
$this->stream = fopen($this->url, 'a'); $this->stream = fopen($this->url, 'a');
if ($this->filePermission !== null) { if ($this->filePermission !== null) {
@chmod($this->url, $this->filePermission); @chmod($this->url, $this->filePermission);
@@ -144,7 +144,7 @@ class StreamHandler extends AbstractProcessingHandler
$dir = $this->getDirFromStream($this->url); $dir = $this->getDirFromStream($this->url);
if (null !== $dir && !is_dir($dir)) { if (null !== $dir && !is_dir($dir)) {
$this->errorMessage = null; $this->errorMessage = null;
set_error_handler(array($this, 'customErrorHandler')); set_error_handler([$this, 'customErrorHandler']);
$status = mkdir($dir, 0777, true); $status = mkdir($dir, 0777, true);
restore_error_handler(); restore_error_handler();
if (false === $status) { if (false === $status) {

View File

@@ -65,8 +65,8 @@ namespace Monolog\Handler;
*/ */
class TestHandler extends AbstractProcessingHandler class TestHandler extends AbstractProcessingHandler
{ {
protected $records = array(); protected $records = [];
protected $recordsByLevel = array(); protected $recordsByLevel = [];
public function getRecords() public function getRecords()
{ {
@@ -75,8 +75,8 @@ class TestHandler extends AbstractProcessingHandler
public function clear() public function clear()
{ {
$this->records = array(); $this->records = [];
$this->recordsByLevel = array(); $this->recordsByLevel = [];
} }
protected function hasRecordRecords($level) protected function hasRecordRecords($level)
@@ -145,7 +145,7 @@ class TestHandler extends AbstractProcessingHandler
if (method_exists($this, $genericMethod)) { if (method_exists($this, $genericMethod)) {
$args[] = $level; $args[] = $level;
return call_user_func_array(array($this, $genericMethod), $args); return call_user_func_array([$this, $genericMethod], $args);
} }
} }

View File

@@ -26,7 +26,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
* *
* @var array * @var array
*/ */
protected $levelMap = array( protected $levelMap = [
Logger::DEBUG => 1, Logger::DEBUG => 1,
Logger::INFO => 2, Logger::INFO => 2,
Logger::NOTICE => 3, Logger::NOTICE => 3,
@@ -35,7 +35,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
Logger::CRITICAL => 6, Logger::CRITICAL => 6,
Logger::ALERT => 7, Logger::ALERT => 7,
Logger::EMERGENCY => 0, Logger::EMERGENCY => 0,
); ];
/** /**
* Construct * Construct

View File

@@ -152,7 +152,7 @@ class Logger implements LoggerInterface
* @param callable[] $processors Optional array of processors * @param callable[] $processors Optional array of processors
* @param DateTimeZone $timezone Optional timezone, if not provided date_default_timezone_get() will be used * @param DateTimeZone $timezone Optional timezone, if not provided date_default_timezone_get() will be used
*/ */
public function __construct(string $name, array $handlers = array(), array $processors = array(), DateTimeZone $timezone = null) public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone $timezone = null)
{ {
$this->name = $name; $this->name = $name;
$this->handlers = $handlers; $this->handlers = $handlers;
@@ -218,7 +218,7 @@ class Logger implements LoggerInterface
*/ */
public function setHandlers(array $handlers): self public function setHandlers(array $handlers): self
{ {
$this->handlers = array(); $this->handlers = [];
foreach (array_reverse($handlers) as $handler) { foreach (array_reverse($handlers) as $handler) {
$this->pushHandler($handler); $this->pushHandler($handler);
} }
@@ -295,7 +295,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function addRecord(int $level, string $message, array $context = array()): bool public function addRecord(int $level, string $message, array $context = []): bool
{ {
$levelName = static::getLevelName($level); $levelName = static::getLevelName($level);
@@ -303,7 +303,7 @@ class Logger implements LoggerInterface
$handlerKey = null; $handlerKey = null;
reset($this->handlers); reset($this->handlers);
while ($handler = current($this->handlers)) { while ($handler = current($this->handlers)) {
if ($handler->isHandling(array('level' => $level))) { if ($handler->isHandling(['level' => $level])) {
$handlerKey = key($this->handlers); $handlerKey = key($this->handlers);
break; break;
} }
@@ -317,15 +317,15 @@ class Logger implements LoggerInterface
$ts = $this->createDateTime(); $ts = $this->createDateTime();
$record = array( $record = [
'message' => $message, 'message' => $message,
'context' => $context, 'context' => $context,
'level' => $level, 'level' => $level,
'level_name' => $levelName, 'level_name' => $levelName,
'channel' => $this->name, 'channel' => $this->name,
'datetime' => $ts, 'datetime' => $ts,
'extra' => array(), 'extra' => [],
); ];
foreach ($this->processors as $processor) { foreach ($this->processors as $processor) {
$record = call_user_func($processor, $record); $record = call_user_func($processor, $record);
@@ -394,9 +394,9 @@ class Logger implements LoggerInterface
*/ */
public function isHandling(int $level): bool public function isHandling(int $level): bool
{ {
$record = array( $record = [
'level' => $level, 'level' => $level,
); ];
foreach ($this->handlers as $handler) { foreach ($this->handlers as $handler) {
if ($handler->isHandling($record)) { if ($handler->isHandling($record)) {
@@ -417,7 +417,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function log($level, $message, array $context = array()) public function log($level, $message, array $context = [])
{ {
$level = static::toMonologLevel($level); $level = static::toMonologLevel($level);
@@ -433,7 +433,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function debug($message, array $context = array()) public function debug($message, array $context = [])
{ {
return $this->addRecord(static::DEBUG, (string) $message, $context); return $this->addRecord(static::DEBUG, (string) $message, $context);
} }
@@ -447,7 +447,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function info($message, array $context = array()) public function info($message, array $context = [])
{ {
return $this->addRecord(static::INFO, (string) $message, $context); return $this->addRecord(static::INFO, (string) $message, $context);
} }
@@ -461,7 +461,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function notice($message, array $context = array()) public function notice($message, array $context = [])
{ {
return $this->addRecord(static::NOTICE, (string) $message, $context); return $this->addRecord(static::NOTICE, (string) $message, $context);
} }
@@ -475,7 +475,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function warning($message, array $context = array()) public function warning($message, array $context = [])
{ {
return $this->addRecord(static::WARNING, (string) $message, $context); return $this->addRecord(static::WARNING, (string) $message, $context);
} }
@@ -489,7 +489,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function error($message, array $context = array()) public function error($message, array $context = [])
{ {
return $this->addRecord(static::ERROR, (string) $message, $context); return $this->addRecord(static::ERROR, (string) $message, $context);
} }
@@ -503,7 +503,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function critical($message, array $context = array()) public function critical($message, array $context = [])
{ {
return $this->addRecord(static::CRITICAL, (string) $message, $context); return $this->addRecord(static::CRITICAL, (string) $message, $context);
} }
@@ -517,7 +517,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function alert($message, array $context = array()) public function alert($message, array $context = [])
{ {
return $this->addRecord(static::ALERT, (string) $message, $context); return $this->addRecord(static::ALERT, (string) $message, $context);
} }
@@ -531,7 +531,7 @@ class Logger implements LoggerInterface
* @param array $context The log context * @param array $context The log context
* @return Boolean Whether the record has been processed * @return Boolean Whether the record has been processed
*/ */
public function emergency($message, array $context = array()) public function emergency($message, array $context = [])
{ {
return $this->addRecord(static::EMERGENCY, (string) $message, $context); return $this->addRecord(static::EMERGENCY, (string) $message, $context);
} }

View File

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

View File

@@ -32,15 +32,15 @@ class IntrospectionProcessor
private $skipStackFramesCount; private $skipStackFramesCount;
private $skipFunctions = array( private $skipFunctions = [
'call_user_func', 'call_user_func',
'call_user_func_array', 'call_user_func_array',
); ];
public function __construct($level = Logger::DEBUG, array $skipClassesPartials = array(), $skipStackFramesCount = 0) public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], $skipStackFramesCount = 0)
{ {
$this->level = Logger::toMonologLevel($level); $this->level = Logger::toMonologLevel($level);
$this->skipClassesPartials = array_merge(array('Monolog\\'), $skipClassesPartials); $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials);
$this->skipStackFramesCount = $skipStackFramesCount; $this->skipStackFramesCount = $skipStackFramesCount;
} }
@@ -85,12 +85,12 @@ class IntrospectionProcessor
// we should have the call source now // we should have the call source now
$record['extra'] = array_merge( $record['extra'] = array_merge(
$record['extra'], $record['extra'],
array( [
'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null, 'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null,
'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null, 'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null,
'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null, 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null,
'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null, 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null,
) ]
); );
return $record; return $record;

View File

@@ -30,7 +30,7 @@ class PsrLogMessageProcessor
return $record; return $record;
} }
$replacements = array(); $replacements = [];
foreach ($record['context'] as $key => $val) { foreach ($record['context'] as $key => $val) {
if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) {
$replacements['{'.$key.'}'] = $val; $replacements['{'.$key.'}'] = $val;

View File

@@ -20,17 +20,17 @@ class TagProcessor
{ {
private $tags; private $tags;
public function __construct(array $tags = array()) public function __construct(array $tags = [])
{ {
$this->setTags($tags); $this->setTags($tags);
} }
public function addTags(array $tags = array()) public function addTags(array $tags = [])
{ {
$this->tags = array_merge($this->tags, $tags); $this->tags = array_merge($this->tags, $tags);
} }
public function setTags(array $tags = array()) public function setTags(array $tags = [])
{ {
$this->tags = $tags; $this->tags = $tags;
} }

View File

@@ -30,13 +30,13 @@ class WebProcessor
* *
* @var array * @var array
*/ */
protected $extraFields = array( protected $extraFields = [
'url' => 'REQUEST_URI', 'url' => 'REQUEST_URI',
'ip' => 'REMOTE_ADDR', 'ip' => 'REMOTE_ADDR',
'http_method' => 'REQUEST_METHOD', 'http_method' => 'REQUEST_METHOD',
'server' => 'SERVER_NAME', 'server' => 'SERVER_NAME',
'referrer' => 'HTTP_REFERER', 'referrer' => 'HTTP_REFERER',
); ];
/** /**
* @param array|\ArrayAccess $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data * @param array|\ArrayAccess $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data

View File

@@ -42,7 +42,7 @@ class Registry
* *
* @var Logger[] * @var Logger[]
*/ */
private static $loggers = array(); private static $loggers = [];
/** /**
* Adds new logging channel to the registry * Adds new logging channel to the registry
@@ -100,7 +100,7 @@ class Registry
*/ */
public static function clear() public static function clear()
{ {
self::$loggers = array(); self::$loggers = [];
} }
/** /**

View File

@@ -24,17 +24,17 @@ class TestCase extends \PHPUnit_Framework_TestCase
/** /**
* @return array Record * @return array Record
*/ */
protected function getRecord($level = Logger::WARNING, $message = 'test', $context = array()) protected function getRecord($level = Logger::WARNING, $message = 'test', $context = [])
{ {
return array( return [
'message' => $message, 'message' => $message,
'context' => $context, 'context' => $context,
'level' => $level, 'level' => $level,
'level_name' => Logger::getLevelName($level), 'level_name' => Logger::getLevelName($level),
'channel' => 'test', 'channel' => 'test',
'datetime' => new DateTimeImmutable(true), 'datetime' => new DateTimeImmutable(true),
'extra' => array(), 'extra' => [],
); ];
} }
/** /**
@@ -42,13 +42,13 @@ class TestCase extends \PHPUnit_Framework_TestCase
*/ */
protected function getMultipleRecords() protected function getMultipleRecords()
{ {
return array( return [
$this->getRecord(Logger::DEBUG, 'debug message 1'), $this->getRecord(Logger::DEBUG, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'), $this->getRecord(Logger::DEBUG, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'), $this->getRecord(Logger::INFO, 'information'),
$this->getRecord(Logger::WARNING, 'warning'), $this->getRecord(Logger::WARNING, 'warning'),
$this->getRecord(Logger::ERROR, 'error'), $this->getRecord(Logger::ERROR, 'error'),
); ];
} }
/** /**

View File

@@ -17,10 +17,10 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
{ {
public function testHandleError() public function testHandleError()
{ {
$logger = new Logger('test', array($handler = new TestHandler)); $logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new ErrorHandler($logger); $errHandler = new ErrorHandler($logger);
$errHandler->registerErrorHandler(array(E_USER_NOTICE => Logger::EMERGENCY), false); $errHandler->registerErrorHandler([E_USER_NOTICE => Logger::EMERGENCY], false);
trigger_error('Foo', E_USER_ERROR); trigger_error('Foo', E_USER_ERROR);
$this->assertCount(1, $handler->getRecords()); $this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasErrorRecords()); $this->assertTrue($handler->hasErrorRecords());
@@ -31,28 +31,35 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
public function testHandleException() public function testHandleException()
{ {
$logger = new Logger('test', array($handler = new TestHandler)); $logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new ErrorHandler($logger); $errHandler = new ErrorHandler($logger);
$errHandler->registerExceptionHandler(array('Monolog\CustomTestException' => Logger::ALERT, 'Throwable' => Logger::WARNING), false); $errHandler->registerExceptionHandler(['Monolog\CustomTestException' => Logger::ALERT, 'Throwable' => Logger::WARNING], false);
try { try {
throw new CustomCustomException(); throw new CustomCustomException();
$this->assertCount(1, $handler->getRecords()); $this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasAlertRecords()); $this->assertTrue($handler->hasAlertRecords());
} catch (\Throwable $e) {} } catch (\Throwable $e) {
}
try { try {
throw new CustomTestException(); throw new CustomTestException();
$this->assertCount(2, $handler->getRecords()); $this->assertCount(2, $handler->getRecords());
$this->assertTrue($handler->hasAlertRecords()); $this->assertTrue($handler->hasAlertRecords());
} catch (\Throwable $e) {} } catch (\Throwable $e) {
}
try { try {
throw new RuntimeException(); throw new RuntimeException();
$this->assertCount(3, $handler->getRecords()); $this->assertCount(3, $handler->getRecords());
$this->assertTrue($handler->hasWarningRecords()); $this->assertTrue($handler->hasWarningRecords());
} catch (\Throwable $e) {} } catch (\Throwable $e) {
}
} }
} }
class CustomTestException extends \Exception {} class CustomTestException extends \Exception
class CustomCustomException extends CustomTestException {} {
}
class CustomCustomException extends CustomTestException
{
}

View File

@@ -21,29 +21,29 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormat() public function testDefaultFormat()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('ip' => '127.0.0.1'), 'extra' => ['ip' => '127.0.0.1'],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
$this->assertEquals( $this->assertEquals(
array( [
'meh', 'meh',
array( [
'message' => 'log', 'message' => 'log',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'extra' => array('ip' => '127.0.0.1'), 'extra' => ['ip' => '127.0.0.1'],
), ],
'unknown', 'unknown',
'error', 'error',
), ],
$message $message
); );
} }
@@ -54,29 +54,29 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLine() public function testFormatWithFileAndLine()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = array( $record = [
'level' => Logger::CRITICAL, 'level' => Logger::CRITICAL,
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14), 'extra' => ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
$this->assertEquals( $this->assertEquals(
array( [
'meh', 'meh',
array( [
'message' => 'log', 'message' => 'log',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'extra' => array('ip' => '127.0.0.1'), 'extra' => ['ip' => '127.0.0.1'],
), ],
'test : 14', 'test : 14',
'error', 'error',
), ],
$message $message
); );
} }
@@ -87,25 +87,25 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithoutContext() public function testFormatWithoutContext()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$record = array( $record = [
'level' => Logger::DEBUG, 'level' => Logger::DEBUG,
'level_name' => 'DEBUG', 'level_name' => 'DEBUG',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
$this->assertEquals( $this->assertEquals(
array( [
'meh', 'meh',
'log', 'log',
'unknown', 'unknown',
'log', 'log',
), ],
$message $message
); );
} }
@@ -116,42 +116,42 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testBatchFormatThrowException() public function testBatchFormatThrowException()
{ {
$formatter = new ChromePHPFormatter(); $formatter = new ChromePHPFormatter();
$records = array( $records = [
array( [
'level' => Logger::INFO, 'level' => Logger::INFO,
'level_name' => 'INFO', 'level_name' => 'INFO',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
), ],
array( [
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'foo', 'channel' => 'foo',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log2', 'message' => 'log2',
), ],
); ];
$this->assertEquals( $this->assertEquals(
array( [
array( [
'meh', 'meh',
'log', 'log',
'unknown', 'unknown',
'info', 'info',
), ],
array( [
'foo', 'foo',
'log2', 'log2',
'unknown', 'unknown',
'warn', 'warn',
), ],
), ],
$formatter->formatBatch($records) $formatter->formatBatch($records)
); );
} }

View File

@@ -30,24 +30,24 @@ class ElasticaFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormat() public function testFormat()
{ {
// test log message // test log message
$msg = array( $msg = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
// expected values // expected values
$expected = $msg; $expected = $msg;
$expected['datetime'] = '1970-01-01T00:00:00.000000+00:00'; $expected['datetime'] = '1970-01-01T00:00:00.000000+00:00';
$expected['context'] = array( $expected['context'] = [
'class' => ['stdClass' => []], 'class' => ['stdClass' => []],
'foo' => 7, 'foo' => 7,
0 => 'bar', 0 => 'bar',
); ];
// format log message // format log message
$formatter = new ElasticaFormatter('my_index', 'doc_type'); $formatter = new ElasticaFormatter('my_index', 'doc_type');

View File

@@ -24,14 +24,14 @@ class FlowdockFormatterTest extends TestCase
$formatter = new FlowdockFormatter('test_source', 'source@test.com'); $formatter = new FlowdockFormatter('test_source', 'source@test.com');
$record = $this->getRecord(); $record = $this->getRecord();
$expected = array( $expected = [
'source' => 'test_source', 'source' => 'test_source',
'from_address' => 'source@test.com', 'from_address' => 'source@test.com',
'subject' => 'in test_source: WARNING - test', 'subject' => 'in test_source: WARNING - test',
'content' => 'test', 'content' => 'test',
'tags' => array('#logs', '#warning', '#test'), 'tags' => ['#logs', '#warning', '#test'],
'project' => 'test_source', 'project' => 'test_source',
); ];
$formatted = $formatter->format($record); $formatted = $formatter->format($record);
$this->assertEquals($expected, $formatted['flowdock']); $this->assertEquals($expected, $formatted['flowdock']);
@@ -43,10 +43,10 @@ class FlowdockFormatterTest extends TestCase
public function testFormatBatch() public function testFormatBatch()
{ {
$formatter = new FlowdockFormatter('test_source', 'source@test.com'); $formatter = new FlowdockFormatter('test_source', 'source@test.com');
$records = array( $records = [
$this->getRecord(Logger::WARNING), $this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::DEBUG),
); ];
$formatted = $formatter->formatBatch($records); $formatted = $formatter->formatBatch($records);
$this->assertArrayHasKey('flowdock', $formatted[0]); $this->assertArrayHasKey('flowdock', $formatted[0]);

View File

@@ -28,15 +28,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormatter() public function testDefaultFormatter()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -63,15 +63,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLine() public function testFormatWithFileAndLine()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('file' => 'test', 'line' => 14), 'extra' => ['file' => 'test', 'line' => 14],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -87,10 +87,10 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatInvalidFails() public function testFormatInvalidFails()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
); ];
$formatter->format($record); $formatter->format($record);
} }
@@ -101,15 +101,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithContext() public function testFormatWithContext()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('key' => 'pair'), 'extra' => ['key' => 'pair'],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -138,19 +138,19 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithContextContainingException() public function testFormatWithContextContainingException()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger', 'exception' => array( 'context' => ['from' => 'logger', 'exception' => [
'class' => '\Exception', 'class' => '\Exception',
'file' => '/some/file/in/dir.php:56', 'file' => '/some/file/in/dir.php:56',
'trace' => array('/some/file/1.php:23', '/some/file/2.php:3'), 'trace' => ['/some/file/1.php:23', '/some/file/2.php:3'],
)), ]],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -166,15 +166,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithExtra() public function testFormatWithExtra()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('key' => 'pair'), 'extra' => ['key' => 'pair'],
'message' => 'log', 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
@@ -200,15 +200,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithLargeData() public function testFormatWithLargeData()
{ {
$formatter = new GelfMessageFormatter(); $formatter = new GelfMessageFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('exception' => str_repeat(' ', 32767)), 'context' => ['exception' => str_repeat(' ', 32767)],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('key' => str_repeat(' ', 32767)), 'extra' => ['key' => str_repeat(' ', 32767)],
'message' => 'log' 'message' => 'log',
); ];
$message = $formatter->format($record); $message = $formatter->format($record);
$messageArray = $message->toArray(); $messageArray = $message->toArray();
@@ -216,7 +216,7 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
$length = 200; $length = 200;
foreach ($messageArray as $key => $value) { foreach ($messageArray as $key => $value) {
if (!in_array($key, array('level', 'timestamp'))) { if (!in_array($key, ['level', 'timestamp'])) {
$length += strlen($value); $length += strlen($value);
} }
} }

View File

@@ -52,10 +52,10 @@ class JsonFormatterTest extends TestCase
public function testFormatBatch() public function testFormatBatch()
{ {
$formatter = new JsonFormatter(); $formatter = new JsonFormatter();
$records = array( $records = [
$this->getRecord(Logger::WARNING), $this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::DEBUG),
); ];
$this->assertEquals(json_encode($records), $formatter->formatBatch($records)); $this->assertEquals(json_encode($records), $formatter->formatBatch($records));
} }
@@ -66,10 +66,10 @@ class JsonFormatterTest extends TestCase
public function testFormatBatchNewlines() public function testFormatBatchNewlines()
{ {
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES); $formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
$records = $expected = array( $records = $expected = [
$this->getRecord(Logger::WARNING), $this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::DEBUG),
); ];
array_walk($expected, function (&$value, $key) { array_walk($expected, function (&$value, $key) {
$value = json_encode($value); $value = json_encode($value);
}); });
@@ -80,14 +80,14 @@ class JsonFormatterTest extends TestCase
{ {
$formatter = new JsonFormatter(); $formatter = new JsonFormatter();
$exception = new \RuntimeException('Foo'); $exception = new \RuntimeException('Foo');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'core', 'channel' => 'core',
'context' => array('exception' => $exception), 'context' => ['exception' => $exception],
'datetime' => new \DateTimeImmutable(), 'datetime' => new \DateTimeImmutable(),
'extra' => array(), 'extra' => [],
'message' => 'foobar', 'message' => 'foobar',
)); ]);
if (version_compare(PHP_VERSION, '5.4.0', '>=')) { if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
$path = substr(json_encode($exception->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1); $path = substr(json_encode($exception->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1);
@@ -101,14 +101,14 @@ class JsonFormatterTest extends TestCase
{ {
$formatter = new JsonFormatter(); $formatter = new JsonFormatter();
$exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?')); $exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'core', 'channel' => 'core',
'context' => array('exception' => $exception), 'context' => ['exception' => $exception],
'datetime' => new \DateTimeImmutable(), 'datetime' => new \DateTimeImmutable(),
'extra' => array(), 'extra' => [],
'message' => 'foobar', 'message' => 'foobar',
)); ]);
if (version_compare(PHP_VERSION, '5.4.0', '>=')) { if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
$pathPrevious = substr(json_encode($exception->getPrevious()->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1); $pathPrevious = substr(json_encode($exception->getPrevious()->getFile(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), 1, -1);

View File

@@ -19,103 +19,103 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefFormatWithString() public function testDefFormatWithString()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'log', 'channel' => 'log',
'context' => array(), 'context' => [],
'message' => 'foo', 'message' => 'foo',
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
)); ]);
$this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
} }
public function testDefFormatWithArrayContext() public function testDefFormatWithArrayContext()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'message' => 'foo', 'message' => 'foo',
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
'context' => array( 'context' => [
'foo' => 'bar', 'foo' => 'bar',
'baz' => 'qux', 'baz' => 'qux',
'bool' => false, 'bool' => false,
'null' => null, 'null' => null,
), ],
)); ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message);
} }
public function testDefFormatExtras() public function testDefFormatExtras()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array('ip' => '127.0.0.1'), 'extra' => ['ip' => '127.0.0.1'],
'message' => 'log', 'message' => 'log',
)); ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message);
} }
public function testFormatExtras() public function testFormatExtras()
{ {
$formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d'); $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array('ip' => '127.0.0.1', 'file' => 'test'), 'extra' => ['ip' => '127.0.0.1', 'file' => 'test'],
'message' => 'log', 'message' => 'log',
)); ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message);
} }
public function testContextAndExtraOptionallyNotShownIfEmpty() public function testContextAndExtraOptionallyNotShownIfEmpty()
{ {
$formatter = new LineFormatter(null, 'Y-m-d', false, true); $formatter = new LineFormatter(null, 'Y-m-d', false, true);
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
)); ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message);
} }
public function testContextAndExtraReplacement() public function testContextAndExtraReplacement()
{ {
$formatter = new LineFormatter('%context.foo% => %extra.foo%'); $formatter = new LineFormatter('%context.foo% => %extra.foo%');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('foo' => 'bar'), 'context' => ['foo' => 'bar'],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array('foo' => 'xbar'), 'extra' => ['foo' => 'xbar'],
'message' => 'log', 'message' => 'log',
)); ]);
$this->assertEquals('bar => xbar', $message); $this->assertEquals('bar => xbar', $message);
} }
public function testDefFormatWithObject() public function testDefFormatWithObject()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array('foo' => new TestFoo, 'bar' => new TestBar, 'baz' => array(), 'res' => fopen('php://memory', 'rb')), 'extra' => ['foo' => new TestFoo, 'bar' => new TestBar, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
'message' => 'foobar', 'message' => 'foobar',
)); ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message);
} }
@@ -123,14 +123,14 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefFormatWithException() public function testDefFormatWithException()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'core', 'channel' => 'core',
'context' => array('exception' => new \RuntimeException('Foo')), 'context' => ['exception' => new \RuntimeException('Foo')],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
'message' => 'foobar', 'message' => 'foobar',
)); ]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
@@ -141,14 +141,14 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$previous = new \LogicException('Wut?'); $previous = new \LogicException('Wut?');
$message = $formatter->format(array( $message = $formatter->format([
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'core', 'channel' => 'core',
'context' => array('exception' => new \RuntimeException('Foo', 0, $previous)), 'context' => ['exception' => new \RuntimeException('Foo', 0, $previous)],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
'message' => 'foobar', 'message' => 'foobar',
)); ]);
$path = str_replace('\\/', '/', json_encode(__FILE__)); $path = str_replace('\\/', '/', json_encode(__FILE__));
@@ -158,24 +158,24 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
public function testBatchFormat() public function testBatchFormat()
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->formatBatch(array( $message = $formatter->formatBatch([
array( [
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'test', 'channel' => 'test',
'message' => 'bar', 'message' => 'bar',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
), ],
array( [
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'log', 'channel' => 'log',
'message' => 'foo', 'message' => 'foo',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
), ],
)); ]);
$this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message); $this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
} }
@@ -183,11 +183,11 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d'); $formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format( $message = $formatter->format(
array( [
'message' => "foo\nbar", 'message' => "foo\nbar",
'context' => array(), 'context' => [],
'extra' => array(), 'extra' => [],
) ]
); );
$this->assertRegExp('/foo bar/', $message); $this->assertRegExp('/foo bar/', $message);
@@ -197,11 +197,11 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
{ {
$formatter = new LineFormatter(null, 'Y-m-d', true); $formatter = new LineFormatter(null, 'Y-m-d', true);
$message = $formatter->format( $message = $formatter->format(
array( [
'message' => "foo\nbar", 'message' => "foo\nbar",
'context' => array(), 'context' => [],
'extra' => array(), 'extra' => [],
) ]
); );
$this->assertRegExp('/foo\nbar/', $message); $this->assertRegExp('/foo\nbar/', $message);

View File

@@ -28,15 +28,15 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormatterV1() public function testDefaultFormatterV1()
{ {
$formatter = new LogstashFormatter('test', 'hostname', null, 'ctxt_'); $formatter = new LogstashFormatter('test', 'hostname', null, 'ctxt_');
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -61,15 +61,15 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLineV1() public function testFormatWithFileAndLineV1()
{ {
$formatter = new LogstashFormatter('test', null, null, 'ctxt_'); $formatter = new LogstashFormatter('test', null, null, 'ctxt_');
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('file' => 'test', 'line' => 14), 'extra' => ['file' => 'test', 'line' => 14],
'message' => 'log', 'message' => 'log',
); ];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -83,15 +83,15 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithContextV1() public function testFormatWithContextV1()
{ {
$formatter = new LogstashFormatter('test', null, null, 'ctxt_'); $formatter = new LogstashFormatter('test', null, null, 'ctxt_');
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('key' => 'pair'), 'extra' => ['key' => 'pair'],
'message' => 'log', 'message' => 'log',
); ];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -112,15 +112,15 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithExtraV1() public function testFormatWithExtraV1()
{ {
$formatter = new LogstashFormatter('test', null, null, 'ctxt_'); $formatter = new LogstashFormatter('test', null, null, 'ctxt_');
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('key' => 'pair'), 'extra' => ['key' => 'pair'],
'message' => 'log', 'message' => 'log',
); ];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -138,15 +138,15 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithApplicationNameV1() public function testFormatWithApplicationNameV1()
{ {
$formatter = new LogstashFormatter('app', 'test', null, 'ctxt_'); $formatter = new LogstashFormatter('app', 'test', null, 'ctxt_');
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('key' => 'pair'), 'extra' => ['key' => 'pair'],
'message' => 'log', 'message' => 'log',
); ];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);
@@ -157,17 +157,17 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithLatin9Data() public function testFormatWithLatin9Data()
{ {
$formatter = new LogstashFormatter('test', 'hostname'); $formatter = new LogstashFormatter('test', 'hostname');
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => '¯\_(ツ)_/¯', 'channel' => '¯\_(ツ)_/¯',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array( 'extra' => [
'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist", 'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist",
), ],
'message' => 'log', 'message' => 'log',
); ];
$message = json_decode($formatter->format($record), true); $message = json_decode($formatter->format($record), true);

View File

@@ -27,10 +27,10 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
public function constructArgumentProvider() public function constructArgumentProvider()
{ {
return array( return [
array(1, true, 1, true), [1, true, 1, true],
array(0, false, 0, false), [0, false, 0, false],
); ];
} }
/** /**
@@ -56,28 +56,28 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
public function testSimpleFormat() public function testSimpleFormat()
{ {
$record = array( $record = [
'message' => 'some log message', 'message' => 'some log message',
'context' => array(), 'context' => [],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test', 'channel' => 'test',
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => array(), 'extra' => [],
); ];
$formatter = new MongoDBFormatter(); $formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record); $formattedRecord = $formatter->format($record);
$this->assertCount(7, $formattedRecord); $this->assertCount(7, $formattedRecord);
$this->assertEquals('some log message', $formattedRecord['message']); $this->assertEquals('some log message', $formattedRecord['message']);
$this->assertEquals(array(), $formattedRecord['context']); $this->assertEquals([], $formattedRecord['context']);
$this->assertEquals(Logger::WARNING, $formattedRecord['level']); $this->assertEquals(Logger::WARNING, $formattedRecord['level']);
$this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']); $this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']);
$this->assertEquals('test', $formattedRecord['channel']); $this->assertEquals('test', $formattedRecord['channel']);
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['datetime']); $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['datetime']);
$this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString()); $this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString());
$this->assertEquals(array(), $formattedRecord['extra']); $this->assertEquals([], $formattedRecord['extra']);
} }
public function testRecursiveFormat() public function testRecursiveFormat()
@@ -86,21 +86,21 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
$someObject->foo = 'something'; $someObject->foo = 'something';
$someObject->bar = 'stuff'; $someObject->bar = 'stuff';
$record = array( $record = [
'message' => 'some log message', 'message' => 'some log message',
'context' => array( 'context' => [
'stuff' => new \DateTimeImmutable('1969-01-21T21:11:30.123456+00:00'), 'stuff' => new \DateTimeImmutable('1969-01-21T21:11:30.123456+00:00'),
'some_object' => $someObject, 'some_object' => $someObject,
'context_string' => 'some string', 'context_string' => 'some string',
'context_int' => 123456, 'context_int' => 123456,
'except' => new \Exception('exception message', 987), 'except' => new \Exception('exception message', 987),
), ],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test', 'channel' => 'test',
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => array(), 'extra' => [],
); ];
$formatter = new MongoDBFormatter(); $formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record); $formattedRecord = $formatter->format($record);
@@ -110,11 +110,11 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('-29731710123', $formattedRecord['context']['stuff']->__toString()); $this->assertEquals('-29731710123', $formattedRecord['context']['stuff']->__toString());
$this->assertEquals( $this->assertEquals(
array( [
'foo' => 'something', 'foo' => 'something',
'bar' => 'stuff', 'bar' => 'stuff',
'class' => 'stdClass', 'class' => 'stdClass',
), ],
$formattedRecord['context']['some_object'] $formattedRecord['context']['some_object']
); );
$this->assertEquals('some string', $formattedRecord['context']['context_string']); $this->assertEquals('some string', $formattedRecord['context']['context_string']);
@@ -131,75 +131,75 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatDepthArray() public function testFormatDepthArray()
{ {
$record = array( $record = [
'message' => 'some log message', 'message' => 'some log message',
'context' => array( 'context' => [
'nest2' => array( 'nest2' => [
'property' => 'anything', 'property' => 'anything',
'nest3' => array( 'nest3' => [
'nest4' => 'value', 'nest4' => 'value',
'property' => 'nothing', 'property' => 'nothing',
), ],
), ],
), ],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test', 'channel' => 'test',
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => array(), 'extra' => [],
); ];
$formatter = new MongoDBFormatter(2); $formatter = new MongoDBFormatter(2);
$formattedResult = $formatter->format($record); $formattedResult = $formatter->format($record);
$this->assertEquals( $this->assertEquals(
array( [
'nest2' => array( 'nest2' => [
'property' => 'anything', 'property' => 'anything',
'nest3' => '[...]', 'nest3' => '[...]',
), ],
), ],
$formattedResult['context'] $formattedResult['context']
); );
} }
public function testFormatDepthArrayInfiniteNesting() public function testFormatDepthArrayInfiniteNesting()
{ {
$record = array( $record = [
'message' => 'some log message', 'message' => 'some log message',
'context' => array( 'context' => [
'nest2' => array( 'nest2' => [
'property' => 'something', 'property' => 'something',
'nest3' => array( 'nest3' => [
'property' => 'anything', 'property' => 'anything',
'nest4' => array( 'nest4' => [
'property' => 'nothing', 'property' => 'nothing',
), ],
), ],
), ],
), ],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test', 'channel' => 'test',
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => array(), 'extra' => [],
); ];
$formatter = new MongoDBFormatter(0); $formatter = new MongoDBFormatter(0);
$formattedResult = $formatter->format($record); $formattedResult = $formatter->format($record);
$this->assertEquals( $this->assertEquals(
array( [
'nest2' => array( 'nest2' => [
'property' => 'something', 'property' => 'something',
'nest3' => array( 'nest3' => [
'property' => 'anything', 'property' => 'anything',
'nest4' => array( 'nest4' => [
'property' => 'nothing', 'property' => 'nothing',
), ],
), ],
), ],
), ],
$formattedResult['context'] $formattedResult['context']
); );
} }
@@ -212,46 +212,46 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
$someObject->nest3->property = 'nothing'; $someObject->nest3->property = 'nothing';
$someObject->nest3->nest4 = 'invisible'; $someObject->nest3->nest4 = 'invisible';
$record = array( $record = [
'message' => 'some log message', 'message' => 'some log message',
'context' => array( 'context' => [
'nest2' => $someObject, 'nest2' => $someObject,
), ],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test', 'channel' => 'test',
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => array(), 'extra' => [],
); ];
$formatter = new MongoDBFormatter(2, true); $formatter = new MongoDBFormatter(2, true);
$formattedResult = $formatter->format($record); $formattedResult = $formatter->format($record);
$this->assertEquals( $this->assertEquals(
array( [
'nest2' => array( 'nest2' => [
'property' => 'anything', 'property' => 'anything',
'nest3' => '[...]', 'nest3' => '[...]',
'class' => 'stdClass', 'class' => 'stdClass',
), ],
), ],
$formattedResult['context'] $formattedResult['context']
); );
} }
public function testFormatDepthException() public function testFormatDepthException()
{ {
$record = array( $record = [
'message' => 'some log message', 'message' => 'some log message',
'context' => array( 'context' => [
'nest2' => new \Exception('exception message', 987), 'nest2' => new \Exception('exception message', 987),
), ],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING), 'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test', 'channel' => 'test',
'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'), 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
'extra' => array(), 'extra' => [],
); ];
$formatter = new MongoDBFormatter(2, false); $formatter = new MongoDBFormatter(2, false);
$formattedRecord = $formatter->format($record); $formattedRecord = $formatter->format($record);

View File

@@ -26,40 +26,40 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormat() public function testFormat()
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->format(array( $formatted = $formatter->format([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'message' => 'foo', 'message' => 'foo',
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')), 'extra' => ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
'context' => array( 'context' => [
'foo' => 'bar', 'foo' => 'bar',
'baz' => 'qux', 'baz' => 'qux',
'inf' => INF, 'inf' => INF,
'-inf' => -INF, '-inf' => -INF,
'nan' => acos(4), 'nan' => acos(4),
), ],
)); ]);
$this->assertEquals(array( $this->assertEquals([
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'message' => 'foo', 'message' => 'foo',
'datetime' => date('Y-m-d'), 'datetime' => date('Y-m-d'),
'extra' => array( 'extra' => [
'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]], 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'], 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
'baz' => array(), 'baz' => [],
'res' => '[resource(stream)]', 'res' => '[resource(stream)]',
), ],
'context' => array( 'context' => [
'foo' => 'bar', 'foo' => 'bar',
'baz' => 'qux', 'baz' => 'qux',
'inf' => 'INF', 'inf' => 'INF',
'-inf' => '-INF', '-inf' => '-INF',
'nan' => 'NaN', 'nan' => 'NaN',
), ],
), $formatted); ], $formatted);
} }
public function testFormatExceptions() public function testFormatExceptions()
@@ -67,72 +67,72 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$e = new \LogicException('bar'); $e = new \LogicException('bar');
$e2 = new \RuntimeException('foo', 0, $e); $e2 = new \RuntimeException('foo', 0, $e);
$formatted = $formatter->format(array( $formatted = $formatter->format([
'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(array( $this->assertEquals([
'exception' => array( '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(),
), ],
), $formatted); ], $formatted);
} }
public function testFormatToStringExceptionHandle() public function testFormatToStringExceptionHandle()
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$this->setExpectedException('RuntimeException', 'Could not convert to string'); $this->setExpectedException('RuntimeException', 'Could not convert to string');
$formatter->format(array( $formatter->format([
'myObject' => new TestToStringError(), 'myObject' => new TestToStringError(),
)); ]);
} }
public function testBatchFormat() public function testBatchFormat()
{ {
$formatter = new NormalizerFormatter('Y-m-d'); $formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->formatBatch(array( $formatted = $formatter->formatBatch([
array( [
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'test', 'channel' => 'test',
'message' => 'bar', 'message' => 'bar',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
), ],
array( [
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'log', 'channel' => 'log',
'message' => 'foo', 'message' => 'foo',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable, 'datetime' => new \DateTimeImmutable,
'extra' => array(), 'extra' => [],
), ],
)); ]);
$this->assertEquals(array( $this->assertEquals([
array( [
'level_name' => 'CRITICAL', 'level_name' => 'CRITICAL',
'channel' => 'test', 'channel' => 'test',
'message' => 'bar', 'message' => 'bar',
'context' => array(), 'context' => [],
'datetime' => date('Y-m-d'), 'datetime' => date('Y-m-d'),
'extra' => array(), 'extra' => [],
), ],
array( [
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'log', 'channel' => 'log',
'message' => 'foo', 'message' => 'foo',
'context' => array(), 'context' => [],
'datetime' => date('Y-m-d'), 'datetime' => date('Y-m-d'),
'extra' => array(), 'extra' => [],
), ],
), $formatted); ], $formatted);
} }
/** /**
@@ -159,11 +159,11 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson'); $reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true); $reflMethod->setAccessible(true);
$res = $reflMethod->invoke($formatter, array($foo, $bar), true); $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
restore_error_handler(); restore_error_handler();
$this->assertEquals(@json_encode(array($foo, $bar)), $res); $this->assertEquals(@json_encode([$foo, $bar]), $res);
} }
public function testIgnoresInvalidTypes() public function testIgnoresInvalidTypes()
@@ -183,11 +183,11 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson'); $reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true); $reflMethod->setAccessible(true);
$res = $reflMethod->invoke($formatter, array($resource), true); $res = $reflMethod->invoke($formatter, [$resource], true);
restore_error_handler(); restore_error_handler();
$this->assertEquals(@json_encode(array($resource)), $res); $this->assertEquals(@json_encode([$resource]), $res);
} }
/** /**
@@ -211,7 +211,7 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$reflMethod = new \ReflectionMethod($formatter, 'toJson'); $reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true); $reflMethod->setAccessible(true);
$res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE")); $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
$this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res); $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
} }
@@ -233,19 +233,19 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
{ {
$obj = new \stdClass; $obj = new \stdClass;
return array( return [
'null' => array(null, null), 'null' => [null, null],
'int' => array(123, 123), 'int' => [123, 123],
'float' => array(123.45, 123.45), 'float' => [123.45, 123.45],
'bool false' => array(false, false), 'bool false' => [false, false],
'bool true' => array(true, true), 'bool true' => [true, true],
'ascii string' => array('abcdef', 'abcdef'), 'ascii string' => ['abcdef', 'abcdef'],
'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'), 'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'), 'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
'empty array' => array(array(), array()), 'empty array' => [[], []],
'array' => array(array('abcdef'), array('abcdef')), 'array' => [['abcdef'], ['abcdef']],
'object' => array($obj, $obj), 'object' => [$obj, $obj],
); ];
} }
/** /**
@@ -265,12 +265,12 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
public function providesHandleJsonErrorFailure() public function providesHandleJsonErrorFailure()
{ {
return array( return [
'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'), 'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'), 'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'), 'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
'default' => array(-1, 'Unknown error'), 'default' => [-1, 'Unknown error'],
); ];
} }
public function testExceptionTraceWithArgs() public function testExceptionTraceWithArgs()
@@ -298,7 +298,7 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
} }
$formatter = new NormalizerFormatter(); $formatter = new NormalizerFormatter();
$record = array('context' => array('exception' => $e)); $record = ['context' => ['exception' => $e]];
$result = $formatter->format($record); $result = $formatter->format($record);
$this->assertRegExp( $this->assertRegExp(

View File

@@ -24,7 +24,7 @@ class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
public function buildTrace(\Exception $e) public function buildTrace(\Exception $e)
{ {
$data = array(); $data = [];
$trace = $e->getTrace(); $trace = $e->getTrace();
foreach ($trace as $frame) { foreach ($trace as $frame) {
if (isset($frame['file'])) { if (isset($frame['file'])) {
@@ -45,64 +45,64 @@ class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormat() public function testFormat()
{ {
$exception = new \Exception('foo'); $exception = new \Exception('foo');
$formatted = $this->formatter->format(array( $formatted = $this->formatter->format([
'foo' => 'string', 'foo' => 'string',
'bar' => 1, 'bar' => 1,
'baz' => false, 'baz' => false,
'bam' => array(1, 2, 3), 'bam' => [1, 2, 3],
'bat' => array('foo' => 'bar'), 'bat' => ['foo' => 'bar'],
'bap' => $dt = new DateTimeImmutable(true), 'bap' => $dt = new DateTimeImmutable(true),
'ban' => $exception, 'ban' => $exception,
)); ]);
$this->assertSame(array( $this->assertSame([
'foo' => 'string', 'foo' => 'string',
'bar' => 1, 'bar' => 1,
'baz' => false, 'baz' => false,
'bam' => $this->encodeJson(array(1, 2, 3)), 'bam' => $this->encodeJson([1, 2, 3]),
'bat' => $this->encodeJson(array('foo' => 'bar')), 'bat' => $this->encodeJson(['foo' => 'bar']),
'bap' => (string) $dt, 'bap' => (string) $dt,
'ban' => $this->encodeJson(array( 'ban' => $this->encodeJson([
'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(),
'trace' => $this->buildTrace($exception), 'trace' => $this->buildTrace($exception),
)), ]),
), $formatted); ], $formatted);
} }
public function testFormatWithErrorContext() public function testFormatWithErrorContext()
{ {
$context = array('file' => 'foo', 'line' => 1); $context = ['file' => 'foo', 'line' => 1];
$formatted = $this->formatter->format(array( $formatted = $this->formatter->format([
'context' => $context, 'context' => $context,
)); ]);
$this->assertSame(array( $this->assertSame([
'context' => $this->encodeJson($context), 'context' => $this->encodeJson($context),
), $formatted); ], $formatted);
} }
public function testFormatWithExceptionContext() public function testFormatWithExceptionContext()
{ {
$exception = new \Exception('foo'); $exception = new \Exception('foo');
$formatted = $this->formatter->format(array( $formatted = $this->formatter->format([
'context' => array( 'context' => [
'exception' => $exception, 'exception' => $exception,
), ],
)); ]);
$this->assertSame(array( $this->assertSame([
'context' => $this->encodeJson(array( 'context' => $this->encodeJson([
'exception' => array( '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(),
'trace' => $this->buildTrace($exception), 'trace' => $this->buildTrace($exception),
), ],
)), ]),
), $formatted); ], $formatted);
} }
} }

View File

@@ -21,15 +21,15 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormat() public function testDefaultFormat()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('ip' => '127.0.0.1'), 'extra' => ['ip' => '127.0.0.1'],
'message' => 'log', 'message' => 'log',
); ];
$message = $wildfire->format($record); $message = $wildfire->format($record);
@@ -46,15 +46,15 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLine() public function testFormatWithFileAndLine()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('from' => 'logger'), 'context' => ['from' => 'logger'],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14), 'extra' => ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
'message' => 'log', 'message' => 'log',
); ];
$message = $wildfire->format($record); $message = $wildfire->format($record);
@@ -71,15 +71,15 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithoutContext() public function testFormatWithoutContext()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$message = $wildfire->format($record); $message = $wildfire->format($record);
@@ -96,17 +96,17 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testBatchFormatThrowException() public function testBatchFormatThrowException()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array(), 'context' => [],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$wildfire->formatBatch(array($record)); $wildfire->formatBatch([$record]);
} }
/** /**
@@ -115,22 +115,22 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testTableFormat() public function testTableFormat()
{ {
$wildfire = new WildfireFormatter(); $wildfire = new WildfireFormatter();
$record = array( $record = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'table-channel', 'channel' => 'table-channel',
'context' => array( 'context' => [
WildfireFormatter::TABLE => array( WildfireFormatter::TABLE => [
array('col1', 'col2', 'col3'), ['col1', 'col2', 'col3'],
array('val1', 'val2', 'val3'), ['val1', 'val2', 'val3'],
array('foo1', 'foo2', 'foo3'), ['foo1', 'foo2', 'foo3'],
array('bar1', 'bar2', 'bar3'), ['bar1', 'bar2', 'bar3'],
), ],
), ],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'table-message', 'message' => 'table-message',
); ];
$message = $wildfire->format($record); $message = $wildfire->format($record);

View File

@@ -25,7 +25,7 @@ class AbstractHandlerTest extends TestCase
*/ */
public function testConstructAndGetSet() public function testConstructAndGetSet()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]);
$this->assertEquals(Logger::WARNING, $handler->getLevel()); $this->assertEquals(Logger::WARNING, $handler->getLevel());
$this->assertEquals(false, $handler->getBubble()); $this->assertEquals(false, $handler->getBubble());
@@ -43,7 +43,7 @@ class AbstractHandlerTest extends TestCase
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
$handler->expects($this->exactly(2)) $handler->expects($this->exactly(2))
->method('handle'); ->method('handle');
$handler->handleBatch(array($this->getRecord(), $this->getRecord())); $handler->handleBatch([$this->getRecord(), $this->getRecord()]);
} }
/** /**
@@ -51,7 +51,7 @@ class AbstractHandlerTest extends TestCase
*/ */
public function testIsHandling() public function testIsHandling()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]);
$this->assertTrue($handler->isHandling($this->getRecord())); $this->assertTrue($handler->isHandling($this->getRecord()));
$this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
} }
@@ -61,7 +61,7 @@ class AbstractHandlerTest extends TestCase
*/ */
public function testHandlesPsrStyleLevels() public function testHandlesPsrStyleLevels()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array('warning', false)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', ['warning', false]);
$this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
$handler->setLevel('debug'); $handler->setLevel('debug');
$this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG)));

View File

@@ -24,7 +24,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testConstructAndGetSet() public function testConstructAndGetSet()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, false)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]);
$handler->setFormatter($formatter = new LineFormatter); $handler->setFormatter($formatter = new LineFormatter);
$this->assertSame($formatter, $handler->getFormatter()); $this->assertSame($formatter, $handler->getFormatter());
} }
@@ -34,7 +34,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleLowerLevelMessage() public function testHandleLowerLevelMessage()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, true)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, true]);
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
} }
@@ -43,7 +43,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleBubbling() public function testHandleBubbling()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, true)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, true]);
$this->assertFalse($handler->handle($this->getRecord())); $this->assertFalse($handler->handle($this->getRecord()));
} }
@@ -52,7 +52,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleNotBubbling() public function testHandleNotBubbling()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, false)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, false]);
$this->assertTrue($handler->handle($this->getRecord())); $this->assertTrue($handler->handle($this->getRecord()));
} }
@@ -61,7 +61,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/ */
public function testHandleIsFalseWhenNotHandled() public function testHandleIsFalseWhenNotHandled()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, false)); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]);
$this->assertTrue($handler->handle($this->getRecord())); $this->assertTrue($handler->handle($this->getRecord()));
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
} }
@@ -72,13 +72,13 @@ class AbstractProcessingHandlerTest extends TestCase
public function testProcessRecord() public function testProcessRecord()
{ {
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler'); $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler');
$handler->pushProcessor(new WebProcessor(array( $handler->pushProcessor(new WebProcessor([
'REQUEST_URI' => '', 'REQUEST_URI' => '',
'REQUEST_METHOD' => '', 'REQUEST_METHOD' => '',
'REMOTE_ADDR' => '', 'REMOTE_ADDR' => '',
'SERVER_NAME' => '', 'SERVER_NAME' => '',
'UNIQUE_ID' => '', 'UNIQUE_ID' => '',
))); ]));
$handledRecord = null; $handledRecord = null;
$handler->expects($this->once()) $handler->expects($this->once())
->method('write') ->method('write')

View File

@@ -31,43 +31,43 @@ class AmqpHandlerTest extends TestCase
$this->markTestSkipped("Please update AMQP to version >= 1.0"); $this->markTestSkipped("Please update AMQP to version >= 1.0");
} }
$messages = array(); $messages = [];
$exchange = $this->getMock('AMQPExchange', array('publish', 'setName'), array(), '', false); $exchange = $this->getMock('AMQPExchange', ['publish', 'setName'], [], '', false);
$exchange->expects($this->once()) $exchange->expects($this->once())
->method('setName') ->method('setName')
->with('log') ->with('log')
; ;
$exchange->expects($this->any()) $exchange->expects($this->any())
->method('publish') ->method('publish')
->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = array()) use (&$messages) { ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = []) use (&$messages) {
$messages[] = array($message, $routing_key, $flags, $attributes); $messages[] = [$message, $routing_key, $flags, $attributes];
})) }))
; ;
$handler = new AmqpHandler($exchange, 'log'); $handler = new AmqpHandler($exchange, 'log');
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = array( $expected = [
array( [
'message' => 'test', 'message' => 'test',
'context' => array( 'context' => [
'data' => array(), 'data' => [],
'foo' => 34, 'foo' => 34,
), ],
'level' => 300, 'level' => 300,
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'test', 'channel' => 'test',
'extra' => array(), 'extra' => [],
), ],
'warning.test', 'warning.test',
0, 0,
array( [
'delivery_mode' => 2, 'delivery_mode' => 2,
'content_type' => 'application/json', 'content_type' => 'application/json',
), ],
); ];
$handler->handle($record); $handler->handle($record);
@@ -83,43 +83,43 @@ class AmqpHandlerTest extends TestCase
$this->markTestSkipped("php-amqplib not installed"); $this->markTestSkipped("php-amqplib not installed");
} }
$messages = array(); $messages = [];
$exchange = $this->getMock('PhpAmqpLib\Channel\AMQPChannel', array('basic_publish', '__destruct'), array(), '', false); $exchange = $this->getMock('PhpAmqpLib\Channel\AMQPChannel', ['basic_publish', '__destruct'], [], '', false);
$exchange->expects($this->any()) $exchange->expects($this->any())
->method('basic_publish') ->method('basic_publish')
->will($this->returnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) { ->will($this->returnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) {
$messages[] = array($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket); $messages[] = [$msg, $exchange, $routing_key, $mandatory, $immediate, $ticket];
})) }))
; ;
$handler = new AmqpHandler($exchange, 'log'); $handler = new AmqpHandler($exchange, 'log');
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = array( $expected = [
array( [
'message' => 'test', 'message' => 'test',
'context' => array( 'context' => [
'data' => array(), 'data' => [],
'foo' => 34, 'foo' => 34,
), ],
'level' => 300, 'level' => 300,
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'test', 'channel' => 'test',
'extra' => array(), 'extra' => [],
), ],
'log', 'log',
'warning.test', 'warning.test',
false, false,
false, false,
null, null,
array( [
'delivery_mode' => 2, 'delivery_mode' => 2,
'content_type' => 'application/json', 'content_type' => 'application/json',
), ],
); ];
$handler->handle($record); $handler->handle($record);

View File

@@ -89,7 +89,7 @@ EOF;
$handler = new BrowserConsoleHandler(); $handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter()); $handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Logger::DEBUG, 'test', array('foo' => 'bar'))); $handler->handle($this->getRecord(Logger::DEBUG, 'test', ['foo' => 'bar']));
$expected = <<<EOF $expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) { (function (c) {if (c && c.groupCollapsed) {

View File

@@ -47,7 +47,7 @@ class BufferHandlerTest extends TestCase
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::DEBUG));
$this->shutdownCheckHandler = $test; $this->shutdownCheckHandler = $test;
register_shutdown_function(array($this, 'checkPropagation')); register_shutdown_function([$this, 'checkPropagation']);
} }
public function checkPropagation() public function checkPropagation()

View File

@@ -32,17 +32,17 @@ class ChromePHPHandlerTest extends TestCase
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$expected = array( $expected = [
'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
'version' => ChromePHPHandler::VERSION, 'version' => ChromePHPHandler::VERSION,
'columns' => array('label', 'log', 'backtrace', 'type'), 'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => array( 'rows' => [
'test', 'test',
'test', 'test',
), ],
'request_uri' => '', 'request_uri' => '',
)))), ]))),
); ];
$this->assertEquals($expected, $handler->getHeaders()); $this->assertEquals($expected, $handler->getHeaders());
} }
@@ -56,33 +56,33 @@ class ChromePHPHandlerTest extends TestCase
// overflow chrome headers limit // overflow chrome headers limit
$handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 100 * 1024))); $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 100 * 1024)));
$expected = array( $expected = [
'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
'version' => ChromePHPHandler::VERSION, 'version' => ChromePHPHandler::VERSION,
'columns' => array('label', 'log', 'backtrace', 'type'), 'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => array( 'rows' => [
array( [
'test', 'test',
'test', 'test',
'unknown', 'unknown',
'log', 'log',
), ],
array( [
'test', 'test',
str_repeat('a', 150 * 1024), str_repeat('a', 150 * 1024),
'unknown', 'unknown',
'warn', 'warn',
), ],
array( [
'monolog', 'monolog',
'Incomplete logs, chrome header size limit reached', 'Incomplete logs, chrome header size limit reached',
'unknown', 'unknown',
'warn', 'warn',
), ],
), ],
'request_uri' => '', 'request_uri' => '',
)))), ]))),
); ];
$this->assertEquals($expected, $handler->getHeaders()); $this->assertEquals($expected, $handler->getHeaders());
} }
@@ -99,19 +99,19 @@ class ChromePHPHandlerTest extends TestCase
$handler2->handle($this->getRecord(Logger::DEBUG)); $handler2->handle($this->getRecord(Logger::DEBUG));
$handler2->handle($this->getRecord(Logger::WARNING)); $handler2->handle($this->getRecord(Logger::WARNING));
$expected = array( $expected = [
'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
'version' => ChromePHPHandler::VERSION, 'version' => ChromePHPHandler::VERSION,
'columns' => array('label', 'log', 'backtrace', 'type'), 'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => array( 'rows' => [
'test', 'test',
'test', 'test',
'test', 'test',
'test', 'test',
), ],
'request_uri' => '', 'request_uri' => '',
)))), ]))),
); ];
$this->assertEquals($expected, $handler2->getHeaders()); $this->assertEquals($expected, $handler2->getHeaders());
} }
@@ -119,14 +119,14 @@ class ChromePHPHandlerTest extends TestCase
class TestChromePHPHandler extends ChromePHPHandler class TestChromePHPHandler extends ChromePHPHandler
{ {
protected $headers = array(); protected $headers = [];
public static function reset() public static function reset()
{ {
self::$initialized = false; self::$initialized = false;
self::$overflowed = false; self::$overflowed = false;
self::$sendHeaders = true; self::$sendHeaders = true;
self::$json['rows'] = array(); self::$json['rows'] = [];
} }
protected function sendHeader($header, $content) protected function sendHeader($header, $content)

View File

@@ -18,7 +18,7 @@ class CouchDBHandlerTest extends TestCase
{ {
public function testHandle() public function testHandle()
{ {
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new CouchDBHandler(); $handler = new CouchDBHandler();

View File

@@ -26,21 +26,21 @@ class DoctrineCouchDBHandlerTest extends TestCase
public function testHandle() public function testHandle()
{ {
$client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient') $client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient')
->setMethods(array('postDocument')) ->setMethods(['postDocument'])
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = array( $expected = [
'message' => 'test', 'message' => 'test',
'context' => array('data' => ['stdClass' => []], 'foo' => 34), 'context' => ['data' => ['stdClass' => []], 'foo' => 34],
'level' => Logger::WARNING, 'level' => Logger::WARNING,
'level_name' => 'WARNING', 'level_name' => 'WARNING',
'channel' => 'test', 'channel' => 'test',
'datetime' => (string) $record['datetime'], 'datetime' => (string) $record['datetime'],
'extra' => array(), 'extra' => [],
); ];
$client->expects($this->once()) $client->expects($this->once())
->method('postDocument') ->method('postDocument')

View File

@@ -24,7 +24,7 @@ class DynamoDbHandlerTest extends TestCase
} }
$this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient') $this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient')
->setMethods(array('formatAttributes', '__call')) ->setMethods(['formatAttributes', '__call'])
->disableOriginalConstructor()->getMock(); ->disableOriginalConstructor()->getMock();
} }
@@ -48,7 +48,7 @@ class DynamoDbHandlerTest extends TestCase
{ {
$record = $this->getRecord(); $record = $this->getRecord();
$formatter = $this->getMock('Monolog\Formatter\FormatterInterface'); $formatter = $this->getMock('Monolog\Formatter\FormatterInterface');
$formatted = array('foo' => 1, 'bar' => 2); $formatted = ['foo' => 1, 'bar' => 2];
$handler = new DynamoDbHandler($this->client, 'foo'); $handler = new DynamoDbHandler($this->client, 'foo');
$handler->setFormatter($formatter); $handler->setFormatter($formatter);
@@ -65,10 +65,10 @@ class DynamoDbHandlerTest extends TestCase
$this->client $this->client
->expects($this->once()) ->expects($this->once())
->method('__call') ->method('__call')
->with('putItem', array(array( ->with('putItem', [[
'TableName' => 'foo', 'TableName' => 'foo',
'Item' => $formatted, 'Item' => $formatted,
))); ]]);
$handler->handle($record); $handler->handle($record);
} }

View File

@@ -29,10 +29,10 @@ class ElasticSearchHandlerTest extends TestCase
/** /**
* @var array Default handler options * @var array Default handler options
*/ */
protected $options = array( protected $options = [
'index' => 'my_index', 'index' => 'my_index',
'type' => 'doc_type', 'type' => 'doc_type',
); ];
public function setUp() public function setUp()
{ {
@@ -43,7 +43,7 @@ class ElasticSearchHandlerTest extends TestCase
// base mock Elastica Client object // base mock Elastica Client object
$this->client = $this->getMockBuilder('Elastica\Client') $this->client = $this->getMockBuilder('Elastica\Client')
->setMethods(array('addDocuments')) ->setMethods(['addDocuments'])
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
} }
@@ -57,19 +57,19 @@ class ElasticSearchHandlerTest extends TestCase
public function testHandle() public function testHandle()
{ {
// log message // log message
$msg = array( $msg = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
// format expected result // format expected result
$formatter = new ElasticaFormatter($this->options['index'], $this->options['type']); $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
$expected = array($formatter->format($msg)); $expected = [$formatter->format($msg)];
// setup ES client mock // setup ES client mock
$this->client->expects($this->any()) $this->client->expects($this->any())
@@ -79,7 +79,7 @@ class ElasticSearchHandlerTest extends TestCase
// perform tests // perform tests
$handler = new ElasticSearchHandler($this->client, $this->options); $handler = new ElasticSearchHandler($this->client, $this->options);
$handler->handle($msg); $handler->handle($msg);
$handler->handleBatch(array($msg)); $handler->handleBatch([$msg]);
} }
/** /**
@@ -113,11 +113,11 @@ class ElasticSearchHandlerTest extends TestCase
*/ */
public function testOptions() public function testOptions()
{ {
$expected = array( $expected = [
'index' => $this->options['index'], 'index' => $this->options['index'],
'type' => $this->options['type'], 'type' => $this->options['type'],
'ignore_error' => false, 'ignore_error' => false,
); ];
$handler = new ElasticSearchHandler($this->client, $this->options); $handler = new ElasticSearchHandler($this->client, $this->options);
$this->assertEquals($expected, $handler->getOptions()); $this->assertEquals($expected, $handler->getOptions());
} }
@@ -128,9 +128,9 @@ class ElasticSearchHandlerTest extends TestCase
*/ */
public function testConnectionErrors($ignore, $expectedError) public function testConnectionErrors($ignore, $expectedError)
{ {
$clientOpts = array('host' => '127.0.0.1', 'port' => 1); $clientOpts = ['host' => '127.0.0.1', 'port' => 1];
$client = new Client($clientOpts); $client = new Client($clientOpts);
$handlerOpts = array('ignore_error' => $ignore); $handlerOpts = ['ignore_error' => $ignore];
$handler = new ElasticSearchHandler($client, $handlerOpts); $handler = new ElasticSearchHandler($client, $handlerOpts);
if ($expectedError) { if ($expectedError) {
@@ -146,10 +146,10 @@ class ElasticSearchHandlerTest extends TestCase
*/ */
public function providerTestConnectionErrors() public function providerTestConnectionErrors()
{ {
return array( return [
array(false, array('RuntimeException', 'Error sending messages to Elasticsearch')), [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
array(true, false), [true, false],
); ];
} }
/** /**
@@ -162,28 +162,28 @@ class ElasticSearchHandlerTest extends TestCase
*/ */
public function testHandleIntegration() public function testHandleIntegration()
{ {
$msg = array( $msg = [
'level' => Logger::ERROR, 'level' => Logger::ERROR,
'level_name' => 'ERROR', 'level_name' => 'ERROR',
'channel' => 'meh', 'channel' => 'meh',
'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
'datetime' => new \DateTimeImmutable("@0"), 'datetime' => new \DateTimeImmutable("@0"),
'extra' => array(), 'extra' => [],
'message' => 'log', 'message' => 'log',
); ];
$expected = $msg; $expected = $msg;
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
$expected['context'] = array( $expected['context'] = [
'class' => '[object] (stdClass: {})', 'class' => '[object] (stdClass: {})',
'foo' => 7, 'foo' => 7,
0 => 'bar', 0 => 'bar',
); ];
$client = new Client(); $client = new Client();
$handler = new ElasticSearchHandler($client, $this->options); $handler = new ElasticSearchHandler($client, $this->options);
try { try {
$handler->handleBatch(array($msg)); $handler->handleBatch([$msg]);
} catch (\RuntimeException $e) { } catch (\RuntimeException $e) {
$this->markTestSkipped("Cannot connect to Elastic Search server on localhost"); $this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
} }
@@ -234,6 +234,6 @@ class ElasticSearchHandlerTest extends TestCase
return $data['_source']; return $data['_source'];
} }
return array(); return [];
} }
} }

View File

@@ -24,7 +24,7 @@ class ErrorLogHandlerTest extends TestCase
{ {
protected function setUp() protected function setUp()
{ {
$GLOBALS['error_log'] = array(); $GLOBALS['error_log'] = [];
} }
/** /**

View File

@@ -63,7 +63,7 @@ class FilterHandlerTest extends TestCase
$this->assertFalse($test->hasEmergencyRecords()); $this->assertFalse($test->hasEmergencyRecords());
$test = new TestHandler(); $test = new TestHandler();
$handler = new FilterHandler($test, array(Logger::INFO, Logger::ERROR)); $handler = new FilterHandler($test, [Logger::INFO, Logger::ERROR]);
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::DEBUG));
$this->assertFalse($test->hasDebugRecords()); $this->assertFalse($test->hasDebugRecords());
@@ -86,14 +86,14 @@ class FilterHandlerTest extends TestCase
$test = new TestHandler(); $test = new TestHandler();
$handler = new FilterHandler($test); $handler = new FilterHandler($test);
$levels = array(Logger::INFO, Logger::ERROR); $levels = [Logger::INFO, Logger::ERROR];
$handler->setAcceptedLevels($levels); $handler->setAcceptedLevels($levels);
$this->assertSame($levels, $handler->getAcceptedLevels()); $this->assertSame($levels, $handler->getAcceptedLevels());
$handler->setAcceptedLevels(array('info', 'error')); $handler->setAcceptedLevels(['info', 'error']);
$this->assertSame($levels, $handler->getAcceptedLevels()); $this->assertSame($levels, $handler->getAcceptedLevels());
$levels = array(Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY); $levels = [Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY];
$handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY); $handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY);
$this->assertSame($levels, $handler->getAcceptedLevels()); $this->assertSame($levels, $handler->getAcceptedLevels());

View File

@@ -203,7 +203,7 @@ class FingersCrossedHandlerTest extends TestCase
public function testChannelLevelActivationStrategy() public function testChannelLevelActivationStrategy()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, array('othertest' => Logger::DEBUG))); $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, ['othertest' => Logger::DEBUG]));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$this->assertFalse($test->hasWarningRecords()); $this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Logger::DEBUG); $record = $this->getRecord(Logger::DEBUG);
@@ -220,7 +220,7 @@ class FingersCrossedHandlerTest extends TestCase
public function testChannelLevelActivationStrategyWithPsrLevels() public function testChannelLevelActivationStrategyWithPsrLevels()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', array('othertest' => 'debug'))); $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug']));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$this->assertFalse($test->hasWarningRecords()); $this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Logger::DEBUG); $record = $this->getRecord(Logger::DEBUG);

View File

@@ -32,13 +32,13 @@ class FirePHPHandlerTest extends TestCase
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::WARNING));
$expected = array( $expected = [
'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1', 'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3', 'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
'X-Wf-1-1-1-1' => 'test', 'X-Wf-1-1-1-1' => 'test',
'X-Wf-1-1-1-2' => 'test', 'X-Wf-1-1-1-2' => 'test',
); ];
$this->assertEquals($expected, $handler->getHeaders()); $this->assertEquals($expected, $handler->getHeaders());
} }
@@ -55,18 +55,18 @@ class FirePHPHandlerTest extends TestCase
$handler2->handle($this->getRecord(Logger::DEBUG)); $handler2->handle($this->getRecord(Logger::DEBUG));
$handler2->handle($this->getRecord(Logger::WARNING)); $handler2->handle($this->getRecord(Logger::WARNING));
$expected = array( $expected = [
'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1', 'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3', 'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
'X-Wf-1-1-1-1' => 'test', 'X-Wf-1-1-1-1' => 'test',
'X-Wf-1-1-1-2' => 'test', 'X-Wf-1-1-1-2' => 'test',
); ];
$expected2 = array( $expected2 = [
'X-Wf-1-1-1-3' => 'test', 'X-Wf-1-1-1-3' => 'test',
'X-Wf-1-1-1-4' => 'test', 'X-Wf-1-1-1-4' => 'test',
); ];
$this->assertEquals($expected, $handler->getHeaders()); $this->assertEquals($expected, $handler->getHeaders());
$this->assertEquals($expected2, $handler2->getHeaders()); $this->assertEquals($expected2, $handler2->getHeaders());
@@ -75,7 +75,7 @@ class FirePHPHandlerTest extends TestCase
class TestFirePHPHandler extends FirePHPHandler class TestFirePHPHandler extends FirePHPHandler
{ {
protected $headers = array(); protected $headers = [];
public static function reset() public static function reset()
{ {

View File

@@ -56,15 +56,15 @@ class FleepHookHandlerTest extends TestCase
*/ */
public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays() public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays()
{ {
$record = array( $record = [
'message' => 'msg', 'message' => 'msg',
'context' => array(), 'context' => [],
'level' => Logger::DEBUG, 'level' => Logger::DEBUG,
'level_name' => Logger::getLevelName(Logger::DEBUG), 'level_name' => Logger::getLevelName(Logger::DEBUG),
'channel' => 'channel', 'channel' => 'channel',
'datetime' => new \DateTimeImmutable(), 'datetime' => new \DateTimeImmutable(),
'extra' => array(), 'extra' => [],
); ];
$expectedFormatter = new LineFormatter(null, null, true, true); $expectedFormatter = new LineFormatter(null, null, true, true);
$expected = $expectedFormatter->format($record); $expected = $expectedFormatter->format($record);

View File

@@ -61,11 +61,11 @@ class FlowdockHandlerTest extends TestCase
private function createHandler($token = 'myToken') private function createHandler($token = 'myToken')
{ {
$constructorArgs = array($token, Logger::DEBUG); $constructorArgs = [$token, Logger::DEBUG];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMock( $this->handler = $this->getMock(
'\Monolog\Handler\FlowdockHandler', '\Monolog\Handler\FlowdockHandler',
array('fsockopen', 'streamSetTimeout', 'closeSocket'), ['fsockopen', 'streamSetTimeout', 'closeSocket'],
$constructorArgs $constructorArgs
); );

View File

@@ -43,7 +43,7 @@ class GelfHandlerTest extends TestCase
protected function getMessagePublisher() protected function getMessagePublisher()
{ {
return $this->getMock('Gelf\Publisher', array('publish'), array(), '', false); return $this->getMock('Gelf\Publisher', ['publish'], [], '', false);
} }
public function testDebug() public function testDebug()

View File

@@ -22,7 +22,7 @@ class GroupHandlerTest extends TestCase
*/ */
public function testConstructorOnlyTakesHandler() public function testConstructorOnlyTakesHandler()
{ {
new GroupHandler(array(new TestHandler(), "foo")); new GroupHandler([new TestHandler(), "foo"]);
} }
/** /**
@@ -31,7 +31,7 @@ class GroupHandlerTest extends TestCase
*/ */
public function testHandle() public function testHandle()
{ {
$testHandlers = array(new TestHandler(), new TestHandler()); $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers); $handler = new GroupHandler($testHandlers);
$handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::INFO)); $handler->handle($this->getRecord(Logger::INFO));
@@ -47,9 +47,9 @@ class GroupHandlerTest extends TestCase
*/ */
public function testHandleBatch() public function testHandleBatch()
{ {
$testHandlers = array(new TestHandler(), new TestHandler()); $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers); $handler = new GroupHandler($testHandlers);
$handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]);
foreach ($testHandlers as $test) { foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords()); $this->assertTrue($test->hasInfoRecords());
@@ -62,7 +62,7 @@ class GroupHandlerTest extends TestCase
*/ */
public function testIsHandling() public function testIsHandling()
{ {
$testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)); $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)];
$handler = new GroupHandler($testHandlers); $handler = new GroupHandler($testHandlers);
$this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR)));
$this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING)));
@@ -75,7 +75,7 @@ class GroupHandlerTest extends TestCase
public function testHandleUsesProcessors() public function testHandleUsesProcessors()
{ {
$test = new TestHandler(); $test = new TestHandler();
$handler = new GroupHandler(array($test)); $handler = new GroupHandler([$test]);
$handler->pushProcessor(function ($record) { $handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true; $record['extra']['foo'] = true;

View File

@@ -37,10 +37,10 @@ class HandlerWrapperTest extends TestCase
*/ */
public function trueFalseDataProvider() public function trueFalseDataProvider()
{ {
return array( return [
array(true), [true],
array(false), [false],
); ];
} }
/** /**

View File

@@ -139,16 +139,16 @@ class HipChatHandlerTest extends TestCase
public function provideLevelColors() public function provideLevelColors()
{ {
return array( return [
array(Logger::DEBUG, 'gray'), [Logger::DEBUG, 'gray'],
array(Logger::INFO, 'green'), [Logger::INFO, 'green'],
array(Logger::WARNING, 'yellow'), [Logger::WARNING, 'yellow'],
array(Logger::ERROR, 'red'), [Logger::ERROR, 'red'],
array(Logger::CRITICAL, 'red'), [Logger::CRITICAL, 'red'],
array(Logger::ALERT, 'red'), [Logger::ALERT, 'red'],
array(Logger::EMERGENCY,'red'), [Logger::EMERGENCY,'red'],
array(Logger::NOTICE, 'green'), [Logger::NOTICE, 'green'],
); ];
} }
/** /**
@@ -168,45 +168,45 @@ class HipChatHandlerTest extends TestCase
public function provideBatchRecords() public function provideBatchRecords()
{ {
return array( return [
array( [
array( [
array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()],
array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()],
array('level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTimeImmutable()],
), ],
'red', 'red',
), ],
array( [
array( [
array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()],
array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()],
), ],
'yellow', 'yellow',
), ],
array( [
array( [
array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()],
array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()],
), ],
'green', 'green',
), ],
array( [
array( [
array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()), ['level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()],
), ],
'gray', 'gray',
), ],
); ];
} }
private function createHandler($token = 'myToken', $room = 'room1', $name = 'Monolog', $notify = false, $host = 'api.hipchat.com', $version = 'v1') private function createHandler($token = 'myToken', $room = 'room1', $name = 'Monolog', $notify = false, $host = 'api.hipchat.com', $version = 'v1')
{ {
$constructorArgs = array($token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version); $constructorArgs = [$token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMock( $this->handler = $this->getMock(
'\Monolog\Handler\HipChatHandler', '\Monolog\Handler\HipChatHandler',
array('fsockopen', 'streamSetTimeout', 'closeSocket'), ['fsockopen', 'streamSetTimeout', 'closeSocket'],
$constructorArgs $constructorArgs
); );

View File

@@ -42,11 +42,11 @@ class LogEntriesHandlerTest extends TestCase
public function testWriteBatchContent() public function testWriteBatchContent()
{ {
$records = array( $records = [
$this->getRecord(), $this->getRecord(),
$this->getRecord(), $this->getRecord(),
$this->getRecord(), $this->getRecord(),
); ];
$this->createHandler(); $this->createHandler();
$this->handler->handleBatch($records); $this->handler->handleBatch($records);
@@ -59,11 +59,11 @@ class LogEntriesHandlerTest extends TestCase
private function createHandler() private function createHandler()
{ {
$useSSL = extension_loaded('openssl'); $useSSL = extension_loaded('openssl');
$args = array('testToken', $useSSL, Logger::DEBUG, true); $args = ['testToken', $useSSL, Logger::DEBUG, true];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMock( $this->handler = $this->getMock(
'\Monolog\Handler\LogEntriesHandler', '\Monolog\Handler\LogEntriesHandler',
array('fsockopen', 'streamSetTimeout', 'closeSocket'), ['fsockopen', 'streamSetTimeout', 'closeSocket'],
$args $args
); );

View File

@@ -41,11 +41,11 @@ class MailHandlerTest extends TestCase
*/ */
public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel() public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel()
{ {
$records = array( $records = [
$this->getRecord(Logger::DEBUG, 'debug message 1'), $this->getRecord(Logger::DEBUG, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'), $this->getRecord(Logger::DEBUG, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'), $this->getRecord(Logger::INFO, 'information'),
); ];
$handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
$handler->expects($this->never()) $handler->expects($this->never())
@@ -63,7 +63,7 @@ class MailHandlerTest extends TestCase
$handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
$record = $this->getRecord(); $record = $this->getRecord();
$records = array($record); $records = [$record];
$records[0]['formatted'] = '['.$record['datetime'].'] test.WARNING: test [] []'."\n"; $records[0]['formatted'] = '['.$record['datetime'].'] test.WARNING: test [] []'."\n";
$handler->expects($this->once()) $handler->expects($this->once())

View File

@@ -24,7 +24,7 @@ class NativeMailerHandlerTest extends TestCase
{ {
protected function setUp() protected function setUp()
{ {
$GLOBALS['mail'] = array(); $GLOBALS['mail'] = [];
} }
/** /**
@@ -50,7 +50,7 @@ class NativeMailerHandlerTest extends TestCase
public function testSetterArrayHeaderInjection() public function testSetterArrayHeaderInjection()
{ {
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org'); $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
$mailer->addHeader(array("Content-Type: text/html\r\nFrom: faked@attacker.org")); $mailer->addHeader(["Content-Type: text/html\r\nFrom: faked@attacker.org"]);
} }
/** /**
@@ -78,7 +78,7 @@ class NativeMailerHandlerTest extends TestCase
$from = 'receiver@example.org'; $from = 'receiver@example.org';
$mailer = new NativeMailerHandler($to, $subject, $from); $mailer = new NativeMailerHandler($to, $subject, $from);
$mailer->handleBatch(array()); $mailer->handleBatch([]);
// batch is empty, nothing sent // batch is empty, nothing sent
$this->assertEmpty($GLOBALS['mail']); $this->assertEmpty($GLOBALS['mail']);

View File

@@ -24,7 +24,7 @@ class NewRelicHandlerTest extends TestCase
public function setUp() public function setUp()
{ {
self::$appname = null; self::$appname = null;
self::$customParameters = array(); self::$customParameters = [];
self::$transactionName = null; self::$transactionName = null;
} }
@@ -46,8 +46,8 @@ class NewRelicHandlerTest extends TestCase
public function testThehandlerCanAddContextParamsToTheNewRelicTrace() public function testThehandlerCanAddContextParamsToTheNewRelicTrace()
{ {
$handler = new StubNewRelicHandler(); $handler = new StubNewRelicHandler();
$handler->handle($this->getRecord(Logger::ERROR, 'log message', array('a' => 'b'))); $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['a' => 'b']));
$this->assertEquals(array('context_a' => 'b'), self::$customParameters); $this->assertEquals(['context_a' => 'b'], self::$customParameters);
} }
public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace() public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace()
@@ -56,10 +56,10 @@ class NewRelicHandlerTest extends TestCase
$handler->handle($this->getRecord( $handler->handle($this->getRecord(
Logger::ERROR, Logger::ERROR,
'log message', 'log message',
array('a' => array('key1' => 'value1', 'key2' => 'value2')) ['a' => ['key1' => 'value1', 'key2' => 'value2']]
)); ));
$this->assertEquals( $this->assertEquals(
array('context_a_key1' => 'value1', 'context_a_key2' => 'value2'), ['context_a_key1' => 'value1', 'context_a_key2' => 'value2'],
self::$customParameters self::$customParameters
); );
} }
@@ -67,40 +67,40 @@ class NewRelicHandlerTest extends TestCase
public function testThehandlerCanAddExtraParamsToTheNewRelicTrace() public function testThehandlerCanAddExtraParamsToTheNewRelicTrace()
{ {
$record = $this->getRecord(Logger::ERROR, 'log message'); $record = $this->getRecord(Logger::ERROR, 'log message');
$record['extra'] = array('c' => 'd'); $record['extra'] = ['c' => 'd'];
$handler = new StubNewRelicHandler(); $handler = new StubNewRelicHandler();
$handler->handle($record); $handler->handle($record);
$this->assertEquals(array('extra_c' => 'd'), self::$customParameters); $this->assertEquals(['extra_c' => 'd'], self::$customParameters);
} }
public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace() public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace()
{ {
$record = $this->getRecord(Logger::ERROR, 'log message'); $record = $this->getRecord(Logger::ERROR, 'log message');
$record['extra'] = array('c' => array('key1' => 'value1', 'key2' => 'value2')); $record['extra'] = ['c' => ['key1' => 'value1', 'key2' => 'value2']];
$handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true); $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true);
$handler->handle($record); $handler->handle($record);
$this->assertEquals( $this->assertEquals(
array('extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'), ['extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'],
self::$customParameters self::$customParameters
); );
} }
public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace() public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace()
{ {
$record = $this->getRecord(Logger::ERROR, 'log message', array('a' => 'b')); $record = $this->getRecord(Logger::ERROR, 'log message', ['a' => 'b']);
$record['extra'] = array('c' => 'd'); $record['extra'] = ['c' => 'd'];
$handler = new StubNewRelicHandler(); $handler = new StubNewRelicHandler();
$handler->handle($record); $handler->handle($record);
$expected = array( $expected = [
'context_a' => 'b', 'context_a' => 'b',
'extra_c' => 'd', 'extra_c' => 'd',
); ];
$this->assertEquals($expected, self::$customParameters); $this->assertEquals($expected, self::$customParameters);
} }
@@ -131,7 +131,7 @@ class NewRelicHandlerTest extends TestCase
public function testTheAppNameCanBeOverriddenFromEachLog() public function testTheAppNameCanBeOverriddenFromEachLog()
{ {
$handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName'); $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName');
$handler->handle($this->getRecord(Logger::ERROR, 'log message', array('appname' => 'logAppName'))); $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['appname' => 'logAppName']));
$this->assertEquals('logAppName', self::$appname); $this->assertEquals('logAppName', self::$appname);
} }
@@ -155,7 +155,7 @@ class NewRelicHandlerTest extends TestCase
public function testTheTransactionNameCanBeOverriddenFromEachLog() public function testTheTransactionNameCanBeOverriddenFromEachLog()
{ {
$handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction'); $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction');
$handler->handle($this->getRecord(Logger::ERROR, 'log message', array('transaction_name' => 'logTransactName'))); $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['transaction_name' => 'logTransactName']));
$this->assertEquals('logTransactName', self::$transactionName); $this->assertEquals('logTransactName', self::$transactionName);
} }

View File

@@ -52,8 +52,8 @@ class PHPConsoleHandlerTest extends TestCase
{ {
return $this->getMockBuilder('PhpConsole\Dispatcher\Debug') return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array('dispatchDebug')) ->setMethods(['dispatchDebug'])
->setConstructorArgs(array($connector, $connector->getDumper())) ->setConstructorArgs([$connector, $connector->getDumper()])
->getMock(); ->getMock();
} }
@@ -61,8 +61,8 @@ class PHPConsoleHandlerTest extends TestCase
{ {
return $this->getMockBuilder('PhpConsole\Dispatcher\Errors') return $this->getMockBuilder('PhpConsole\Dispatcher\Errors')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array('dispatchError', 'dispatchException')) ->setMethods(['dispatchError', 'dispatchException'])
->setConstructorArgs(array($connector, $connector->getDumper())) ->setConstructorArgs([$connector, $connector->getDumper()])
->getMock(); ->getMock();
} }
@@ -70,7 +70,7 @@ class PHPConsoleHandlerTest extends TestCase
{ {
$connector = $this->getMockBuilder('PhpConsole\Connector') $connector = $this->getMockBuilder('PhpConsole\Connector')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods([
'sendMessage', 'sendMessage',
'onShutDown', 'onShutDown',
'isActiveClient', 'isActiveClient',
@@ -81,7 +81,7 @@ class PHPConsoleHandlerTest extends TestCase
'setAllowedIpMasks', 'setAllowedIpMasks',
'setHeadersLimit', 'setHeadersLimit',
'startEvalRequestsListener', 'startEvalRequestsListener',
)) ])
->getMock(); ->getMock();
$connector->expects($this->any()) $connector->expects($this->any())
@@ -93,17 +93,17 @@ class PHPConsoleHandlerTest extends TestCase
protected function getHandlerDefaultOption($name) protected function getHandlerDefaultOption($name)
{ {
$handler = new PHPConsoleHandler(array(), $this->connector); $handler = new PHPConsoleHandler([], $this->connector);
$options = $handler->getOptions(); $options = $handler->getOptions();
return $options[$name]; return $options[$name];
} }
protected function initLogger($handlerOptions = array(), $level = Logger::DEBUG) protected function initLogger($handlerOptions = [], $level = Logger::DEBUG)
{ {
return new Logger('test', array( return new Logger('test', [
new PHPConsoleHandler($handlerOptions, $this->connector, $level), new PHPConsoleHandler($handlerOptions, $this->connector, $level),
)); ]);
} }
public function testInitWithDefaultConnector() public function testInitWithDefaultConnector()
@@ -114,7 +114,7 @@ class PHPConsoleHandlerTest extends TestCase
public function testInitWithCustomConnector() public function testInitWithCustomConnector()
{ {
$handler = new PHPConsoleHandler(array(), $this->connector); $handler = new PHPConsoleHandler([], $this->connector);
$this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector())); $this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector()));
} }
@@ -128,7 +128,7 @@ class PHPConsoleHandlerTest extends TestCase
{ {
$message = 'test'; $message = 'test';
$tag = 'tag'; $tag = 'tag';
$context = array($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),
@@ -140,7 +140,7 @@ class PHPConsoleHandlerTest extends TestCase
public function testDebugTags($tagsContextKeys = null) public function testDebugTags($tagsContextKeys = null)
{ {
$expectedTags = mt_rand(); $expectedTags = mt_rand();
$logger = $this->initLogger($tagsContextKeys ? array('debugTagsKeysInContext' => $tagsContextKeys) : array()); $logger = $this->initLogger($tagsContextKeys ? ['debugTagsKeysInContext' => $tagsContextKeys] : []);
if (!$tagsContextKeys) { if (!$tagsContextKeys) {
$tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext'); $tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext');
} }
@@ -151,7 +151,7 @@ class PHPConsoleHandlerTest extends TestCase
$this->equalTo($expectedTags) $this->equalTo($expectedTags)
); );
$this->connector->setDebugDispatcher($debugDispatcher); $this->connector->setDebugDispatcher($debugDispatcher);
$logger->debug('test', array($key => $expectedTags)); $logger->debug('test', [$key => $expectedTags]);
} }
} }
@@ -168,8 +168,8 @@ class PHPConsoleHandlerTest extends TestCase
$this->equalTo($line), $this->equalTo($line),
$classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore')) $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
); );
$errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? array('classesPartialsTraceIgnore' => $classesPartialsTraceIgnore) : array()), false); $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false);
$errorHandler->registerErrorHandler(array(), false, E_USER_WARNING); $errorHandler->registerErrorHandler([], false, E_USER_WARNING);
$errorHandler->handleError($code, $message, $file, $line); $errorHandler->handleError($code, $message, $file, $line);
} }
@@ -183,7 +183,7 @@ class PHPConsoleHandlerTest extends TestCase
$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()),
array('exception' => $e) ['exception' => $e]
); );
} }
@@ -192,45 +192,45 @@ class PHPConsoleHandlerTest extends TestCase
*/ */
public function testWrongOptionsThrowsException() public function testWrongOptionsThrowsException()
{ {
new PHPConsoleHandler(array('xxx' => 1)); new PHPConsoleHandler(['xxx' => 1]);
} }
public function testOptionEnabled() public function testOptionEnabled()
{ {
$this->debugDispatcher->expects($this->never())->method('dispatchDebug'); $this->debugDispatcher->expects($this->never())->method('dispatchDebug');
$this->initLogger(array('enabled' => false))->debug('test'); $this->initLogger(['enabled' => false])->debug('test');
} }
public function testOptionClassesPartialsTraceIgnore() public function testOptionClassesPartialsTraceIgnore()
{ {
$this->testError(array('Class', 'Namespace\\')); $this->testError(['Class', 'Namespace\\']);
} }
public function testOptionDebugTagsKeysInContext() public function testOptionDebugTagsKeysInContext()
{ {
$this->testDebugTags(array('key1', 'key2')); $this->testDebugTags(['key1', 'key2']);
} }
public function testOptionUseOwnErrorsAndExceptionsHandler() public function testOptionUseOwnErrorsAndExceptionsHandler()
{ {
$this->initLogger(array('useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true)); $this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]);
$this->assertEquals(array(VendorPhpConsoleHandler::getInstance(), 'handleError'), set_error_handler(function () { $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () {
})); }));
$this->assertEquals(array(VendorPhpConsoleHandler::getInstance(), 'handleException'), set_exception_handler(function () { $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () {
})); }));
} }
public static function provideConnectorMethodsOptionsSets() public static function provideConnectorMethodsOptionsSets()
{ {
return array( return [
array('sourcesBasePath', 'setSourcesBasePath', __DIR__), ['sourcesBasePath', 'setSourcesBasePath', __DIR__],
array('serverEncoding', 'setServerEncoding', 'cp1251'), ['serverEncoding', 'setServerEncoding', 'cp1251'],
array('password', 'setPassword', '******'), ['password', 'setPassword', '******'],
array('enableSslOnlyMode', 'enableSslOnlyMode', true, false), ['enableSslOnlyMode', 'enableSslOnlyMode', true, false],
array('ipMasks', 'setAllowedIpMasks', array('127.0.0.*')), ['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']],
array('headersLimit', 'setHeadersLimit', 2500), ['headersLimit', 'setHeadersLimit', 2500],
array('enableEvalListener', 'startEvalRequestsListener', true, false), ['enableEvalListener', 'startEvalRequestsListener', true, false],
); ];
} }
/** /**
@@ -242,24 +242,24 @@ class PHPConsoleHandlerTest extends TestCase
if ($isArgument) { if ($isArgument) {
$expectCall->with($value); $expectCall->with($value);
} }
new PHPConsoleHandler(array($option => $value), $this->connector); new PHPConsoleHandler([$option => $value], $this->connector);
} }
public function testOptionDetectDumpTraceAndSource() public function testOptionDetectDumpTraceAndSource()
{ {
new PHPConsoleHandler(array('detectDumpTraceAndSource' => true), $this->connector); new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector);
$this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource); $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
} }
public static function provideDumperOptionsValues() public static function provideDumperOptionsValues()
{ {
return array( return [
array('dumperLevelLimit', 'levelLimit', 1001), ['dumperLevelLimit', 'levelLimit', 1001],
array('dumperItemsCountLimit', 'itemsCountLimit', 1002), ['dumperItemsCountLimit', 'itemsCountLimit', 1002],
array('dumperItemSizeLimit', 'itemSizeLimit', 1003), ['dumperItemSizeLimit', 'itemSizeLimit', 1003],
array('dumperDumpSizeLimit', 'dumpSizeLimit', 1004), ['dumperDumpSizeLimit', 'dumpSizeLimit', 1004],
array('dumperDetectCallbacks', 'detectCallbacks', true), ['dumperDetectCallbacks', 'detectCallbacks', true],
); ];
} }
/** /**
@@ -267,7 +267,7 @@ class PHPConsoleHandlerTest extends TestCase
*/ */
public function testDumperOptions($option, $dumperProperty, $value) public function testDumperOptions($option, $dumperProperty, $value)
{ {
new PHPConsoleHandler(array($option => $value), $this->connector); new PHPConsoleHandler([$option => $value], $this->connector);
$this->assertEquals($value, $this->connector->getDumper()->$dumperProperty); $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
} }
} }

View File

@@ -34,15 +34,15 @@ class ProcessHandlerTest extends TestCase
*/ */
public function testWriteOpensProcessAndWritesToStdInOfProcess() public function testWriteOpensProcessAndWritesToStdInOfProcess()
{ {
$fixtures = array( $fixtures = [
'chuck norris', 'chuck norris',
'foobar1337' 'foobar1337',
); ];
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->setMethods(array('writeProcessInput')); $mockBuilder->setMethods(['writeProcessInput']);
// using echo as command, as it is most probably available // using echo as command, as it is most probably available
$mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND)); $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
$handler = $mockBuilder->getMock(); $handler = $mockBuilder->getMock();
@@ -126,8 +126,8 @@ class ProcessHandlerTest extends TestCase
public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException() public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException()
{ {
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->setMethods(array('selectErrorStream')); $mockBuilder->setMethods(['selectErrorStream']);
$mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND)); $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
$handler = $mockBuilder->getMock(); $handler = $mockBuilder->getMock();
@@ -157,9 +157,9 @@ class ProcessHandlerTest extends TestCase
public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException() public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException()
{ {
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->setMethods(array('readProcessErrors')); $mockBuilder->setMethods(['readProcessErrors']);
// using echo as command, as it is most probably available // using echo as command, as it is most probably available
$mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND)); $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
$handler = $mockBuilder->getMock(); $handler = $mockBuilder->getMock();

View File

@@ -21,11 +21,11 @@ class PsrHandlerTest extends TestCase
{ {
public function logLevelProvider() public function logLevelProvider()
{ {
$levels = array(); $levels = [];
$monologLogger = new Logger(''); $monologLogger = new Logger('');
foreach ($monologLogger->getLevels() as $levelName => $level) { foreach ($monologLogger->getLevels() as $levelName => $level) {
$levels[] = array($levelName, $level); $levels[] = [$levelName, $level];
} }
return $levels; return $levels;
@@ -37,7 +37,7 @@ class PsrHandlerTest extends TestCase
public function testHandlesAllLevels($levelName, $level) public function testHandlesAllLevels($levelName, $level)
{ {
$message = 'Hello, world! ' . $level; $message = 'Hello, world! ' . $level;
$context = array('foo' => 'bar', 'level' => $level); $context = ['foo' => 'bar', 'level' => $level];
$psrLogger = $this->getMock('Psr\Log\NullLogger'); $psrLogger = $this->getMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once()) $psrLogger->expects($this->once())
@@ -45,6 +45,6 @@ class PsrHandlerTest extends TestCase
->with(strtolower($levelName), $message, $context); ->with(strtolower($levelName), $message, $context);
$handler = new PsrHandler($psrLogger); $handler = new PsrHandler($psrLogger);
$handler->handle(array('level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context)); $handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context]);
} }
} }

View File

@@ -103,7 +103,7 @@ class PushoverHandlerTest extends TestCase
public function testWriteToMultipleUsers() public function testWriteToMultipleUsers()
{ {
$this->createHandler('myToken', array('userA', 'userB')); $this->createHandler('myToken', ['userA', 'userB']);
$this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1')); $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1'));
fseek($this->res, 0); fseek($this->res, 0);
$content = fread($this->res, 1024); $content = fread($this->res, 1024);
@@ -114,11 +114,11 @@ class PushoverHandlerTest extends TestCase
private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog') private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog')
{ {
$constructorArgs = array($token, $user, $title); $constructorArgs = [$token, $user, $title];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMock( $this->handler = $this->getMock(
'\Monolog\Handler\PushoverHandler', '\Monolog\Handler\PushoverHandler',
array('fsockopen', 'streamSetTimeout', 'closeSocket'), ['fsockopen', 'streamSetTimeout', 'closeSocket'],
$constructorArgs $constructorArgs
); );

View File

@@ -78,8 +78,8 @@ class RavenHandlerTest extends TestCase
$ravenClient = $this->getRavenClient(); $ravenClient = $this->getRavenClient();
$handler = $this->getHandler($ravenClient); $handler = $this->getHandler($ravenClient);
$tags = array(1, 2, 'foo'); $tags = [1, 2, 'foo'];
$record = $this->getRecord(Logger::INFO, 'test', array('tags' => $tags)); $record = $this->getRecord(Logger::INFO, 'test', ['tags' => $tags]);
$handler->handle($record); $handler->handle($record);
$this->assertEquals($tags, $ravenClient->lastData['tags']); $this->assertEquals($tags, $ravenClient->lastData['tags']);
@@ -92,7 +92,7 @@ class RavenHandlerTest extends TestCase
$checksum = '098f6bcd4621d373cade4e832627b4f6'; $checksum = '098f6bcd4621d373cade4e832627b4f6';
$release = '05a671c66aefea124cc08b76ea6d30bb'; $release = '05a671c66aefea124cc08b76ea6d30bb';
$record = $this->getRecord(Logger::INFO, 'test', array('checksum' => $checksum, 'release' => $release)); $record = $this->getRecord(Logger::INFO, 'test', ['checksum' => $checksum, 'release' => $release]);
$handler->handle($record); $handler->handle($record);
$this->assertEquals($checksum, $ravenClient->lastData['checksum']); $this->assertEquals($checksum, $ravenClient->lastData['checksum']);
@@ -104,8 +104,8 @@ class RavenHandlerTest extends TestCase
$ravenClient = $this->getRavenClient(); $ravenClient = $this->getRavenClient();
$handler = $this->getHandler($ravenClient); $handler = $this->getHandler($ravenClient);
$fingerprint = array('{{ default }}', 'other value'); $fingerprint = ['{{ default }}', 'other value'];
$record = $this->getRecord(Logger::INFO, 'test', array('fingerprint' => $fingerprint)); $record = $this->getRecord(Logger::INFO, 'test', ['fingerprint' => $fingerprint]);
$handler->handle($record); $handler->handle($record);
$this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']); $this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']);
@@ -119,14 +119,14 @@ class RavenHandlerTest extends TestCase
$recordWithNoContext = $this->getRecord(Logger::INFO, 'test with default user context'); $recordWithNoContext = $this->getRecord(Logger::INFO, 'test with default user context');
// set user context 'externally' // set user context 'externally'
$user = array( $user = [
'id' => '123', 'id' => '123',
'email' => 'test@test.com', 'email' => 'test@test.com',
); ];
$recordWithContext = $this->getRecord(Logger::INFO, 'test', array('user' => $user)); $recordWithContext = $this->getRecord(Logger::INFO, 'test', ['user' => $user]);
$ravenClient->user_context(array('id' => 'test_user_id')); $ravenClient->user_context(['id' => 'test_user_id']);
// handle context // handle context
$handler->handle($recordWithContext); $handler->handle($recordWithContext);
$this->assertEquals($user, $ravenClient->lastData['user']); $this->assertEquals($user, $ravenClient->lastData['user']);
@@ -154,7 +154,7 @@ class RavenHandlerTest extends TestCase
try { try {
$this->methodThatThrowsAnException(); $this->methodThatThrowsAnException();
} catch (\Exception $e) { } catch (\Exception $e) {
$record = $this->getRecord(Logger::ERROR, $e->getMessage(), array('exception' => $e)); $record = $this->getRecord(Logger::ERROR, $e->getMessage(), ['exception' => $e]);
$handler->handle($record); $handler->handle($record);
} }
@@ -183,13 +183,13 @@ class RavenHandlerTest extends TestCase
public function testHandleBatchDoNothingIfRecordsAreBelowLevel() public function testHandleBatchDoNothingIfRecordsAreBelowLevel()
{ {
$records = array( $records = [
$this->getRecord(Logger::DEBUG, 'debug message 1'), $this->getRecord(Logger::DEBUG, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'), $this->getRecord(Logger::DEBUG, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'), $this->getRecord(Logger::INFO, 'information'),
); ];
$handler = $this->getMock('Monolog\Handler\RavenHandler', null, array($this->getRavenClient())); $handler = $this->getMock('Monolog\Handler\RavenHandler', null, [$this->getRavenClient()]);
$handler->expects($this->never())->method('handle'); $handler->expects($this->never())->method('handle');
$handler->setLevel(Logger::ERROR); $handler->setLevel(Logger::ERROR);
$handler->handleBatch($records); $handler->handleBatch($records);
@@ -215,7 +215,7 @@ class RavenHandlerTest extends TestCase
$this->assertEquals($release, $ravenClient->lastData['release']); $this->assertEquals($release, $ravenClient->lastData['release']);
$localRelease = 'v41.41.41'; $localRelease = 'v41.41.41';
$record = $this->getRecord(Logger::INFO, 'test', array('release' => $localRelease)); $record = $this->getRecord(Logger::INFO, 'test', ['release' => $localRelease]);
$handler->handle($record); $handler->handle($record);
$this->assertEquals($localRelease, $ravenClient->lastData['release']); $this->assertEquals($localRelease, $ravenClient->lastData['release']);
} }

View File

@@ -39,14 +39,14 @@ class RedisHandlerTest extends TestCase
public function testPredisHandle() public function testPredisHandle()
{ {
$redis = $this->getMock('Predis\Client', array('rpush')); $redis = $this->getMock('Predis\Client', ['rpush']);
// Predis\Client uses rpush // Predis\Client uses rpush
$redis->expects($this->once()) $redis->expects($this->once())
->method('rpush') ->method('rpush')
->with('key', 'test'); ->with('key', 'test');
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key'); $handler = new RedisHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%")); $handler->setFormatter(new LineFormatter("%message%"));
@@ -55,14 +55,14 @@ class RedisHandlerTest extends TestCase
public function testRedisHandle() public function testRedisHandle()
{ {
$redis = $this->getMock('Redis', array('rpush')); $redis = $this->getMock('Redis', ['rpush']);
// Redis uses rPush // Redis uses rPush
$redis->expects($this->once()) $redis->expects($this->once())
->method('rPush') ->method('rPush')
->with('key', 'test'); ->with('key', 'test');
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key'); $handler = new RedisHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%")); $handler->setFormatter(new LineFormatter("%message%"));
@@ -71,7 +71,7 @@ class RedisHandlerTest extends TestCase
public function testRedisHandleCapped() public function testRedisHandleCapped()
{ {
$redis = $this->getMock('Redis', array('multi', 'rpush', 'ltrim', 'exec')); $redis = $this->getMock('Redis', ['multi', 'rpush', 'ltrim', 'exec']);
// Redis uses multi // Redis uses multi
$redis->expects($this->once()) $redis->expects($this->once())
@@ -90,7 +90,7 @@ class RedisHandlerTest extends TestCase
->method('exec') ->method('exec')
->will($this->returnSelf()); ->will($this->returnSelf());
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10);
$handler->setFormatter(new LineFormatter("%message%")); $handler->setFormatter(new LineFormatter("%message%"));
@@ -99,9 +99,9 @@ class RedisHandlerTest extends TestCase
public function testPredisHandleCapped() public function testPredisHandleCapped()
{ {
$redis = $this->getMock('Predis\Client', array('transaction')); $redis = $this->getMock('Predis\Client', ['transaction']);
$redisTransaction = $this->getMock('Predis\Client', array('rpush', 'ltrim')); $redisTransaction = $this->getMock('Predis\Client', ['rpush', 'ltrim']);
$redisTransaction->expects($this->once()) $redisTransaction->expects($this->once())
->method('rpush') ->method('rpush')
@@ -118,7 +118,7 @@ class RedisHandlerTest extends TestCase
$cb($redisTransaction); $cb($redisTransaction);
})); }));
$record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10);
$handler->setFormatter(new LineFormatter("%message%")); $handler->setFormatter(new LineFormatter("%message%"));

View File

@@ -13,7 +13,6 @@ namespace Monolog\Handler;
use InvalidArgumentException; use InvalidArgumentException;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use PHPUnit_Framework_Error_Deprecated;
/** /**
* @covers Monolog\Handler\RotatingFileHandler * @covers Monolog\Handler\RotatingFileHandler
@@ -38,11 +37,11 @@ class RotatingFileHandlerTest extends TestCase
$this->lastError = null; $this->lastError = null;
$self = $this; $self = $this;
// workaround with &$self used for PHP 5.3 // workaround with &$self used for PHP 5.3
set_error_handler(function($code, $message) use (&$self) { set_error_handler(function ($code, $message) use (&$self) {
$self->lastError = array( $self->lastError = [
'code' => $code, 'code' => $code,
'message' => $message, 'message' => $message,
); ];
}); });
} }
@@ -108,32 +107,32 @@ class RotatingFileHandlerTest extends TestCase
public function rotationTests() public function rotationTests()
{ {
$now = time(); $now = time();
$dayCallback = function($ago) use ($now) { $dayCallback = function ($ago) use ($now) {
return $now + 86400 * $ago; return $now + 86400 * $ago;
}; };
$monthCallback = function($ago) { $monthCallback = function ($ago) {
return gmmktime(0, 0, 0, date('n') + $ago, date('d'), date('Y')); return gmmktime(0, 0, 0, date('n') + $ago, date('d'), date('Y'));
}; };
$yearCallback = function($ago) { $yearCallback = function ($ago) {
return gmmktime(0, 0, 0, date('n'), date('d'), date('Y') + $ago); return gmmktime(0, 0, 0, date('n'), date('d'), date('Y') + $ago);
}; };
return array( return [
'Rotation is triggered when the file of the current day is not present' 'Rotation is triggered when the file of the current day is not present'
=> array(true, RotatingFileHandler::FILE_PER_DAY, $dayCallback), => [true, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
'Rotation is not triggered when the file of the current day is already present' 'Rotation is not triggered when the file of the current day is already present'
=> array(false, RotatingFileHandler::FILE_PER_DAY, $dayCallback), => [false, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
'Rotation is triggered when the file of the current month is not present' 'Rotation is triggered when the file of the current month is not present'
=> array(true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback), => [true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
'Rotation is not triggered when the file of the current month is already present' 'Rotation is not triggered when the file of the current month is already present'
=> array(false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback), => [false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
'Rotation is triggered when the file of the current year is not present' 'Rotation is triggered when the file of the current year is not present'
=> array(true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback), => [true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
'Rotation is not triggered when the file of the current year is already present' 'Rotation is not triggered when the file of the current year is already present'
=> array(false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback), => [false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
); ];
} }
/** /**
@@ -150,13 +149,13 @@ class RotatingFileHandlerTest extends TestCase
public function dateFormatProvider() public function dateFormatProvider()
{ {
return array( return [
array(RotatingFileHandler::FILE_PER_DAY, true), [RotatingFileHandler::FILE_PER_DAY, true],
array(RotatingFileHandler::FILE_PER_MONTH, true), [RotatingFileHandler::FILE_PER_MONTH, true],
array(RotatingFileHandler::FILE_PER_YEAR, true), [RotatingFileHandler::FILE_PER_YEAR, true],
array('m-d-Y', false), ['m-d-Y', false],
array('Y-m-d-h-i', false) ['Y-m-d-h-i', false],
); ];
} }
/** /**
@@ -174,15 +173,15 @@ class RotatingFileHandlerTest extends TestCase
public function filenameFormatProvider() public function filenameFormatProvider()
{ {
return array( return [
array('{filename}', false), ['{filename}', false],
array('{filename}-{date}', true), ['{filename}-{date}', true],
array('{date}', true), ['{date}', true],
array('foobar-{date}', true), ['foobar-{date}', true],
array('foo-{date}-bar', true), ['foo-{date}-bar', true],
array('{date}-foobar', true), ['{date}-foobar', true],
array('foobar', false), ['foobar', false],
); ];
} }
public function testReuseCurrentFile() public function testReuseCurrentFile()

View File

@@ -92,25 +92,25 @@ class SlackHandlerTest extends TestCase
public function provideLevelColors() public function provideLevelColors()
{ {
return array( return [
array(Logger::DEBUG, '%23e3e4e6'), // escaped #e3e4e6 [Logger::DEBUG, '%23e3e4e6'], // escaped #e3e4e6
array(Logger::INFO, 'good'), [Logger::INFO, 'good'],
array(Logger::NOTICE, 'good'), [Logger::NOTICE, 'good'],
array(Logger::WARNING, 'warning'), [Logger::WARNING, 'warning'],
array(Logger::ERROR, 'danger'), [Logger::ERROR, 'danger'],
array(Logger::CRITICAL, 'danger'), [Logger::CRITICAL, 'danger'],
array(Logger::ALERT, 'danger'), [Logger::ALERT, 'danger'],
array(Logger::EMERGENCY,'danger'), [Logger::EMERGENCY,'danger'],
); ];
} }
private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false) private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false)
{ {
$constructorArgs = array($token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra); $constructorArgs = [$token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra];
$this->res = fopen('php://memory', 'a'); $this->res = fopen('php://memory', 'a');
$this->handler = $this->getMock( $this->handler = $this->getMock(
'\Monolog\Handler\SlackHandler', '\Monolog\Handler\SlackHandler',
array('fsockopen', 'streamSetTimeout', 'closeSocket'), ['fsockopen', 'streamSetTimeout', 'closeSocket'],
$constructorArgs $constructorArgs
); );

Some files were not shown because too many files have changed in this diff Show More