From f43e3d563776da6e696648025437ea0576dd1e9a Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 11 Nov 2024 15:21:55 +0100 Subject: [PATCH] Upgrade phpstan, phpunit (#1923) * Upgrade phpstan, phpunit * Fix phpunit deprecation * Fix hg tests * Fix php-console tests * Fix phpunit on 8.1 * Bump phpconsole --- .github/workflows/continuous-integration.yml | 5 + composer.json | 9 +- phpstan-baseline.neon | 96 ++++++++++++++----- phpstan.neon.dist | 6 +- phpunit.xml.dist | 3 + .../Formatter/GelfMessageFormatter.php | 4 +- src/Monolog/Formatter/JsonFormatter.php | 2 +- src/Monolog/Formatter/LineFormatter.php | 6 +- src/Monolog/Formatter/MongoDBFormatter.php | 2 +- src/Monolog/Formatter/NormalizerFormatter.php | 4 +- src/Monolog/Handler/BrowserConsoleHandler.php | 4 +- src/Monolog/Handler/ErrorLogHandler.php | 5 +- src/Monolog/Handler/MandrillHandler.php | 4 +- src/Monolog/Handler/OverflowHandler.php | 2 +- src/Monolog/Handler/SendGridHandler.php | 4 +- src/Monolog/Handler/Slack/SlackRecord.php | 4 +- src/Monolog/Handler/SocketHandler.php | 4 +- src/Monolog/Handler/SyslogUdpHandler.php | 2 +- src/Monolog/Handler/TestHandler.php | 16 ++-- src/Monolog/Logger.php | 2 +- src/Monolog/Processor/MercurialProcessor.php | 7 +- src/Monolog/Test/TestCase.php | 10 +- src/Monolog/Utils.php | 21 +--- tests/Monolog/ErrorHandlerTest.php | 6 +- .../Formatter/MongoDBFormatterTest.php | 2 - .../Formatter/NormalizerFormatterTest.php | 4 - .../Handler/BrowserConsoleHandlerTest.php | 1 - .../Monolog/Handler/FleepHookHandlerTest.php | 7 ++ tests/Monolog/Handler/FlowdockHandlerTest.php | 2 +- tests/Monolog/Handler/HandlerWrapperTest.php | 1 + .../Monolog/Handler/InsightOpsHandlerTest.php | 2 +- .../Monolog/Handler/LogEntriesHandlerTest.php | 2 +- tests/Monolog/Handler/LogmaticHandlerTest.php | 2 +- .../Monolog/Handler/PHPConsoleHandlerTest.php | 16 ++-- tests/Monolog/Handler/ProcessHandlerTest.php | 5 +- tests/Monolog/Handler/PushoverHandlerTest.php | 2 +- tests/Monolog/Handler/SlackHandlerTest.php | 2 +- tests/Monolog/Handler/SocketHandlerTest.php | 1 + tests/Monolog/Handler/StreamHandlerTest.php | 2 +- .../Handler/TelegramBotHandlerTest.php | 7 ++ tests/Monolog/LoggerTest.php | 1 - .../Processor/MercurialProcessorTest.php | 46 ++++++++- tests/Monolog/UtilsTest.php | 30 ------ 43 files changed, 210 insertions(+), 153 deletions(-) diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml index ce7b3b236..17a1e424d 100644 --- a/.github/workflows/continuous-integration.yml +++ b/.github/workflows/continuous-integration.yml @@ -78,6 +78,11 @@ jobs: composer-options: "${{ matrix.composer-options }}" - name: "Run tests" + if: "matrix.php-version >= '8.2'" + run: "composer exec phpunit -- --exclude-group Elasticsearch --exclude-group Elastica" + + - name: "Run tests" + if: "matrix.php-version == '8.1'" run: "composer exec phpunit -- --exclude-group Elasticsearch,Elastica" tests-es-7: diff --git a/composer.json b/composer.json index 43f258279..9574a1b0d 100644 --- a/composer.json +++ b/composer.json @@ -26,10 +26,11 @@ "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpstan/phpstan": "^1.9", - "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-strict-rules": "^1.4", - "phpunit/phpunit": "^10.5.17", + "php-console/php-console": "^3.1.8", + "phpstan/phpstan": "^2", + "phpstan/phpstan-deprecation-rules": "^2", + "phpstan/phpstan-strict-rules": "^2", + "phpunit/phpunit": "^10.5.17 || ^11.0.7", "predis/predis": "^1.1 || ^2", "rollbar/rollbar": "^4.0", "ruflin/elastica": "^7 || ^8", diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 436cc4cd9..0371c1617 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -1,111 +1,163 @@ parameters: ignoreErrors: - - message: "#^Property Monolog\\\\ErrorHandler\\:\\:\\$reservedMemory is never read, only written\\.$#" + message: '#^Property Monolog\\ErrorHandler\:\:\$reservedMemory is never read, only written\.$#' + identifier: property.onlyWritten count: 1 path: src/Monolog/ErrorHandler.php - - message: "#^Return type \\(array\\\\|bool\\|float\\|int\\|object\\|string\\|null\\) of method Monolog\\\\Formatter\\\\JsonFormatter\\:\\:normalize\\(\\) should be covariant with return type \\(array\\\\|bool\\|float\\|int\\|string\\|null\\) of method Monolog\\\\Formatter\\\\NormalizerFormatter\\:\\:normalize\\(\\)$#" + message: '#^Method Monolog\\Formatter\\JsonFormatter\:\:normalizeException\(\) return type has no value type specified in iterable type array\.$#' + identifier: missingType.iterableValue count: 1 path: src/Monolog/Formatter/JsonFormatter.php - - message: "#^Cannot access offset 'table' on array\\\\|bool\\|float\\|int\\|object\\|string\\.$#" + message: '#^PHPDoc tag @return with type array\\|int\|string\>\|int\|string\>\|string is not subtype of native type array\.$#' + identifier: return.phpDocType + count: 1 + path: src/Monolog/Formatter/JsonFormatter.php + + - + message: '#^Return type \(array\) of method Monolog\\Formatter\\JsonFormatter\:\:normalizeException\(\) should be covariant with return type \(array\\|int\|string\>\|int\|string\>\|string\) of method Monolog\\Formatter\\NormalizerFormatter\:\:normalizeException\(\)$#' + identifier: method.childReturnType + count: 1 + path: src/Monolog/Formatter/JsonFormatter.php + + - + message: '#^Return type \(array\\|bool\|float\|int\|object\|string\|null\>\|bool\|float\|int\|object\|string\|null\) of method Monolog\\Formatter\\JsonFormatter\:\:normalize\(\) should be covariant with return type \(array\\|bool\|float\|int\|string\|null\>\|bool\|float\|int\|string\|null\) of method Monolog\\Formatter\\NormalizerFormatter\:\:normalize\(\)$#' + identifier: method.childReturnType + count: 1 + path: src/Monolog/Formatter/JsonFormatter.php + + - + message: '#^Method Monolog\\Formatter\\NormalizerFormatter\:\:normalizeException\(\) should return array\\|int\|string\>\|int\|string\>\|string but returns array\\.$#' + identifier: return.type + count: 1 + path: src/Monolog/Formatter/NormalizerFormatter.php + + - + message: '#^Method Monolog\\Formatter\\NormalizerFormatter\:\:normalizeException\(\) should return array\\|int\|string\>\|int\|string\>\|string but returns array\\|string, array\\|int\|string\>\|int\|string\>\|int\|string\>\.$#' + identifier: return.type + count: 1 + path: src/Monolog/Formatter/NormalizerFormatter.php + + - + message: '#^Cannot access offset ''table'' on array\\|bool\|float\|int\|string\|null\>\|bool\|float\|int\|object\|string\.$#' + identifier: offsetAccess.nonOffsetAccessible count: 1 path: src/Monolog/Formatter/WildfireFormatter.php - - message: "#^Return type \\(array\\\\|bool\\|float\\|int\\|object\\|string\\|null\\) of method Monolog\\\\Formatter\\\\WildfireFormatter\\:\\:normalize\\(\\) should be covariant with return type \\(array\\\\|bool\\|float\\|int\\|string\\|null\\) of method Monolog\\\\Formatter\\\\NormalizerFormatter\\:\\:normalize\\(\\)$#" + message: '#^Return type \(array\\|bool\|float\|int\|string\|null\>\|bool\|float\|int\|object\|string\|null\) of method Monolog\\Formatter\\WildfireFormatter\:\:normalize\(\) should be covariant with return type \(array\\|bool\|float\|int\|string\|null\>\|bool\|float\|int\|string\|null\) of method Monolog\\Formatter\\NormalizerFormatter\:\:normalize\(\)$#' + identifier: method.childReturnType count: 1 path: src/Monolog/Formatter/WildfireFormatter.php - - message: "#^Access to constant VERSION on an unknown class Elasticsearch\\\\Client\\.$#" + message: '#^Access to constant VERSION on an unknown class Elasticsearch\\Client\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/ElasticsearchHandler.php - - message: "#^Call to method bulk\\(\\) on an unknown class Elasticsearch\\\\Client\\.$#" + message: '#^Call to method bulk\(\) on an unknown class Elasticsearch\\Client\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/ElasticsearchHandler.php - - message: "#^Method Monolog\\\\Handler\\\\ElasticsearchHandler\\:\\:createExceptionFromError\\(\\) should return Throwable but returns Elasticsearch\\\\Common\\\\Exceptions\\\\RuntimeException\\.$#" + message: '#^Method Monolog\\Handler\\ElasticsearchHandler\:\:createExceptionFromError\(\) should return Throwable but returns Elasticsearch\\Common\\Exceptions\\RuntimeException\.$#' + identifier: return.type count: 1 path: src/Monolog/Handler/ElasticsearchHandler.php - - message: "#^Method Monolog\\\\Handler\\\\ElasticsearchHandler\\:\\:createExceptionFromResponses\\(\\) should return Throwable but returns Elasticsearch\\\\Common\\\\Exceptions\\\\RuntimeException\\.$#" + message: '#^Method Monolog\\Handler\\ElasticsearchHandler\:\:createExceptionFromResponses\(\) should return Throwable but returns Elasticsearch\\Common\\Exceptions\\RuntimeException\.$#' + identifier: return.type count: 1 path: src/Monolog/Handler/ElasticsearchHandler.php - - message: "#^Parameter \\$client of method Monolog\\\\Handler\\\\ElasticsearchHandler\\:\\:__construct\\(\\) has invalid type Elasticsearch\\\\Client\\.$#" + message: '#^Parameter \$client of method Monolog\\Handler\\ElasticsearchHandler\:\:__construct\(\) has invalid type Elasticsearch\\Client\.$#' + identifier: class.notFound count: 2 path: src/Monolog/Handler/ElasticsearchHandler.php - - message: "#^Property Monolog\\\\Handler\\\\ElasticsearchHandler\\:\\:\\$client has unknown class Elasticsearch\\\\Client as its type\\.$#" + message: '#^Property Monolog\\Handler\\ElasticsearchHandler\:\:\$client has unknown class Elasticsearch\\Client as its type\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/ElasticsearchHandler.php - - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" + message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' + identifier: ternary.shortNotAllowed count: 1 path: src/Monolog/Handler/FingersCrossedHandler.php - - message: "#^Call to method setBody\\(\\) on an unknown class Swift_Message\\.$#" + message: '#^Call to method setBody\(\) on an unknown class Swift_Message\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/MandrillHandler.php - - message: "#^Call to method setDate\\(\\) on an unknown class Swift_Message\\.$#" + message: '#^Call to method setDate\(\) on an unknown class Swift_Message\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/MandrillHandler.php - - message: "#^Class Swift_Message not found\\.$#" + message: '#^Class Swift_Message not found\.$#' + identifier: class.notFound count: 2 path: src/Monolog/Handler/MandrillHandler.php - - message: "#^Cloning object of an unknown class Swift_Message\\.$#" + message: '#^Cloning object of an unknown class Swift_Message\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/MandrillHandler.php - - message: "#^Parameter \\$message of method Monolog\\\\Handler\\\\MandrillHandler\\:\\:__construct\\(\\) has invalid type Swift_Message\\.$#" + message: '#^Parameter \$message of method Monolog\\Handler\\MandrillHandler\:\:__construct\(\) has invalid type Swift_Message\.$#' + identifier: class.notFound count: 3 path: src/Monolog/Handler/MandrillHandler.php - - message: "#^Property Monolog\\\\Handler\\\\MandrillHandler\\:\\:\\$message has unknown class Swift_Message as its type\\.$#" + message: '#^Property Monolog\\Handler\\MandrillHandler\:\:\$message has unknown class Swift_Message as its type\.$#' + identifier: class.notFound count: 1 path: src/Monolog/Handler/MandrillHandler.php - - message: "#^Variable property access on \\$this\\(Monolog\\\\LogRecord\\)\\.$#" + message: '#^Variable property access on \$this\(Monolog\\LogRecord\)\.$#' + identifier: property.dynamicName count: 4 path: src/Monolog/LogRecord.php - - message: "#^Cannot assign offset Fiber to WeakMap\\, int\\>\\.$#" + message: '#^Cannot assign offset Fiber to WeakMap\, int\>\.$#' + identifier: offsetAssign.dimType count: 1 path: src/Monolog/Logger.php - - message: "#^Parameter \\#1 \\$level \\('alert'\\|'critical'\\|'debug'\\|'emergency'\\|'error'\\|'info'\\|'notice'\\|'warning'\\|Monolog\\\\Level\\) of method Monolog\\\\Logger\\:\\:log\\(\\) should be contravariant with parameter \\$level \\(mixed\\) of method Psr\\\\Log\\\\LoggerInterface\\:\\:log\\(\\)$#" + message: '#^Parameter \#1 \$level \(''alert''\|''critical''\|''debug''\|''emergency''\|''error''\|''info''\|''notice''\|''warning''\|Monolog\\Level\) of method Monolog\\Logger\:\:log\(\) should be contravariant with parameter \$level \(mixed\) of method Psr\\Log\\LoggerInterface\:\:log\(\)$#' + identifier: method.childParameterType count: 1 path: src/Monolog/Logger.php - - message: "#^Variable property access on \\$this\\(Monolog\\\\Logger\\)\\.$#" + message: '#^Variable property access on \$this\(Monolog\\Logger\)\.$#' + identifier: property.dynamicName count: 1 path: src/Monolog/Logger.php - - message: "#^Parameter \\#1 \\$length of function random_bytes expects int\\<1, max\\>, int given\\.$#" + message: '#^Parameter \#1 \$length of function random_bytes expects int\<1, max\>, int given\.$#' + identifier: argument.type count: 1 path: src/Monolog/Processor/UidProcessor.php diff --git a/phpstan.neon.dist b/phpstan.neon.dist index b84494370..8de22cf5a 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -15,13 +15,9 @@ parameters: - '#zend_monitor_|ZEND_MONITOR_#' - '#MongoDB\\(Client|Collection)#' - # Cannot resolve this cleanly as different normalizers return different types but it is safe - - message: '#Return type \(string\) of method Monolog\\Formatter\\LineFormatter::normalizeException\(\) should be compatible with return type \(array\) of method Monolog\\Formatter\\NormalizerFormatter::normalizeException\(\)#' - paths: - - src/Monolog/Formatter/LineFormatter.php - includes: - phpstan-baseline.neon - phpstan-ignore-by-php-version.neon.php + - phar://phpstan.phar/conf/bleedingEdge.neon - vendor/phpstan/phpstan-strict-rules/rules.neon - vendor/phpstan/phpstan-deprecation-rules/rules.neon diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 087cd6b90..0e806839b 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -3,6 +3,9 @@ xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="tests/bootstrap.php" colors="true" + displayDetailsOnTestsThatTriggerWarnings="true" + displayDetailsOnSkippedTests="true" + displayDetailsOnTestsThatTriggerNotices="true" beStrictAboutTestsThatDoNotTestAnything="false"> diff --git a/src/Monolog/Formatter/GelfMessageFormatter.php b/src/Monolog/Formatter/GelfMessageFormatter.php index dd6fefbcb..9b0861948 100644 --- a/src/Monolog/Formatter/GelfMessageFormatter.php +++ b/src/Monolog/Formatter/GelfMessageFormatter.php @@ -88,11 +88,11 @@ public function format(LogRecord $record): Message { $context = $extra = []; if (isset($record->context)) { - /** @var mixed[] $context */ + /** @var array|bool|float|int|string|null> $context */ $context = parent::normalize($record->context); } if (isset($record->extra)) { - /** @var mixed[] $extra */ + /** @var array|bool|float|int|string|null> $extra */ $extra = parent::normalize($record->extra); } diff --git a/src/Monolog/Formatter/JsonFormatter.php b/src/Monolog/Formatter/JsonFormatter.php index 238039f4e..f5a68a440 100644 --- a/src/Monolog/Formatter/JsonFormatter.php +++ b/src/Monolog/Formatter/JsonFormatter.php @@ -204,7 +204,7 @@ protected function normalize(mixed $data, int $depth = 0): mixed * Normalizes given exception with or without its own stack trace based on * `includeStacktraces` property. * - * @inheritDoc + * @return array>>|string */ protected function normalizeException(Throwable $e, int $depth = 0): array { diff --git a/src/Monolog/Formatter/LineFormatter.php b/src/Monolog/Formatter/LineFormatter.php index 06b8e4328..e563503f0 100644 --- a/src/Monolog/Formatter/LineFormatter.php +++ b/src/Monolog/Formatter/LineFormatter.php @@ -175,7 +175,7 @@ public function format(LogRecord $record): string if (null === $output) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); } } @@ -243,7 +243,7 @@ protected function replaceNewlines(string $str): string if (null === $str) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); } } @@ -309,6 +309,6 @@ private function stacktracesParser(\Throwable $e): string private function stacktracesParserCustom(string $trace): string { - return implode("\n", array_filter(array_map($this->stacktracesParser, explode("\n", $trace)))); + return implode("\n", array_filter(array_map($this->stacktracesParser, explode("\n", $trace)), fn ($line) => $line !== false && $line !== '')); } } diff --git a/src/Monolog/Formatter/MongoDBFormatter.php b/src/Monolog/Formatter/MongoDBFormatter.php index 2da3e0bec..129f04837 100644 --- a/src/Monolog/Formatter/MongoDBFormatter.php +++ b/src/Monolog/Formatter/MongoDBFormatter.php @@ -150,7 +150,7 @@ private function legacyGetMongoDbDateTime(\DateTimeInterface $value): UTCDateTim { $milliseconds = floor(((float) $value->format('U.u')) * 1000); - $milliseconds = (PHP_INT_SIZE == 8) //64-bit OS? + $milliseconds = (PHP_INT_SIZE === 8) //64-bit OS? ? (int) $milliseconds : (string) $milliseconds; diff --git a/src/Monolog/Formatter/NormalizerFormatter.php b/src/Monolog/Formatter/NormalizerFormatter.php index 36d77c96c..261967f1a 100644 --- a/src/Monolog/Formatter/NormalizerFormatter.php +++ b/src/Monolog/Formatter/NormalizerFormatter.php @@ -163,7 +163,7 @@ public function setBasePath(string $path = ''): self */ protected function normalizeRecord(LogRecord $record): array { - /** @var array $normalized */ + /** @var array $normalized */ $normalized = $this->normalize($record->toArray()); return $normalized; @@ -248,7 +248,7 @@ protected function normalize(mixed $data, int $depth = 0): mixed } /** - * @return mixed[] + * @return array>>|string */ protected function normalizeException(Throwable $e, int $depth = 0) { diff --git a/src/Monolog/Handler/BrowserConsoleHandler.php b/src/Monolog/Handler/BrowserConsoleHandler.php index 0d75cb313..788d7d068 100644 --- a/src/Monolog/Handler/BrowserConsoleHandler.php +++ b/src/Monolog/Handler/BrowserConsoleHandler.php @@ -243,7 +243,7 @@ private static function handleCustomStyles(string $style, string $string): strin if (null === $style) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Failed to run preg_replace_callback: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + throw new \RuntimeException('Failed to run preg_replace_callback: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); } return $style; @@ -256,7 +256,7 @@ private static function handleCustomStyles(string $style, string $string): strin private static function dump(string $title, array $dict): array { $script = []; - $dict = array_filter($dict); + $dict = array_filter($dict, fn ($value) => $value !== null); if (\count($dict) === 0) { return $script; } diff --git a/src/Monolog/Handler/ErrorLogHandler.php b/src/Monolog/Handler/ErrorLogHandler.php index aaad9d48c..a38c3f5e0 100644 --- a/src/Monolog/Handler/ErrorLogHandler.php +++ b/src/Monolog/Handler/ErrorLogHandler.php @@ -27,11 +27,12 @@ class ErrorLogHandler extends AbstractProcessingHandler public const OPERATING_SYSTEM = 0; public const SAPI = 4; + /** @var 0|1|3|4 */ protected int $messageType; protected bool $expandNewlines; /** - * @param int $messageType Says where the error should go. + * @param 0|1|3|4 $messageType Says where the error should go. * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries * * @throws \InvalidArgumentException If an unsupported message type is set @@ -84,7 +85,7 @@ protected function write(LogRecord $record): void if ($lines === false) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Failed to preg_split formatted string: ' . $pcreErrorCode . ' / '. Utils::pcreLastErrorMessage($pcreErrorCode)); + throw new \RuntimeException('Failed to preg_split formatted string: ' . $pcreErrorCode . ' / '. preg_last_error_msg()); } foreach ($lines as $line) { error_log($line, $this->messageType); diff --git a/src/Monolog/Handler/MandrillHandler.php b/src/Monolog/Handler/MandrillHandler.php index 64e16c9de..477ac345a 100644 --- a/src/Monolog/Handler/MandrillHandler.php +++ b/src/Monolog/Handler/MandrillHandler.php @@ -70,8 +70,8 @@ protected function send(string $content, array $records): void $ch = curl_init(); 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_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'key' => $this->apiKey, 'raw_message' => (string) $message, diff --git a/src/Monolog/Handler/OverflowHandler.php b/src/Monolog/Handler/OverflowHandler.php index b213a98dc..adc0eb1f0 100644 --- a/src/Monolog/Handler/OverflowHandler.php +++ b/src/Monolog/Handler/OverflowHandler.php @@ -97,7 +97,7 @@ public function handle(LogRecord $record): bool return false === $this->bubble; } - if ($this->thresholdMap[$level] == 0) { + if ($this->thresholdMap[$level] === 0) { // This current message is breaking the threshold. Flush the buffer and continue handling the current record foreach ($this->buffer[$level] ?? [] as $buffered) { $this->handler->handle($buffered); diff --git a/src/Monolog/Handler/SendGridHandler.php b/src/Monolog/Handler/SendGridHandler.php index 0a6fe406b..9c3b8e6af 100644 --- a/src/Monolog/Handler/SendGridHandler.php +++ b/src/Monolog/Handler/SendGridHandler.php @@ -92,8 +92,8 @@ protected function send(string $content, array $records): void $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.sendgrid.com/api/mail.send.json'); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($message)); Curl\Util::execute($ch, 2); } diff --git a/src/Monolog/Handler/Slack/SlackRecord.php b/src/Monolog/Handler/Slack/SlackRecord.php index a10d6d6c8..0e46c2d2f 100644 --- a/src/Monolog/Handler/Slack/SlackRecord.php +++ b/src/Monolog/Handler/Slack/SlackRecord.php @@ -206,7 +206,7 @@ public function getAttachmentColor(Level $level): string */ public function stringify(array $fields): string { - /** @var array $normalized */ + /** @var array|bool|float|int|string|null> $normalized */ $normalized = $this->normalizerFormatter->normalizeValue($fields); $hasSecondDimension = \count(array_filter($normalized, 'is_array')) > 0; @@ -341,7 +341,7 @@ private function generateAttachmentField(string $title, $value): array */ private function generateAttachmentFields(array $data): array { - /** @var array $normalized */ + /** @var array|string> $normalized */ $normalized = $this->normalizerFormatter->normalizeValue($data); $fields = []; diff --git a/src/Monolog/Handler/SocketHandler.php b/src/Monolog/Handler/SocketHandler.php index 69a036f52..36d46bf9d 100644 --- a/src/Monolog/Handler/SocketHandler.php +++ b/src/Monolog/Handler/SocketHandler.php @@ -386,7 +386,7 @@ private function writeToSocket(string $data): void $sent = 0; $this->lastSentBytes = $sent; while ($this->isConnected() && $sent < $length) { - if (0 == $sent) { + if (0 === $sent) { $chunk = $this->fwrite($data); } else { $chunk = $this->fwrite(substr($data, $sent)); @@ -412,7 +412,7 @@ private function writeToSocket(string $data): void private function writingIsTimedOut(int $sent): bool { // convert to ms - if (0.0 == $this->writingTimeout) { + if (0.0 === $this->writingTimeout) { return false; } diff --git a/src/Monolog/Handler/SyslogUdpHandler.php b/src/Monolog/Handler/SyslogUdpHandler.php index e8db4cdeb..b5e467417 100644 --- a/src/Monolog/Handler/SyslogUdpHandler.php +++ b/src/Monolog/Handler/SyslogUdpHandler.php @@ -96,7 +96,7 @@ private function splitMessageIntoLines($message): array if (false === $lines) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); + throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); } return $lines; diff --git a/src/Monolog/Handler/TestHandler.php b/src/Monolog/Handler/TestHandler.php index d410dd9ae..eb5fb445c 100644 --- a/src/Monolog/Handler/TestHandler.php +++ b/src/Monolog/Handler/TestHandler.php @@ -23,14 +23,14 @@ * * @author Jordi Boggiano * - * @method bool hasEmergency(string|array $recordAssertions) - * @method bool hasAlert(string|array $recordAssertions) - * @method bool hasCritical(string|array $recordAssertions) - * @method bool hasError(string|array $recordAssertions) - * @method bool hasWarning(string|array $recordAssertions) - * @method bool hasNotice(string|array $recordAssertions) - * @method bool hasInfo(string|array $recordAssertions) - * @method bool hasDebug(string|array $recordAssertions) + * @method bool hasEmergency(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasAlert(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasCritical(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasError(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasWarning(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasNotice(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasInfo(array{message: string, context?: mixed[]}|string $recordAssertions) + * @method bool hasDebug(array{message: string, context?: mixed[]}|string $recordAssertions) * * @method bool hasEmergencyRecords() * @method bool hasAlertRecords() diff --git a/src/Monolog/Logger.php b/src/Monolog/Logger.php index edc62f3a8..f57fe332e 100644 --- a/src/Monolog/Logger.php +++ b/src/Monolog/Logger.php @@ -166,7 +166,7 @@ class Logger implements LoggerInterface, ResettableInterface /** * @param string $name The logging channel, a simple descriptive name that is attached to all log records - * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc. + * @param list $handlers Optional stack of handlers, the first one in the array is called first, etc. * @param callable[] $processors Optional array of processors * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used * diff --git a/src/Monolog/Processor/MercurialProcessor.php b/src/Monolog/Processor/MercurialProcessor.php index a48a78544..3076a3d8c 100644 --- a/src/Monolog/Processor/MercurialProcessor.php +++ b/src/Monolog/Processor/MercurialProcessor.php @@ -62,13 +62,18 @@ private static function getMercurialInfo(): array } $result = explode(' ', trim((string) shell_exec('hg id -nb'))); - if (\count($result) >= 3) { return self::$cache = [ 'branch' => $result[1], 'revision' => $result[2], ]; } + if (\count($result) === 2) { + return self::$cache = [ + 'branch' => $result[1], + 'revision' => $result[0], + ]; + } return self::$cache = []; } diff --git a/src/Monolog/Test/TestCase.php b/src/Monolog/Test/TestCase.php index 29ec7c96e..a2ff3f7ad 100644 --- a/src/Monolog/Test/TestCase.php +++ b/src/Monolog/Test/TestCase.php @@ -17,6 +17,7 @@ use Monolog\DateTimeImmutable; use Monolog\Formatter\FormatterInterface; use Psr\Log\LogLevel; +use ReflectionProperty; /** * Lets you easily generate log records and a dummy formatter for testing purposes @@ -27,15 +28,6 @@ */ class TestCase extends \PHPUnit\Framework\TestCase { - public function tearDown(): void - { - parent::tearDown(); - - if (isset($this->handler)) { - unset($this->handler); - } - } - /** * @param array $context * @param array $extra diff --git a/src/Monolog/Utils.php b/src/Monolog/Utils.php index 75d484b64..153801553 100644 --- a/src/Monolog/Utils.php +++ b/src/Monolog/Utils.php @@ -140,25 +140,6 @@ public static function handleJsonError(int $code, $data, ?int $encodeFlags = nul return $json; } - /** - * @internal - */ - public static function pcreLastErrorMessage(int $code): string - { - if (PHP_VERSION_ID >= 80000) { - return preg_last_error_msg(); - } - - $constants = (get_defined_constants(true))['pcre']; - $constants = array_filter($constants, function ($key) { - return substr($key, -6) == '_ERROR'; - }, ARRAY_FILTER_USE_KEY); - - $constants = array_flip($constants); - - return $constants[$code] ?? 'UNDEFINED_ERROR'; - } - /** * Throws an exception according to a given code with a customized message * @@ -209,7 +190,7 @@ function (array $m): string { if (!\is_string($data)) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode)); + throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . preg_last_error_msg()); } $data = str_replace( ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'], diff --git a/tests/Monolog/ErrorHandlerTest.php b/tests/Monolog/ErrorHandlerTest.php index 930b58f92..b3435ee54 100644 --- a/tests/Monolog/ErrorHandlerTest.php +++ b/tests/Monolog/ErrorHandlerTest.php @@ -68,7 +68,6 @@ protected function getPrivatePropertyValue($instance, $property) { $ref = new \ReflectionClass(\get_class($instance)); $prop = $ref->getProperty($property); - $prop->setAccessible(true); return $prop->getValue($instance); } @@ -91,6 +90,7 @@ public function testFatalHandler( $this->assertEquals($expectedFatalLevel, $this->getPrivatePropertyValue($errHandler, 'fatalLevel')); } + #[WithoutErrorHandler] public function testHandleException() { $logger = new Logger('test', [$handler = new TestHandler]); @@ -106,12 +106,14 @@ public function testHandleException() $errHandler->registerExceptionHandler([], true); $prop = $this->getPrivatePropertyValue($errHandler, 'previousExceptionHandler'); $this->assertTrue(\is_callable($prop)); + + restore_exception_handler(); + restore_exception_handler(); } public function testCodeToString() { $method = new \ReflectionMethod(ErrorHandler::class, 'codeToString'); - $method->setAccessible(true); $this->assertEquals('E_ERROR', $method->invokeArgs(null, [E_ERROR])); $this->assertEquals('E_WARNING', $method->invokeArgs(null, [E_WARNING])); diff --git a/tests/Monolog/Formatter/MongoDBFormatterTest.php b/tests/Monolog/Formatter/MongoDBFormatterTest.php index c01e0260d..ebe46cbd9 100644 --- a/tests/Monolog/Formatter/MongoDBFormatterTest.php +++ b/tests/Monolog/Formatter/MongoDBFormatterTest.php @@ -44,11 +44,9 @@ public function testConstruct($traceDepth, $traceAsString, $expectedTraceDepth, $formatter = new MongoDBFormatter($traceDepth, $traceAsString); $reflTrace = new \ReflectionProperty($formatter, 'exceptionTraceAsString'); - $reflTrace->setAccessible(true); $this->assertEquals($expectedTraceAsString, $reflTrace->getValue($formatter)); $reflDepth = new \ReflectionProperty($formatter, 'maxNestingLevel'); - $reflDepth->setAccessible(true); $this->assertEquals($expectedTraceDepth, $reflDepth->getValue($formatter)); } diff --git a/tests/Monolog/Formatter/NormalizerFormatterTest.php b/tests/Monolog/Formatter/NormalizerFormatterTest.php index d6dc3c5cf..b98cfedee 100644 --- a/tests/Monolog/Formatter/NormalizerFormatterTest.php +++ b/tests/Monolog/Formatter/NormalizerFormatterTest.php @@ -220,7 +220,6 @@ public function testIgnoresRecursiveObjectReferences() $formatter = new NormalizerFormatter(); $reflMethod = new \ReflectionMethod($formatter, 'toJson'); - $reflMethod->setAccessible(true); $res = $reflMethod->invoke($formatter, [$foo, $bar], true); restore_error_handler(); @@ -255,7 +254,6 @@ public function testToJsonIgnoresInvalidTypes() $formatter = new NormalizerFormatter(); $reflMethod = new \ReflectionMethod($formatter, 'toJson'); - $reflMethod->setAccessible(true); $res = $reflMethod->invoke($formatter, [$resource], true); restore_error_handler(); @@ -299,7 +297,6 @@ public function testIgnoresInvalidEncoding() { $formatter = new NormalizerFormatter(); $reflMethod = new \ReflectionMethod($formatter, 'toJson'); - $reflMethod->setAccessible(true); // send an invalid unicode sequence as a object that can't be cleaned $record = new \stdClass; @@ -312,7 +309,6 @@ public function testConvertsInvalidEncodingAsLatin9() { $formatter = new NormalizerFormatter(); $reflMethod = new \ReflectionMethod($formatter, 'toJson'); - $reflMethod->setAccessible(true); $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]); diff --git a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php index a2e9451d7..86d233964 100644 --- a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php +++ b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php @@ -27,7 +27,6 @@ protected function setUp(): void protected function generateScript() { $reflMethod = new \ReflectionMethod('Monolog\Handler\BrowserConsoleHandler', 'generateScript'); - $reflMethod->setAccessible(true); return $reflMethod->invoke(null); } diff --git a/tests/Monolog/Handler/FleepHookHandlerTest.php b/tests/Monolog/Handler/FleepHookHandlerTest.php index 828282994..68cd6bed4 100644 --- a/tests/Monolog/Handler/FleepHookHandlerTest.php +++ b/tests/Monolog/Handler/FleepHookHandlerTest.php @@ -39,6 +39,13 @@ public function setUp(): void $this->handler = new FleepHookHandler(self::TOKEN); } + public function tearDown(): void + { + parent::tearDown(); + + unset($this->handler); + } + /** * @covers ::__construct */ diff --git a/tests/Monolog/Handler/FlowdockHandlerTest.php b/tests/Monolog/Handler/FlowdockHandlerTest.php index 3e03f1da5..90375ced4 100644 --- a/tests/Monolog/Handler/FlowdockHandlerTest.php +++ b/tests/Monolog/Handler/FlowdockHandlerTest.php @@ -40,6 +40,7 @@ public function tearDown(): void parent::tearDown(); unset($this->res); + unset($this->handler); } public function testWriteHeader() @@ -73,7 +74,6 @@ private function createHandler($token = 'myToken') ->getMock(); $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/HandlerWrapperTest.php b/tests/Monolog/Handler/HandlerWrapperTest.php index 166fcd0bf..5836aa88d 100644 --- a/tests/Monolog/Handler/HandlerWrapperTest.php +++ b/tests/Monolog/Handler/HandlerWrapperTest.php @@ -36,6 +36,7 @@ public function tearDown(): void parent::tearDown(); unset($this->wrapper); + unset($this->handler); } public static function trueFalseDataProvider(): array diff --git a/tests/Monolog/Handler/InsightOpsHandlerTest.php b/tests/Monolog/Handler/InsightOpsHandlerTest.php index 144181ef9..44ec55b30 100644 --- a/tests/Monolog/Handler/InsightOpsHandlerTest.php +++ b/tests/Monolog/Handler/InsightOpsHandlerTest.php @@ -33,6 +33,7 @@ public function tearDown(): void parent::tearDown(); unset($this->resource); + unset($this->handler); } public function testWriteContent() @@ -68,7 +69,6 @@ private function createHandler() ->getMock(); $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/LogEntriesHandlerTest.php b/tests/Monolog/Handler/LogEntriesHandlerTest.php index c078da3e1..f574e86bd 100644 --- a/tests/Monolog/Handler/LogEntriesHandlerTest.php +++ b/tests/Monolog/Handler/LogEntriesHandlerTest.php @@ -32,6 +32,7 @@ public function tearDown(): void parent::tearDown(); unset($this->res); + unset($this->handler); } public function testWriteContent() @@ -72,7 +73,6 @@ private function createHandler() ->getMock(); $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/LogmaticHandlerTest.php b/tests/Monolog/Handler/LogmaticHandlerTest.php index 4ac0c96d1..24ff9029a 100644 --- a/tests/Monolog/Handler/LogmaticHandlerTest.php +++ b/tests/Monolog/Handler/LogmaticHandlerTest.php @@ -32,6 +32,7 @@ public function tearDown(): void parent::tearDown(); unset($this->res); + unset($this->handler); } public function testWriteContent() @@ -72,7 +73,6 @@ private function createHandler() ->getMock(); $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/PHPConsoleHandlerTest.php b/tests/Monolog/Handler/PHPConsoleHandlerTest.php index f6b554636..184d5ac77 100644 --- a/tests/Monolog/Handler/PHPConsoleHandlerTest.php +++ b/tests/Monolog/Handler/PHPConsoleHandlerTest.php @@ -21,6 +21,7 @@ use PhpConsole\Dispatcher\Errors as ErrorDispatcher; use PhpConsole\Handler as VendorPhpConsoleHandler; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\WithoutErrorHandler; use PHPUnit\Framework\MockObject\MockObject; /** @@ -169,6 +170,7 @@ public function testDebugTags($tagsContextKeys = null) } } + #[WithoutErrorHandler] public function testError($classesPartialsTraceIgnore = null) { $code = E_USER_NOTICE; @@ -182,10 +184,12 @@ public function testError($classesPartialsTraceIgnore = null) $this->equalTo($line), $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore')) ); - $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false); + $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false, false); $errorHandler->registerErrorHandler([], false, E_USER_WARNING); $reflMethod = new \ReflectionMethod($errorHandler, 'handleError'); $reflMethod->invoke($errorHandler, $code, $message, $file, $line); + + restore_error_handler(); } public function testException() @@ -215,11 +219,6 @@ public function testOptionEnabled() $this->initLogger(['enabled' => false])->debug('test'); } - public function testOptionClassesPartialsTraceIgnore() - { - $this->testError(['Class', 'Namespace\\']); - } - public function testOptionDebugTagsKeysInContext() { $this->testDebugTags(['key1', 'key2']); @@ -232,6 +231,11 @@ public function testOptionUseOwnErrorsAndExceptionsHandler() })); $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () { })); + + restore_exception_handler(); + restore_error_handler(); + restore_exception_handler(); + restore_error_handler(); } public static function provideConnectorMethodsOptionsSets() diff --git a/tests/Monolog/Handler/ProcessHandlerTest.php b/tests/Monolog/Handler/ProcessHandlerTest.php index f0dfaa2c0..2145274b2 100644 --- a/tests/Monolog/Handler/ProcessHandlerTest.php +++ b/tests/Monolog/Handler/ProcessHandlerTest.php @@ -22,7 +22,7 @@ class ProcessHandlerTest extends TestCase * * @var string */ - const DUMMY_COMMAND = 'echo'; + const DUMMY_COMMAND = 'php -r "echo fgets(STDIN);"'; /** * @covers Monolog\Handler\ProcessHandler::__construct @@ -42,7 +42,6 @@ public function testWriteOpensProcessAndWritesToStdInOfProcess() $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder->onlyMethods(['writeProcessInput']); - // using echo as command, as it is most probably available $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]); $handler = $mockBuilder->getMock(); @@ -163,7 +162,6 @@ public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentExcep { $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder->onlyMethods(['readProcessErrors']); - // using echo as command, as it is most probably available $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]); $handler = $mockBuilder->getMock(); @@ -184,7 +182,6 @@ public function testCloseClosesProcess() { $class = new \ReflectionClass('Monolog\Handler\ProcessHandler'); $property = $class->getProperty('process'); - $property->setAccessible(true); $handler = new ProcessHandler(self::DUMMY_COMMAND); $handler->handle($this->getRecord(Level::Warning, '21 is only the half truth')); diff --git a/tests/Monolog/Handler/PushoverHandlerTest.php b/tests/Monolog/Handler/PushoverHandlerTest.php index 5010e8a19..b8d452a07 100644 --- a/tests/Monolog/Handler/PushoverHandlerTest.php +++ b/tests/Monolog/Handler/PushoverHandlerTest.php @@ -32,6 +32,7 @@ public function tearDown(): void parent::tearDown(); unset($this->res); + unset($this->handler); } public function testWriteHeader() @@ -131,7 +132,6 @@ private function createHandler($token = 'myToken', $user = 'myUser', $title = 'M ->getMock(); $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/SlackHandlerTest.php b/tests/Monolog/Handler/SlackHandlerTest.php index 8ef83beae..f89c00d89 100644 --- a/tests/Monolog/Handler/SlackHandlerTest.php +++ b/tests/Monolog/Handler/SlackHandlerTest.php @@ -42,6 +42,7 @@ public function tearDown(): void parent::tearDown(); unset($this->res); + unset($this->handler); } public function testWriteHeader() @@ -139,7 +140,6 @@ private function createHandler($token = 'myToken', $channel = 'channel1', $usern ->getMock(); $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); - $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/SocketHandlerTest.php b/tests/Monolog/Handler/SocketHandlerTest.php index ca6c358e4..5a7251647 100644 --- a/tests/Monolog/Handler/SocketHandlerTest.php +++ b/tests/Monolog/Handler/SocketHandlerTest.php @@ -32,6 +32,7 @@ public function tearDown(): void parent::tearDown(); unset($this->res); + unset($this->handler); } public function testInvalidHostname() diff --git a/tests/Monolog/Handler/StreamHandlerTest.php b/tests/Monolog/Handler/StreamHandlerTest.php index 378ed8c09..1d3a45bdd 100644 --- a/tests/Monolog/Handler/StreamHandlerTest.php +++ b/tests/Monolog/Handler/StreamHandlerTest.php @@ -263,7 +263,7 @@ public static function provideMemoryValues() #[DataProvider('provideMemoryValues')] public function testPreventOOMError($phpMemory, $expectedChunkSize): void { - $previousValue = ini_set('memory_limit', $phpMemory); + $previousValue = @ini_set('memory_limit', $phpMemory); if ($previousValue === false) { $this->markTestSkipped('We could not set a memory limit that would trigger the error.'); diff --git a/tests/Monolog/Handler/TelegramBotHandlerTest.php b/tests/Monolog/Handler/TelegramBotHandlerTest.php index e0c8e7f43..88dcdba30 100644 --- a/tests/Monolog/Handler/TelegramBotHandlerTest.php +++ b/tests/Monolog/Handler/TelegramBotHandlerTest.php @@ -23,6 +23,13 @@ class TelegramBotHandlerTest extends TestCase { private TelegramBotHandler&MockObject $handler; + public function tearDown(): void + { + parent::tearDown(); + + unset($this->handler); + } + public function testSendTelegramRequest(): void { $this->createHandler(); diff --git a/tests/Monolog/LoggerTest.php b/tests/Monolog/LoggerTest.php index 9f78ccb91..67a5534ff 100644 --- a/tests/Monolog/LoggerTest.php +++ b/tests/Monolog/LoggerTest.php @@ -743,7 +743,6 @@ public function testReset() $getProperty = function ($object, $property) { $reflectionProperty = new \ReflectionProperty(\get_class($object), $property); - $reflectionProperty->setAccessible(true); return $reflectionProperty->getValue($object); }; diff --git a/tests/Monolog/Processor/MercurialProcessorTest.php b/tests/Monolog/Processor/MercurialProcessorTest.php index 25d91848b..05abef9d5 100644 --- a/tests/Monolog/Processor/MercurialProcessorTest.php +++ b/tests/Monolog/Processor/MercurialProcessorTest.php @@ -15,6 +15,41 @@ class MercurialProcessorTest extends TestCase { + private string $oldCwd; + private string $testDir; + + protected function setUp(): void + { + parent::setUp(); + + $this->oldCwd = getcwd(); + $this->testDir = sys_get_temp_dir().'/monolog-processor-mercurial-test'; + + mkdir($this->testDir, recursive: true); + chdir($this->testDir); + } + + protected function tearDown(): void + { + parent::tearDown(); + + chdir($this->oldCwd); + + if (!file_exists($this->testDir)) { + return; + } + $items = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->testDir, \RecursiveDirectoryIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST + ); + + foreach ($items as $item) { + $item->isDir() ? rmdir((string) $item) : unlink((string) $item); + } + + rmdir($this->testDir); + } + /** * @covers Monolog\Processor\MercurialProcessor::__invoke */ @@ -31,12 +66,17 @@ public function testProcessor() return; } - `hg init`; + exec('hg init'); + exec('hg branch default'); + touch('test.txt'); + exec('hg add test.txt'); + exec('hg commit -u foo -m "initial commit"'); + $processor = new MercurialProcessor(); $record = $processor($this->getRecord()); $this->assertArrayHasKey('hg', $record->extra); - $this->assertTrue(!\is_array($record->extra['hg']['branch'])); - $this->assertTrue(!\is_array($record->extra['hg']['revision'])); + $this->assertSame('default', $record->extra['hg']['branch']); + $this->assertSame('0', $record->extra['hg']['revision']); } } diff --git a/tests/Monolog/UtilsTest.php b/tests/Monolog/UtilsTest.php index 1ebff1103..4ffee0cc8 100644 --- a/tests/Monolog/UtilsTest.php +++ b/tests/Monolog/UtilsTest.php @@ -77,7 +77,6 @@ public static function providesHandleJsonErrorFailure() public function testDetectAndCleanUtf8($in, $expect) { $reflMethod = new \ReflectionMethod(Utils::class, 'detectAndCleanUtf8'); - $reflMethod->setAccessible(true); $args = [&$in]; $reflMethod->invokeArgs(null, $args); $this->assertSame($expect, $in); @@ -102,35 +101,6 @@ public static function providesDetectAndCleanUtf8() ]; } - #[DataProvider('providesPcreLastErrorMessage')] - public function testPcreLastErrorMessage(int $code, string $msg) - { - if (PHP_VERSION_ID >= 80000) { - $this->assertSame('No error', Utils::pcreLastErrorMessage($code)); - - return; - } - - $this->assertEquals($msg, Utils::pcreLastErrorMessage($code)); - } - - /** - * @return array[] - */ - public static function providesPcreLastErrorMessage(): array - { - return [ - [0, 'PREG_NO_ERROR'], - [1, 'PREG_INTERNAL_ERROR'], - [2, 'PREG_BACKTRACK_LIMIT_ERROR'], - [3, 'PREG_RECURSION_LIMIT_ERROR'], - [4, 'PREG_BAD_UTF8_ERROR'], - [5, 'PREG_BAD_UTF8_OFFSET_ERROR'], - [6, 'PREG_JIT_STACKLIMIT_ERROR'], - [-1, 'UNDEFINED_ERROR'], - ]; - } - public static function provideIniValuesToConvertToBytes() { return [