From d613d537c53787bc689311a36590d74025a0ff83 Mon Sep 17 00:00:00 2001 From: Maxim Harder Date: Mon, 27 Feb 2023 13:32:26 +0100 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8=D0=B7?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BA=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [UPDATE] Оптимизация кода под PHP 8.2 [NEW] Минимально поддерживаемая версия DLE - 16.0 [UPDATE] Изменён список алгоритмов на hash_hmac_algos --- README.md | 58 +-- manifest.json | 2 +- upload/api/composer.json | 5 +- upload/api/composer.lock | 105 +++-- upload/api/includes/PDO.Iterator.class.php | 40 -- upload/api/includes/PDO.Log.class.php | 35 -- upload/api/includes/PDO.class.php | 368 ---------------- upload/api/includes/functions.php | 416 ++++++++++-------- upload/api/index.php | 13 +- upload/api/routes/admin_logs.php | 1 + upload/api/vendor/composer/autoload_files.php | 1 + upload/api/vendor/composer/autoload_psr4.php | 2 +- .../api/vendor/composer/autoload_static.php | 3 +- upload/api/vendor/composer/installed.json | 108 +++-- upload/api/vendor/composer/installed.php | 23 +- upload/api/vendor/composer/platform_check.php | 4 +- .../api/vendor/monolog/monolog/CHANGELOG.md | 86 ++++ upload/api/vendor/monolog/monolog/README.md | 14 +- .../api/vendor/monolog/monolog/composer.json | 28 +- .../Monolog/Attribute/AsMonologProcessor.php | 28 +- .../monolog/src/Monolog/DateTimeImmutable.php | 5 +- .../monolog/src/Monolog/ErrorHandler.php | 141 +++--- .../Monolog/Formatter/ChromePHPFormatter.php | 54 +-- .../Monolog/Formatter/ElasticaFormatter.php | 18 +- .../Formatter/ElasticsearchFormatter.php | 15 +- .../Monolog/Formatter/FlowdockFormatter.php | 34 +- .../Monolog/Formatter/FluentdFormatter.php | 24 +- .../Monolog/Formatter/FormatterInterface.php | 18 +- .../Formatter/GelfMessageFormatter.php | 109 ++--- .../Formatter/GoogleCloudLoggingFormatter.php | 14 +- .../src/Monolog/Formatter/HtmlFormatter.php | 55 +-- .../src/Monolog/Formatter/JsonFormatter.php | 65 ++- .../src/Monolog/Formatter/LineFormatter.php | 42 +- .../src/Monolog/Formatter/LogglyFormatter.php | 14 +- .../Monolog/Formatter/LogmaticFormatter.php | 28 +- .../Monolog/Formatter/LogstashFormatter.php | 51 +-- .../Monolog/Formatter/MongoDBFormatter.php | 20 +- .../Monolog/Formatter/NormalizerFormatter.php | 66 ++- .../src/Monolog/Formatter/ScalarFormatter.php | 18 +- .../Monolog/Formatter/WildfireFormatter.php | 88 ++-- .../src/Monolog/Handler/AbstractHandler.php | 50 +-- .../Handler/AbstractProcessingHandler.php | 27 +- .../Monolog/Handler/AbstractSyslogHandler.php | 73 ++- .../src/Monolog/Handler/AmqpHandler.php | 76 ++-- .../Monolog/Handler/BrowserConsoleHandler.php | 81 ++-- .../src/Monolog/Handler/BufferHandler.php | 48 +- .../src/Monolog/Handler/ChromePHPHandler.php | 54 ++- .../src/Monolog/Handler/CouchDBHandler.php | 38 +- .../src/Monolog/Handler/CubeHandler.php | 54 +-- .../monolog/src/Monolog/Handler/Curl/Util.php | 12 +- .../Monolog/Handler/DeduplicationHandler.php | 68 +-- .../Handler/DoctrineCouchDBHandler.php | 14 +- .../src/Monolog/Handler/DynamoDbHandler.php | 50 +-- .../src/Monolog/Handler/ElasticaHandler.php | 39 +- .../Monolog/Handler/ElasticsearchHandler.php | 50 ++- .../src/Monolog/Handler/ErrorLogHandler.php | 24 +- .../Monolog/Handler/FallbackGroupHandler.php | 15 +- .../src/Monolog/Handler/FilterHandler.php | 105 ++--- .../ActivationStrategyInterface.php | 8 +- .../ChannelLevelActivationStrategy.php | 42 +- .../ErrorLevelActivationStrategy.php | 20 +- .../Monolog/Handler/FingersCrossedHandler.php | 108 +++-- .../src/Monolog/Handler/FirePHPHandler.php | 24 +- .../src/Monolog/Handler/FleepHookHandler.php | 25 +- .../src/Monolog/Handler/FlowdockHandler.php | 28 +- .../Handler/FormattableHandlerInterface.php | 5 +- .../Handler/FormattableHandlerTrait.php | 11 +- .../src/Monolog/Handler/GelfHandler.php | 15 +- .../src/Monolog/Handler/GroupHandler.php | 30 +- .../monolog/src/Monolog/Handler/Handler.php | 4 +- .../src/Monolog/Handler/HandlerInterface.php | 27 +- .../src/Monolog/Handler/HandlerWrapper.php | 30 +- .../src/Monolog/Handler/IFTTTHandler.php | 21 +- .../src/Monolog/Handler/InsightOpsHandler.php | 22 +- .../src/Monolog/Handler/LogEntriesHandler.php | 22 +- .../src/Monolog/Handler/LogglyHandler.php | 49 +-- .../src/Monolog/Handler/LogmaticHandler.php | 46 +- .../src/Monolog/Handler/MailHandler.php | 28 +- .../src/Monolog/Handler/MandrillHandler.php | 18 +- .../src/Monolog/Handler/MongoDBHandler.php | 28 +- .../Monolog/Handler/NativeMailerHandler.php | 33 +- .../src/Monolog/Handler/NewRelicHandler.php | 91 ++-- .../src/Monolog/Handler/NoopHandler.php | 10 +- .../src/Monolog/Handler/NullHandler.php | 30 +- .../src/Monolog/Handler/OverflowHandler.php | 42 +- .../src/Monolog/Handler/PHPConsoleHandler.php | 142 +++--- .../src/Monolog/Handler/ProcessHandler.php | 27 +- .../Handler/ProcessableHandlerInterface.php | 7 +- .../Handler/ProcessableHandlerTrait.php | 21 +- .../src/Monolog/Handler/PsrHandler.php | 30 +- .../src/Monolog/Handler/PushoverHandler.php | 128 +++--- .../src/Monolog/Handler/RedisHandler.php | 51 +-- .../Monolog/Handler/RedisPubSubHandler.php | 32 +- .../src/Monolog/Handler/RollbarHandler.php | 74 ++-- .../Monolog/Handler/RotatingFileHandler.php | 48 +- .../src/Monolog/Handler/SamplingHandler.php | 55 +-- .../src/Monolog/Handler/SendGridHandler.php | 22 +- .../src/Monolog/Handler/Slack/SlackRecord.php | 140 +++--- .../src/Monolog/Handler/SlackHandler.php | 32 +- .../Monolog/Handler/SlackWebhookHandler.php | 25 +- .../src/Monolog/Handler/SocketHandler.php | 73 ++- .../src/Monolog/Handler/SqsHandler.php | 19 +- .../src/Monolog/Handler/StreamHandler.php | 53 +-- .../Monolog/Handler/SymfonyMailerHandler.php | 28 +- .../src/Monolog/Handler/SyslogHandler.php | 20 +- .../Monolog/Handler/SyslogUdp/UdpSocket.php | 31 +- .../src/Monolog/Handler/SyslogUdpHandler.php | 44 +- .../Monolog/Handler/TelegramBotHandler.php | 61 +-- .../src/Monolog/Handler/TestHandler.php | 114 ++--- .../Handler/WebRequestRecognizerTrait.php | 1 - .../Handler/WhatFailureGroupHandler.php | 23 +- .../Monolog/Handler/ZendMonitorHandler.php | 75 ++-- .../monolog/monolog/src/Monolog/LogRecord.php | 112 ++++- .../monolog/monolog/src/Monolog/Logger.php | 338 +++++++------- .../src/Monolog/Processor/GitProcessor.php | 28 +- .../Monolog/Processor/HostnameProcessor.php | 11 +- .../Processor/IntrospectionProcessor.php | 53 ++- .../Processor/MemoryPeakUsageProcessor.php | 8 +- .../src/Monolog/Processor/MemoryProcessor.php | 5 +- .../Processor/MemoryUsageProcessor.php | 8 +- .../Monolog/Processor/MercurialProcessor.php | 26 +- .../Monolog/Processor/ProcessIdProcessor.php | 8 +- .../Monolog/Processor/ProcessorInterface.php | 11 +- .../Processor/PsrLogMessageProcessor.php | 31 +- .../src/Monolog/Processor/TagProcessor.php | 10 +- .../src/Monolog/Processor/UidProcessor.php | 20 +- .../src/Monolog/Processor/WebProcessor.php | 27 +- .../monolog/monolog/src/Monolog/Registry.php | 11 +- .../src/Monolog/ResettableInterface.php | 5 +- .../monolog/src/Monolog/SignalHandler.php | 31 +- .../monolog/src/Monolog/Test/TestCase.php | 51 +-- .../monolog/monolog/src/Monolog/Utils.php | 56 +-- upload/api/vendor/psr/log/composer.json | 6 +- upload/engine/inc/dleapi.php | 170 +++---- upload/install.xml | 4 +- ...\270 \320\274\320\265\320\275\321\217.txt" | 124 ------ 136 files changed, 2865 insertions(+), 3579 deletions(-) delete mode 100644 upload/api/includes/PDO.Iterator.class.php delete mode 100644 upload/api/includes/PDO.Log.class.php delete mode 100644 upload/api/includes/PDO.class.php delete mode 100644 "\320\237\321\200\320\276\321\207\321\202\320\270 \320\274\320\265\320\275\321\217.txt" diff --git a/README.md b/README.md index 3895540..9d6aef4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![GitHub forks](https://img.shields.io/github/forks/Gokujo/dle_api.svg?style=flat-square)](https://github.com/Gokujo/dle_api/network) [![GitHub license](https://img.shields.io/github/license/Gokujo/dle_api.svg?style=flat-square)](https://github.com/Gokujo/dle_api/blob/master/LICENSE) -![DLE-13.x](https://img.shields.io/badge/DLE-13.x-green.svg?style=flat-square) +![DLE-16.x](https://img.shields.io/badge/DLE-16.x-green.svg?style=flat-square) ![MySQL-5.5.6](https://img.shields.io/badge/MySQL-5.5.6-red.svg?style=flat-square) ![Версия_релиза](https://img.shields.io/github/manifest-json/v/Gokujo/dle_api?filename=manifest.json&style=flat-square) @@ -10,16 +10,16 @@ # DLE API Модификация для админпанели и глобальные функции для моих разработок -Совместимость проверенна на DLE-версиях 13.х. Для корректной работы требуется минимальная версия MySQL 5.5.6 или MariaDB 10.0, поскольку используются Foreign Key, которые требуют наличие InnoDB. +Совместимость проверенна на DLE-версиях 16.х. Для корректной работы требуется минимальная версия MySQL 5.5.6 или MariaDB 10.0, поскольку используются Foreign Key, которые требуют наличие InnoDB. Для установки достаточно скачать [релиз](https://github.com/Gokujo/dle_api/releases/latest). Документация к API находится на сервере [POSTMAN](https://documenter.getpostman.com/view/7856564/2s93CLsZ6p). На данный момент она не полная и пополняется медленно, но верно. -Релизы выше только для версий DLE 13 и выше. +Релизы выше только для версий DLE 16 и выше. Чтобы пополнить описания к полям - делаем форк репозитория и редактируем файл в папке apidata **DLE-API.postman_collection.json**. Изменяем и делаем пуш риквест. -# DLE >= 13.x +# Инструкция Скачайте релиз. У вас три варианта для установки: 1. **При помощи bat-Скрипта. Для пользователей Windows** Для этого устанавливаем [7Zip](https://www.7-zip.org/download.html). @@ -34,44 +34,6 @@ Залейте папку **engine** в корень сайта и установите плагин через менеджер плагинов. - -# DLE < 13 -В теории, и на движках младше всё должно работать, поскольку в процессе не затрагиваются файлы движка. Но, это не точно, я не пробовал, не эксперементировал. На свой страх и риск. - -## Установка -Залить папки **api** и **engine** из папки **upload** в корень сайта. Затем выполнить запрос в базу данных: - -```SQL -CREATE TABLE {prefix}_api_keys ( - id int auto_increment - primary key, - api varchar(255) not null, - is_admin tinyint(1) default 0 not null, - creator int default 0 null, - created datetime default CURRENT_TIMESTAMP not null, - active tinyint(1) default 0 not null, - user_id int default 0 not null, - own_only tinyint(1) default 1 not null, - constraint {prefix}_api_keys_key_uindex - unique (api) -); - -create table {prefix}_api_scope ( - scope_id int auto_increment - primary key, - `table` varchar(255) null, - `read` tinyint(1) default 0 not null, - `write` tinyint(1) default 0 not null, - `delete` tinyint(1) default 0 not null, - key_id int default 0 not null, - constraint {prefix}_api_scope_{prefix}_api_keys_id_fk - foreign key (key_id) references {prefix}_api_keys (id) - on update cascade on delete cascade -); - -INSERT INTO {prefix}_admin_sections (name, title, descr, icon, allow_groups) VALUES ('dleapi', 'DLE-API', 'Неофициальное API для DLE. Раздел по созданию и управлению над ключами доступа к API.', '/engine/skins/images/icons/dleapi.png', 1); -``` - ## Обновление Заменить все файлы из папки **upload**, кроме **install.xml**. @@ -79,14 +41,4 @@ INSERT INTO {prefix}_admin_sections (name, title, descr, icon, allow_groups) VAL ## Удаление Удаляем **из корня** сайта папку **api**, a так-же из папки **engine/inc** файл **dleapi.php** и из **engine/skins/images** файл **dleapi.png**. -Выполняем запрос в базу данных: - - -```SQL -DELETE FROM {prefix}_admin_sections WHERE `name` = 'dleapi'; -DROP TABLE {prefix}_api_keys cascade, {prefix}_api_scope cascade; -DROP PROCEDURE IF EXISTS addFieldIfNotExists; -DROP FUNCTION IF EXISTS isFieldExisting; -``` - -**{prefix}** заменяем на свой префикс базы данных. +Удаляем плагин из менеджера плагинов diff --git a/manifest.json b/manifest.json index febc345..40ab704 100644 --- a/manifest.json +++ b/manifest.json @@ -1,4 +1,4 @@ { - "version": "0.2.2", + "version": "0.3.0", "name": "DLE API" } diff --git a/upload/api/composer.json b/upload/api/composer.json index 0824d43..c02d2e0 100644 --- a/upload/api/composer.json +++ b/upload/api/composer.json @@ -3,11 +3,12 @@ "ext-json": "*", "slim/slim": "3.*", "monolog/monolog": "*", - "ext-pdo": "*" + "ext-pdo": "*", + "lincanbin/php-pdo-mysql-class": "*" }, "config": { "platform": { - "php": "7.4" + "php": "8.1" } } } diff --git a/upload/api/composer.lock b/upload/api/composer.lock index da33eae..020e47b 100644 --- a/upload/api/composer.lock +++ b/upload/api/composer.lock @@ -4,46 +4,93 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "d2b34a12928563cf6ccdbde1e8316842", + "content-hash": "fe0a38e04772d434bbb79c6ea0e4631c", "packages": [ + { + "name": "lincanbin/php-pdo-mysql-class", + "version": "v2.2", + "source": { + "type": "git", + "url": "https://github.com/lincanbin/PHP-PDO-MySQL-Class.git", + "reference": "7517d30ffc514a3c54217717b97721ab394fa87a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lincanbin/PHP-PDO-MySQL-Class/zipball/7517d30ffc514a3c54217717b97721ab394fa87a", + "reference": "7517d30ffc514a3c54217717b97721ab394fa87a", + "shasum": "" + }, + "require": { + "ext-pdo": "*", + "ext-pdo_mysql": "*", + "php": ">=5.3.6" + }, + "type": "library", + "autoload": { + "files": [ + "src/PDO.class.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "lincanbin", + "email": "lincanbin@hotmail.com" + } + ], + "description": "A PHP MySQL PDO class similar to the Python MySQLdb, which supports iterator and parameter binding when using 'WHERE IN' statement.", + "keywords": [ + "database", + "iterator", + "mysql", + "pdo" + ], + "support": { + "issues": "https://github.com/lincanbin/PHP-PDO-MySQL-Class/issues", + "source": "https://github.com/lincanbin/PHP-PDO-MySQL-Class/tree/v2.2" + }, + "time": "2020-11-27T02:02:36+00:00" + }, { "name": "monolog/monolog", - "version": "2.9.1", + "version": "3.3.1", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "f259e2b15fb95494c83f52d3caad003bbf5ffaa1" + "reference": "9b5daeaffce5b926cac47923798bba91059e60e2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/f259e2b15fb95494c83f52d3caad003bbf5ffaa1", - "reference": "f259e2b15fb95494c83f52d3caad003bbf5ffaa1", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/9b5daeaffce5b926cac47923798bba91059e60e2", + "reference": "9b5daeaffce5b926cac47923798bba91059e60e2", "shasum": "" }, "require": { - "php": ">=7.2", - "psr/log": "^1.0.1 || ^2.0 || ^3.0" + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" }, "provide": { - "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + "psr/log-implementation": "3.0.0" }, "require-dev": { - "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "aws/aws-sdk-php": "^3.0", "doctrine/couchdb": "~1.0@dev", "elasticsearch/elasticsearch": "^7 || ^8", "ext-json": "*", "graylog2/gelf-php": "^1.4.2 || ^2@dev", - "guzzlehttp/guzzle": "^7.4", + "guzzlehttp/guzzle": "^7.4.5", "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpspec/prophecy": "^1.15", - "phpstan/phpstan": "^0.12.91", - "phpunit/phpunit": "^8.5.14", - "predis/predis": "^1.1 || ^2.0", - "rollbar/rollbar": "^1.3 || ^2 || ^3", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-strict-rules": "^1.4", + "phpunit/phpunit": "^9.5.26", + "predis/predis": "^1.1 || ^2", "ruflin/elastica": "^7", - "swiftmailer/swiftmailer": "^5.3|^6.0", "symfony/mailer": "^5.4 || ^6", "symfony/mime": "^5.4 || ^6" }, @@ -66,7 +113,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "2.x-dev" + "dev-main": "3.x-dev" } }, "autoload": { @@ -94,7 +141,7 @@ ], "support": { "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/2.9.1" + "source": "https://github.com/Seldaek/monolog/tree/3.3.1" }, "funding": [ { @@ -106,7 +153,7 @@ "type": "tidelift" } ], - "time": "2023-02-06T13:44:46+00:00" + "time": "2023-02-06T13:46:10+00:00" }, { "name": "nikic/fast-route", @@ -314,30 +361,30 @@ }, { "name": "psr/log", - "version": "1.1.4", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11" + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1.x-dev" + "dev-master": "3.x-dev" } }, "autoload": { "psr-4": { - "Psr\\Log\\": "Psr/Log/" + "Psr\\Log\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -358,9 +405,9 @@ "psr-3" ], "support": { - "source": "https://github.com/php-fig/log/tree/1.1.4" + "source": "https://github.com/php-fig/log/tree/3.0.0" }, - "time": "2021-05-03T11:20:27+00:00" + "time": "2021-07-14T16:46:02+00:00" }, { "name": "slim/slim", @@ -462,7 +509,7 @@ }, "platform-dev": [], "platform-overrides": { - "php": "7.4" + "php": "8.1" }, "plugin-api-version": "2.2.0" } diff --git a/upload/api/includes/PDO.Iterator.class.php b/upload/api/includes/PDO.Iterator.class.php deleted file mode 100644 index 8c40802..0000000 --- a/upload/api/includes/PDO.Iterator.class.php +++ /dev/null @@ -1,40 +0,0 @@ -position = 0; - $this->pdo = $pdo; - $this->fetchMode = $fetchMode; - } - - function rewind() { - $this->position = 0; - $this->pdo->execute(); - $this->nextResult = $this->pdo->fetch($this->fetchMode, PDO::FETCH_ORI_NEXT); - } - - function current() { - return $this->nextResult; - } - - function key() { - return $this->position; - } - - function next() { - ++$this->position; - $this->nextResult = $this->pdo->fetch($this->fetchMode, PDO::FETCH_ORI_NEXT); - } - - function valid() { - $invalid = $this->nextResult === false; - if ($invalid) { - $this->pdo->closeCursor(); - } - return !$invalid; - } -} \ No newline at end of file diff --git a/upload/api/includes/PDO.Log.class.php b/upload/api/includes/PDO.Log.class.php deleted file mode 100644 index 19cd0e7..0000000 --- a/upload/api/includes/PDO.Log.class.php +++ /dev/null @@ -1,35 +0,0 @@ -path = __DIR__ . $this->path; - } - - public function write($message, $fileSalt) - { - $date = new DateTime(); - $log = $this->path . $date->format('Y-m-d') . "-" . md5($date->format('Y-m-d') . $fileSalt) . ".txt"; - if (is_dir($this->path)) { - if (!file_exists($log)) { - $fh = fopen($log, 'a+') or die("Fatal Error !"); - $logcontent = "Time : " . $date->format('H:i:s') . "\r\n" . $message . "\r\n"; - fwrite($fh, $logcontent); - fclose($fh); - } else { - $this->edit($log, $date, $message); - } - } else { - if (mkdir($this->path, 0777) === true) { - $this->write($message, $fileSalt); - } - } - } - private function edit($log, DateTime $date, $message) - { - $logcontent = "Time : " . $date->format('H:i:s') . "\r\n" . $message . "\r\n\r\n"; - $logcontent = $logcontent . file_get_contents($log); - file_put_contents($log, $logcontent); - } -} \ No newline at end of file diff --git a/upload/api/includes/PDO.class.php b/upload/api/includes/PDO.class.php deleted file mode 100644 index ab97a32..0000000 --- a/upload/api/includes/PDO.class.php +++ /dev/null @@ -1,368 +0,0 @@ -logObject = new PDOLog(); - $this->Host = $Host; - $this->DBPort = $DBPort; - $this->DBName = $DBName; - $this->DBUser = $DBUser; - $this->DBPassword = $DBPassword; - $this->parameters = array(); - $this->Connect(); - } - - - private function Connect() - { - try { - $dsn = 'mysql:'; - $dsn .= 'host=' . $this->Host . ';'; - $dsn .= 'port=' . $this->DBPort . ';'; - if (!empty($this->DBName)) { - $dsn .= 'dbname=' . $this->DBName . ';'; - } - $dsn .= 'charset=utf8;'; - $this->pdo = new PDO($dsn, - $this->DBUser, - $this->DBPassword, - array( - //For PHP 5.3.6 or lower - PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", - PDO::ATTR_EMULATE_PREPARES => false, - - //长连接 - //PDO::ATTR_PERSISTENT => true, - - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, - PDO::MYSQL_ATTR_FOUND_ROWS => true - ) - ); - /* - //For PHP 5.3.6 or lower - $this->pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8'); - $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); - $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - //$this->pdo->setAttribute(PDO::ATTR_PERSISTENT, true);//长连接 - $this->pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); - */ - $this->connectionStatus = true; - - } - catch (PDOException $e) { - $this->ExceptionLog($e, '', 'Connect'); - } - } - - private function SetFailureFlag() - { - $this->pdo = null; - $this->connectionStatus = false; - } - - /** - * close pdo connection - */ - public function closeConnection() - { - $this->pdo = null; - } - - private function Init($query, $parameters = null, $driverOptions = array()) - { - if (!$this->connectionStatus) { - $this->Connect(); - } - try { - $this->parameters = $parameters; - $this->sQuery = $this->pdo->prepare($this->BuildParams($query, $this->parameters), $driverOptions); - - if (!empty($this->parameters)) { - if (array_key_exists(0, $parameters)) { - $parametersType = true; - array_unshift($this->parameters, ""); - unset($this->parameters[0]); - } else { - $parametersType = false; - } - foreach ($this->parameters as $column => $value) { - $this->sQuery->bindParam($parametersType ? intval($column) : ":" . $column, $this->parameters[$column]); //It would be query after loop end(before 'sQuery->execute()').It is wrong to use $value. - } - } - - if (!isset($driverOptions[PDO::ATTR_CURSOR])) { - $this->sQuery->execute(); - } - $this->querycount++; - } - catch (PDOException $e) { - $this->ExceptionLog($e, $this->BuildParams($query), 'Init', array('query' => $query, 'parameters' => $parameters)); - - } - - $this->parameters = array(); - } - - private function BuildParams($query, $params = null) - { - if (!empty($params)) { - $array_parameter_found = false; - foreach ($params as $parameter_key => $parameter) { - if (is_array($parameter)){ - $array_parameter_found = true; - $in = ""; - foreach ($parameter as $key => $value){ - $name_placeholder = $parameter_key."_".$key; - // concatenates params as named placeholders - $in .= ":".$name_placeholder.", "; - // adds each single parameter to $params - $params[$name_placeholder] = $value; - } - $in = rtrim($in, ", "); - $query = preg_replace("/:".$parameter_key."/", $in, $query); - // removes array form $params - unset($params[$parameter_key]); - } - } - - // updates $this->params if $params and $query have changed - if ($array_parameter_found) $this->parameters = $params; - } - return $query; - } - - /** - * @return bool - */ - public function beginTransaction() - { - return $this->pdo->beginTransaction(); - } - - /** - * @return bool - */ - public function commit() - { - return $this->pdo->commit(); - } - - /** - * @return bool - */ - public function rollBack() - { - return $this->pdo->rollBack(); - } - - /** - * @return bool - */ - public function inTransaction() - { - return $this->pdo->inTransaction(); - } - - /** - * execute a sql query, returns an result array in the select operation, and returns the number of rows affected in other operations - * @param string $query - * @param null $params - * @param int $fetchMode - * @return array|int|null - */ - public function query($query, $params = null, $fetchMode = PDO::FETCH_ASSOC) - { - $query = trim($query); - $rawStatement = explode(" ", $query); - $this->Init($query, $params); - $statement = strtolower($rawStatement[0]); - if ($statement === 'select' || $statement === 'show' || $statement === 'call') { - return $this->sQuery->fetchAll($fetchMode); - } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') { - return $this->sQuery->rowCount(); - } else { - return NULL; - } - } - - /** - * execute a sql query, returns an iterator in the select operation, and returns the number of rows affected in other operations - * @param string $query - * @param null $params - * @param int $fetchMode - * @return int|null|PDOIterator - */ - public function iterator($query, $params = null, $fetchMode = PDO::FETCH_ASSOC) - { - $query = trim($query); - $rawStatement = explode(" ", $query); - $this->Init($query, $params, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); - $statement = strtolower($rawStatement[0]); - if ($statement === 'select' || $statement === 'show' || $statement === 'call') { - return new PDOIterator($this->sQuery, $fetchMode); - } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') { - return $this->sQuery->rowCount(); - } else { - return NULL; - } - } - - /** - * @param $tableName - * @param null $params - * @return bool|string - */ - public function insert($tableName, $params = null) - { - $keys = array_keys($params); - $rowCount = $this->query( - 'INSERT INTO `' . $tableName . '` (`' . implode('`,`', $keys) . '`) - VALUES (:' . implode(',:', $keys) . ')', - $params - ); - if ($rowCount === 0) { - return false; - } - return $this->lastInsertId(); - } - - /** - * @return string - */ - public function lastInsertId() - { - return $this->pdo->lastInsertId(); - } - - - /** - * @param $query - * @param null $params - * @return array - */ - public function column($query, $params = null) - { - $this->Init($query, $params); - $resultColumn = $this->sQuery->fetchAll(PDO::FETCH_COLUMN); - $this->rowCount = $this->sQuery->rowCount(); - $this->columnCount = $this->sQuery->columnCount(); - $this->sQuery->closeCursor(); - return $resultColumn; - } - - /** - * @param $query - * @param null $params - * @param int $fetchmode - * @return mixed - */ - public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC) - { - $this->Init($query, $params); - $resultRow = $this->sQuery->fetch($fetchmode); - $this->rowCount = $this->sQuery->rowCount(); - $this->columnCount = $this->sQuery->columnCount(); - $this->sQuery->closeCursor(); - return $resultRow; - } - - /** - * @param $query - * @param null $params - * @return mixed - */ - public function single($query, $params = null) - { - $this->Init($query, $params); - return $this->sQuery->fetchColumn(); - } - - /** - * @param PDOException $e - * @param string $sql - * @param string $method - * @param array $parameters - */ - private function ExceptionLog(PDOException $e, $sql = "", $method = '', $parameters = array()) - { - $message = $e->getMessage(); - $exception = 'Unhandled Exception.
'; - $exception .= $message; - $exception .= "
You can find the error back in the log."; - - if (!empty($sql)) { - $message .= "\r\nRaw SQL : " . $sql; - } - $this->logObject->write($message, $this->DBName . md5($this->DBPassword)); - if ( - self::AUTO_RECONNECT - && $this->retryAttempt < self::RETRY_ATTEMPTS - && stripos($message, 'server has gone away') !== false - && !empty($method) - && !$this->inTransaction() - ) { - $this->SetFailureFlag(); - $this->retryAttempt ++; - $this->logObject->write('Retry ' . $this->retryAttempt . ' times', $this->DBName . md5($this->DBPassword)); - call_user_func_array(array($this, $method), $parameters); - } else { - if (($this->pdo === null || !$this->inTransaction()) && php_sapi_name() !== "cli") { - //Prevent search engines to crawl - header("HTTP/1.1 500 Internal Server Error"); - header("Status: 500 Internal Server Error"); - echo $exception; - exit(); - } else { - throw $e; - } - } - } -} diff --git a/upload/api/includes/functions.php b/upload/api/includes/functions.php index 3b1d032..66b99ef 100644 --- a/upload/api/includes/functions.php +++ b/upload/api/includes/functions.php @@ -1,224 +1,266 @@ ', '%'); - $secondSign = array('='); - $type = gettype(defType($value, $type)); - $outSign = '='; - $checkSign = NULL; +/** + * Проверяет входящее значение на тип и на знак сравнения и возвращает строкой в виде '%value%' + * + * @param $value + * @param $type + * @return string + */ +function getComparer($value, $type = null) : string { + $firstSign = array('!', '<', '>', '%'); + $secondSign = array('='); + $type = gettype(defType($value, $type)); + $outSign = '='; + $checkSign = NULL; - if (!in_array($type, ['integer', 'double', 'boolean']) && in_array($value[0], $firstSign, true)) { + if (!in_array($type, ['integer', 'double', 'boolean']) && in_array($value[0], $firstSign, true)) { $checkSign = $value[0]; - if (in_array($value[1], $secondSign, true)){ - $checkSign .= $value[1]; - $value = substr($value, 2); - } else { - $value = substr($value, 1); - } + if (in_array($value[1], $secondSign, true)) { + $checkSign .= $value[1]; + $value = substr($value, 2); + } else { + $value = substr($value, 1); } + } - if ($checkSign === '!') { - $outSign = '<>'; - } elseif (in_array($checkSign, array('<', '>', '<=', '>='))) { - $outSign = $checkSign; - } elseif ($checkSign === '%') { - $outSign = 'LIKE'; - $value = '%'. $value .'%'; - } + if ($checkSign === '!') { + $outSign = '<>'; + } elseif (in_array($checkSign, array('<', '>', '<=', '>='))) { + $outSign = $checkSign; + } elseif ($checkSign === '%') { + $outSign = 'LIKE'; + $value = '%' . $value . '%'; + } - $value = defType($value, $type); + $value = defType($value, $type); - return " {$outSign} {$value}"; - } + return " {$outSign} {$value}"; +} - function checkAPI ($key, $name) { - global $connect, $DLEprefix, $USERprefix; +/** + * Проверяет ключ API на действительность в базе данных + * + * @param $key + * @param $name + * @return array|false[] + */ +function checkAPI($key, $name) : array { + global $connect, $DLEprefix, $USERprefix; - $antwort = array( - 'admin' => false, - 'read' => false, - 'view' => false, - 'delete' => false, - ); + $antwort = array( + 'admin' => false, + 'read' => false, + 'view' => false, + 'delete' => false, + ); - try { - if (!empty($key) && !empty($name)) { - $keyCheck = $connect->query( "SELECT k.id, k.api, k.is_admin, k.active, u.user_id, k.own_only, u.name FROM {$DLEprefix}_api_keys k, {$USERprefix}_users u WHERE u.user_id = k.user_id and api = :key", array( 'key' => $key) ); - - if(!empty($keyCheck)) { - if($keyCheck[0]['is_admin'] && $keyCheck[0]['active'] === 1) { - $antwort = array( - 'admin' => true, - 'read' => true, - 'view' => true, - 'delete' => true, - 'own' => [ - 'access' => true, - 'user_id' => $keyCheck[0]['user_id'], - 'user_name' => $keyCheck[0]['name'] - ], - ); - } else { - - $tablesCheck = $connect->query( "SELECT * FROM {$DLEprefix}_api_scope - WHERE table = :name and key_id = :api", array( 'name' => $name, 'api' => $keyCheck[0]['api']) ); - - if ( count( $tablesCheck ) > 0 ) { - if ( $keyCheck[0]['active'] === 1 ) { - if ( $keyCheck[0]['is_admin'] === 1 ) $antwort['admin'] = true; - if ( $tablesCheck[0]['read'] === 1 ) $antwort['read'] = true; - if ( $tablesCheck[0]['view'] === 1 ) $antwort['view'] = true; - if ( $tablesCheck[0]['delete'] === 1 ) $antwort['delete'] = true; - if ( $keyCheck[0]['own_only'] === 1 ) $antwort['own']['access'] = true; - $antwort['own']['user_id'] = $keyCheck[0]['user_id']; - $antwort['own']['user_name'] = $keyCheck[0]['name']; - } - else $antwort['error'] = 'API-ключ не активен!'; - } - else $antwort['error'] = 'API-ключ не действителен!'; - } - } - else $antwort['error'] = 'API-ключ не действителен!'; - } else { - if (!isset($key)) $antwort['error'] = 'API-ключ не может быть пустым!'; - if (!isset($name)) $antwort['error'] = 'Название базы данных не может быть пустым!'; - } + try { + if (!empty($key) && !empty($name)) { + $keyCheck = $connect->query("SELECT k.id, k.api, k.is_admin, k.active, u.user_id, k.own_only, u.name FROM {$DLEprefix}_api_keys k, {$USERprefix}_users u WHERE u.user_id = k.user_id and api = :key", array('key' => $key)); - return $antwort; + if (!empty($keyCheck)) { + if ($keyCheck[0]['is_admin'] && $keyCheck[0]['active'] === 1) { + $antwort = array( + 'admin' => true, + 'read' => true, + 'view' => true, + 'delete' => true, + 'own' => [ + 'access' => true, + 'user_id' => $keyCheck[0]['user_id'], + 'user_name' => $keyCheck[0]['name'] + ], + ); + } else { - } catch (Exception $e) { - throw new Error($e->getMessage()); + $tablesCheck = $connect->query("SELECT * FROM {$DLEprefix}_api_scope + WHERE table = :name and key_id = :api", array('name' => $name, + 'api' => $keyCheck[0]['api'] + )); + + if (count($tablesCheck) > 0) { + if ($keyCheck[0]['active'] === 1) { + if ($keyCheck[0]['is_admin'] === 1) $antwort['admin'] = true; + if ($tablesCheck[0]['read'] === 1) $antwort['read'] = true; + if ($tablesCheck[0]['view'] === 1) $antwort['view'] = true; + if ($tablesCheck[0]['delete'] === 1) $antwort['delete'] = true; + if ($keyCheck[0]['own_only'] === 1) $antwort['own']['access'] = true; + $antwort['own']['user_id'] = $keyCheck[0]['user_id']; + $antwort['own']['user_name'] = $keyCheck[0]['name']; + } else $antwort['error'] = 'API-ключ не активен!'; + } else $antwort['error'] = 'API-ключ не действителен!'; + } + } else $antwort['error'] = 'API-ключ не действителен!'; + } else { + if (!isset($key)) $antwort['error'] = 'API-ключ не может быть пустым!'; + if (!isset($name)) $antwort['error'] = 'Название базы данных не может быть пустым!'; } + + return $antwort; + + } catch (Exception $e) { + throw new Error($e->getMessage()); } +} - function defType($value, $type = null) { - $output = null; +/** + * Возвращает значение в верной типизации + * + * @param $value + * @param $type + * @return bool|float|int|string + */ +function defType($value, $type = null) : float|bool|int|string { - if ($type === 'integer') $output = (int)$value; - elseif ($type === 'boolean') $output = (bool)$value; - elseif ($type === 'double') $output = (float)$value; - else $output = "'{$value}'"; + if ($type === 'integer') $output = (int) $value; + elseif ($type === 'boolean') $output = (bool) $value; + elseif ($type === 'double') $output = (float) $value; + else $output = "'{$value}'"; - return $output; - } + return $output; +} - function checkLength($text, $max) { - return (strlen($text) > $max && $max !== 0) ? substr($text, 0, $max) : $text; - } +/** + * Проверяет текст на максимальную длину и возвращает его + * + * @param $text + * @param $max + * @return string + */ +function checkLength($text, $max) : string { + return (strlen($text) > $max && $max !== 0) ? substr($text, 0, $max) : $text; +} - class CacheSystem { - private $app, $data, $module, $id, $cachePath; - - /** - * CacheSystem constructor. - * - * @param $module // Название таблицы - * @param string $id // Идентификационный набор символов - * @param string $data // Передаваемые и сохраняемые данные - * @param string $app // Тип кеша - * @param string $path // Путь кеша - */ - public function __construct ($module, $id = '', $data = '', $app = 'api', $path = ENGINE_DIR . '/cache') { - $this->data = $data; - $this->app = $app; - $this->module = $module; - $this->id = $id; - if (empty($this->id)) $this->id = "{$app}_{$module}"; - $this->setCachePath($path); - } +/** + * Система кеширования запросов + */ +class CacheSystem { + private string $cachePath; + private string $module; + private string $id; + private string $data; + private string $app; - /** - * @param string $cachePath - */ - public function setCachePath ($cachePath) { - if (!mkdir($cachePath) && !is_dir($cachePath)) { - throw new \RuntimeException(sprintf('Directory "%s" was not created', $cachePath)); - } - $this->cachePath = $cachePath; + /** + * CacheSystem constructor. + * + * @param $module // Название таблицы + * @param string $id // Идентификационный набор символов + * @param mixed $data // Передаваемые и сохраняемые данные + * @param string $app // Тип кеша + * @param string $path // Путь кеша + */ + public function __construct(string $module, string $id = '', mixed $data = '', string $app = 'api', string $path = ENGINE_DIR . '/cache') { + $this->data = $data; + $this->app = $app; + $this->module = $module; + $this->id = $id; + if (empty($this->id)) $this->id = "{$app}_{$module}"; + $this->setCachePath($path); + } + + /** + * @param string $cachePath + */ + public function setCachePath(string $cachePath) : void { + if (!mkdir($cachePath) && !is_dir($cachePath)) { + throw new \RuntimeException(sprintf('Directory "%s" was not created', $cachePath)); } + $this->cachePath = $cachePath; + } - /** - * @return string - */ - public function create() { - $file_name = "{$this->app}_{$this->module}_" . md5($this->id) .'.json'; - file_put_contents($this->cachePath .'/'. $file_name, json_encode($this->data, JSON_UNESCAPED_UNICODE)); + /** + * @return bool|string + */ + public function create() : bool|string { + $file_name = "{$this->app}_{$this->module}_" . md5($this->id) . '.json'; + file_put_contents($this->cachePath . '/' . $file_name, json_encode($this->data, JSON_UNESCAPED_UNICODE)); - return $this->get(); - } + return $this->get(); + } - /** - * @return bool|false|string - */ - public function get() { - $file_name = "{$this->app}_{$this->module}_" . md5($this->id) .'.json'; - if (file_exists($this->cachePath .'/'. $file_name)) { - $return_data = json_decode(file_get_contents($this->cachePath.'/'.$file_name), true); - foreach ($return_data as $id => $data) { - foreach ($data as $key => $value) - $return_data[$id][$key] = $this->secureData($key, $value); - } - return json_encode($return_data); + /** + * Возвращает сохранённый в кеше запрос + * + * @return string + */ + public function get() : string { + $file_name = "{$this->app}_{$this->module}_" . md5($this->id) . '.json'; + if (file_exists($this->cachePath . '/' . $file_name)) { + $return_data = json_decode(file_get_contents($this->cachePath . '/' . $file_name), true); + foreach ($return_data as $id => $data) { + foreach ($data as $key => $value) + $return_data[$id][$key] = $this->secureData($key, $value); } - - return false; + return ''; } - /** - * @param string $app - */ - public function clear($app = '') { - $pattern = (empty($app)) ? '*' : $this->app .'_'. $app . '_*'; - $pattern .= '.json'; - try { - foreach (glob($this->cachePath .'/'.$pattern) as $filename) { - unlink($filename); - } - } catch (Exception $e) { - throw new Error($e->getMessage()); + return json_encode([], JSON_UNESCAPED_UNICODE); + } + + /** + * Очищает файлы кеша + * + * @param string $app + */ + public function clear(string $app = '') : void { + $pattern = (empty($app)) ? '*' : $this->app . '_' . $app . '_*'; + $pattern .= '.json'; + try { + foreach (glob($this->cachePath . '/' . $pattern) as $filename) { + unlink($filename); } + } catch (Exception $e) { + throw new Error($e->getMessage()); } + } - /** - * @param mixed $data - */ - public function setData ($data) { - $this->data = $data; - } + /** + * @param mixed $data + */ + public function setData(mixed $data) : void { + $this->data = $data; + } - /** - * @param $data - * @param $value - * - * @return mixed|string - */ - private function secureData($data, $value) { - global $dleapi; - $secure_arr = ['password', 'hash', 'ip', 'logged_ip']; - - if ($dleapi['secure']) { - if (in_array($data, $secure_arr)) { - if ($data == 'password') $value = 'Тут должен быть пароль'; - if ($data == 'hash') $value = 'Тут должен быть хэш'; - if (in_array($data, ['ip', 'logged_ip'])) $value = '127.0.0.1'; - } - } - return $value; + /** + * Засекречивает данные при выводе информации + * + * @param $data + * @param $value + * + * @return mixed|string + */ + private function secureData($data, $value) : mixed { + global $dleapi; + $secure_arr = ['password', 'hash', 'ip', 'logged_ip']; + if ($dleapi['secure']) { + if (in_array($data, $secure_arr)) { + if ($data == 'password') $value = 'Тут должен быть пароль'; + if ($data == 'hash') $value = 'Тут должен быть хэш'; + if (in_array($data, ['ip', 'logged_ip'])) $value = '127.0.0.1'; + } } + return $value; + } +} diff --git a/upload/api/index.php b/upload/api/index.php index 3d5e0c4..eec100e 100644 --- a/upload/api/index.php +++ b/upload/api/index.php @@ -18,14 +18,13 @@ @ini_set('html_errors', false); //Даём понять DLE, что приложение не чужое и может использовать файлы движка -define('DATALIFEENGINE', true); +const DATALIFEENGINE = true; define('ROOT_DIR', dirname(__FILE__, 2)); -define('API_DIR', __DIR__); -define('ENGINE_DIR', ROOT_DIR.'/engine'); +const API_DIR = __DIR__; +const ENGINE_DIR = ROOT_DIR . '/engine'; //Подключаем функционал API и самой DLE require_once ENGINE_DIR.'/classes/plugins.class.php'; - include_once DLEPlugins::Check(API_DIR.'/includes/functions.php'); $config = [ @@ -34,13 +33,15 @@ 'debug' => true, 'logger' => [ 'name' => 'dle-api', - 'level' => Monolog\Logger::DEBUG, + 'level' => E_WARNING, 'path' => API_DIR.'/logs/app.log', ], ], ]; + + // Подключаем файл-роутер и запускаем главную функцию include_once DLEPlugins::Check(API_DIR.'/routes/_router.php'); -?> + diff --git a/upload/api/routes/admin_logs.php b/upload/api/routes/admin_logs.php index e23f0dc..708a63c 100644 --- a/upload/api/routes/admin_logs.php +++ b/upload/api/routes/admin_logs.php @@ -7,6 +7,7 @@ use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; +global $connect, $app; $api_name = "admin_logs"; diff --git a/upload/api/vendor/composer/autoload_files.php b/upload/api/vendor/composer/autoload_files.php index 4202030..40439fe 100644 --- a/upload/api/vendor/composer/autoload_files.php +++ b/upload/api/vendor/composer/autoload_files.php @@ -7,4 +7,5 @@ return array( '253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php', + 'bdf151f62a69e3ca51f07e0bd032de74' => $vendorDir . '/lincanbin/php-pdo-mysql-class/src/PDO.class.php', ); diff --git a/upload/api/vendor/composer/autoload_psr4.php b/upload/api/vendor/composer/autoload_psr4.php index d95b77c..6da681f 100644 --- a/upload/api/vendor/composer/autoload_psr4.php +++ b/upload/api/vendor/composer/autoload_psr4.php @@ -7,7 +7,7 @@ return array( 'Slim\\' => array($vendorDir . '/slim/slim/Slim'), - 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), 'Psr\\Container\\' => array($vendorDir . '/psr/container/src'), 'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'), diff --git a/upload/api/vendor/composer/autoload_static.php b/upload/api/vendor/composer/autoload_static.php index 060657c..7733997 100644 --- a/upload/api/vendor/composer/autoload_static.php +++ b/upload/api/vendor/composer/autoload_static.php @@ -8,6 +8,7 @@ class ComposerStaticInita605d6639370e7e4b9025ac25f5fe7b8 { public static $files = array ( '253c157292f75eb38082b5acb06f3f01' => __DIR__ . '/..' . '/nikic/fast-route/src/functions.php', + 'bdf151f62a69e3ca51f07e0bd032de74' => __DIR__ . '/..' . '/lincanbin/php-pdo-mysql-class/src/PDO.class.php', ); public static $prefixLengthsPsr4 = array ( @@ -38,7 +39,7 @@ class ComposerStaticInita605d6639370e7e4b9025ac25f5fe7b8 ), 'Psr\\Log\\' => array ( - 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', + 0 => __DIR__ . '/..' . '/psr/log/src', ), 'Psr\\Http\\Message\\' => array ( diff --git a/upload/api/vendor/composer/installed.json b/upload/api/vendor/composer/installed.json index 3779071..23cc80c 100644 --- a/upload/api/vendor/composer/installed.json +++ b/upload/api/vendor/composer/installed.json @@ -1,44 +1,94 @@ { "packages": [ + { + "name": "lincanbin/php-pdo-mysql-class", + "version": "v2.2", + "version_normalized": "2.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/lincanbin/PHP-PDO-MySQL-Class.git", + "reference": "7517d30ffc514a3c54217717b97721ab394fa87a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lincanbin/PHP-PDO-MySQL-Class/zipball/7517d30ffc514a3c54217717b97721ab394fa87a", + "reference": "7517d30ffc514a3c54217717b97721ab394fa87a", + "shasum": "" + }, + "require": { + "ext-pdo": "*", + "ext-pdo_mysql": "*", + "php": ">=5.3.6" + }, + "time": "2020-11-27T02:02:36+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/PDO.class.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "lincanbin", + "email": "lincanbin@hotmail.com" + } + ], + "description": "A PHP MySQL PDO class similar to the Python MySQLdb, which supports iterator and parameter binding when using 'WHERE IN' statement.", + "keywords": [ + "database", + "iterator", + "mysql", + "pdo" + ], + "support": { + "issues": "https://github.com/lincanbin/PHP-PDO-MySQL-Class/issues", + "source": "https://github.com/lincanbin/PHP-PDO-MySQL-Class/tree/v2.2" + }, + "install-path": "../lincanbin/php-pdo-mysql-class" + }, { "name": "monolog/monolog", - "version": "2.9.1", - "version_normalized": "2.9.1.0", + "version": "3.3.1", + "version_normalized": "3.3.1.0", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "f259e2b15fb95494c83f52d3caad003bbf5ffaa1" + "reference": "9b5daeaffce5b926cac47923798bba91059e60e2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/f259e2b15fb95494c83f52d3caad003bbf5ffaa1", - "reference": "f259e2b15fb95494c83f52d3caad003bbf5ffaa1", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/9b5daeaffce5b926cac47923798bba91059e60e2", + "reference": "9b5daeaffce5b926cac47923798bba91059e60e2", "shasum": "" }, "require": { - "php": ">=7.2", - "psr/log": "^1.0.1 || ^2.0 || ^3.0" + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" }, "provide": { - "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + "psr/log-implementation": "3.0.0" }, "require-dev": { - "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "aws/aws-sdk-php": "^3.0", "doctrine/couchdb": "~1.0@dev", "elasticsearch/elasticsearch": "^7 || ^8", "ext-json": "*", "graylog2/gelf-php": "^1.4.2 || ^2@dev", - "guzzlehttp/guzzle": "^7.4", + "guzzlehttp/guzzle": "^7.4.5", "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpspec/prophecy": "^1.15", - "phpstan/phpstan": "^0.12.91", - "phpunit/phpunit": "^8.5.14", - "predis/predis": "^1.1 || ^2.0", - "rollbar/rollbar": "^1.3 || ^2 || ^3", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-strict-rules": "^1.4", + "phpunit/phpunit": "^9.5.26", + "predis/predis": "^1.1 || ^2", "ruflin/elastica": "^7", - "swiftmailer/swiftmailer": "^5.3|^6.0", "symfony/mailer": "^5.4 || ^6", "symfony/mime": "^5.4 || ^6" }, @@ -58,11 +108,11 @@ "rollbar/rollbar": "Allow sending log messages to Rollbar", "ruflin/elastica": "Allow sending log messages to an Elastic Search server" }, - "time": "2023-02-06T13:44:46+00:00", + "time": "2023-02-06T13:46:10+00:00", "type": "library", "extra": { "branch-alias": { - "dev-main": "2.x-dev" + "dev-main": "3.x-dev" } }, "installation-source": "dist", @@ -91,7 +141,7 @@ ], "support": { "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/2.9.1" + "source": "https://github.com/Seldaek/monolog/tree/3.3.1" }, "funding": [ { @@ -316,33 +366,33 @@ }, { "name": "psr/log", - "version": "1.1.4", - "version_normalized": "1.1.4.0", + "version": "3.0.0", + "version_normalized": "3.0.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11" + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, - "time": "2021-05-03T11:20:27+00:00", + "time": "2021-07-14T16:46:02+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1.x-dev" + "dev-master": "3.x-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { - "Psr\\Log\\": "Psr/Log/" + "Psr\\Log\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -363,7 +413,7 @@ "psr-3" ], "support": { - "source": "https://github.com/php-fig/log/tree/1.1.4" + "source": "https://github.com/php-fig/log/tree/3.0.0" }, "install-path": "../psr/log" }, diff --git a/upload/api/vendor/composer/installed.php b/upload/api/vendor/composer/installed.php index a890e05..ca3d2dd 100644 --- a/upload/api/vendor/composer/installed.php +++ b/upload/api/vendor/composer/installed.php @@ -19,13 +19,22 @@ 'reference' => NULL, 'dev_requirement' => false, ), + 'lincanbin/php-pdo-mysql-class' => array( + 'pretty_version' => 'v2.2', + 'version' => '2.2.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../lincanbin/php-pdo-mysql-class', + 'aliases' => array(), + 'reference' => '7517d30ffc514a3c54217717b97721ab394fa87a', + 'dev_requirement' => false, + ), 'monolog/monolog' => array( - 'pretty_version' => '2.9.1', - 'version' => '2.9.1.0', + 'pretty_version' => '3.3.1', + 'version' => '3.3.1.0', 'type' => 'library', 'install_path' => __DIR__ . '/../monolog/monolog', 'aliases' => array(), - 'reference' => 'f259e2b15fb95494c83f52d3caad003bbf5ffaa1', + 'reference' => '9b5daeaffce5b926cac47923798bba91059e60e2', 'dev_requirement' => false, ), 'nikic/fast-route' => array( @@ -71,18 +80,18 @@ ), ), 'psr/log' => array( - 'pretty_version' => '1.1.4', - 'version' => '1.1.4.0', + 'pretty_version' => '3.0.0', + 'version' => '3.0.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/log', 'aliases' => array(), - 'reference' => 'd49695b909c3b7628b6289db5479a1c204601f11', + 'reference' => 'fe5ea303b0887d5caefd3d431c3e61ad47037001', 'dev_requirement' => false, ), 'psr/log-implementation' => array( 'dev_requirement' => false, 'provided' => array( - 0 => '1.0.0 || 2.0.0 || 3.0.0', + 0 => '3.0.0', ), ), 'slim/slim' => array( diff --git a/upload/api/vendor/composer/platform_check.php b/upload/api/vendor/composer/platform_check.php index 580fa96..4c3a5d6 100644 --- a/upload/api/vendor/composer/platform_check.php +++ b/upload/api/vendor/composer/platform_check.php @@ -4,8 +4,8 @@ $issues = array(); -if (!(PHP_VERSION_ID >= 70400)) { - $issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.'; +if (!(PHP_VERSION_ID >= 80100)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.1.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { diff --git a/upload/api/vendor/monolog/monolog/CHANGELOG.md b/upload/api/vendor/monolog/monolog/CHANGELOG.md index 8a8c651..c08558a 100644 --- a/upload/api/vendor/monolog/monolog/CHANGELOG.md +++ b/upload/api/vendor/monolog/monolog/CHANGELOG.md @@ -1,3 +1,89 @@ +### 3.3.1 (2023-02-06) + + * Fixed Logger not being serializable anymore (#1792) + +### 3.3.0 (2023-02-06) + + * Deprecated FlowdockHandler & Formatter as the flowdock service was shutdown (#1748) + * Added `ClosureContextProcessor` to allow delaying the creation of context data by setting a Closure in context which is called when the log record is used (#1745) + * Added an ElasticsearchHandler option to set the `op_type` to `create` instead of the default `index` (#1766) + * Added support for enum context values in PsrLogMessageProcessor (#1773) + * Added graylog2/gelf-php 2.x support (#1747) + * Improved `BrowserConsoleHandler` logging to use more appropriate methods than just console.log in the browser (#1739) + * Fixed GitProcessor not filtering correctly based on Level (#1749) + * Fixed `WhatFailureGroupHandler` not catching errors happening inside `close()` (#1791) + * Fixed datetime field in `GoogleCloudLoggingFormatter` (#1758) + * Fixed infinite loop detection within Fibers (#1753) + * Fixed `AmqpHandler->setExtraAttributes` not working with buffering handler wrappers (#1781) + +### 3.2.0 (2022-07-24) + + * Deprecated `CubeHandler` and `PHPConsoleHandler` as both projects are abandoned and those should not be used anymore (#1734) + * Marked `Logger` `@final` as it should not be extended, prefer composition or talk to us if you are missing something + * Added RFC 5424 level (`7` to `0`) support to `Logger::log` and `Logger::addRecord` to increase interoperability (#1723) + * Added `SyslogFormatter` to output syslog-like files which can be consumed by tools like [lnav](https://lnav.org/) (#1689) + * Added support for `__toString` for objects which are not json serializable in `JsonFormatter` (#1733) + * Added `GoogleCloudLoggingFormatter` (#1719) + * Added support for Predis 2.x (#1732) + * Added `AmqpHandler->setExtraAttributes` to allow configuring attributes when using an AMQPExchange (#1724) + * Fixed serialization/unserialization of handlers to make sure private properties are included (#1727) + * Fixed allowInlineLineBreaks in LineFormatter causing issues with windows paths containing `\n` or `\r` sequences (#1720) + * Fixed max normalization depth not being taken into account when formatting exceptions with a deep chain of previous exceptions (#1726) + * Fixed PHP 8.2 deprecation warnings (#1722) + * Fixed rare race condition or filesystem issue where StreamHandler is unable to create the directory the log should go into yet it exists already (#1678) + +### 3.1.0 (2022-06-09) + + * Added `$datetime` parameter to `Logger::addRecord` as low level API to allow logging into the past or future (#1682) + * Added `Logger::useLoggingLoopDetection` to allow disabling cyclic logging detection in concurrent frameworks (#1681) + * Fixed handling of fatal errors if callPrevious is disabled in ErrorHandler (#1670) + * Fixed interop issue by removing the need for a return type in ProcessorInterface (#1680) + * Marked the reusable `Monolog\Test\TestCase` class as `@internal` to make sure PHPStorm does not show it above PHPUnit, you may still use it to test your own handlers/etc though (#1677) + * Fixed RotatingFileHandler issue when the date format contained slashes (#1671) + +### 3.0.0 (2022-05-10) + +Changes from RC1 + +- The `Monolog\LevelName` enum does not exist anymore, use `Monolog\Level->getName()` instead. + +### 3.0.0-RC1 (2022-05-08) + +This is mostly a cleanup release offering stronger type guarantees for integrators with the +array->object/enum changes, but there is no big new feature for end users. + +See [UPGRADE notes](UPGRADE.md#300) for details on all breaking changes especially if you are extending/implementing Monolog classes/interfaces. + +Noteworthy BC Breaks: + +- The minimum supported PHP version is now `8.1.0`. +- Log records have been converted from an array to a [`Monolog\LogRecord` object](src/Monolog/LogRecord.php) + with public (and mostly readonly) properties. e.g. instead of doing + `$record['context']` use `$record->context`. + In formatters or handlers if you rather need an array to work with you can use `$record->toArray()` + to get back a Monolog 1/2 style record array. This will contain the enum values instead of enum cases + in the `level` and `level_name` keys to be more backwards compatible and use simpler data types. +- `FormatterInterface`, `HandlerInterface`, `ProcessorInterface`, etc. changed to contain `LogRecord $record` + instead of `array $record` parameter types. If you want to support multiple Monolog versions this should + be possible by type-hinting nothing, or `array|LogRecord` if you support PHP 8.0+. You can then code + against the $record using Monolog 2 style as LogRecord implements ArrayAccess for BC. + The interfaces do not require a `LogRecord` return type even where it would be applicable, but if you only + support Monolog 3 in integration code I would recommend you use `LogRecord` return types wherever fitting + to ensure forward compatibility as it may be added in Monolog 4. +- Log levels are now enums [`Monolog\Level`](src/Monolog/Level.php) and [`Monolog\LevelName`](src/Monolog/LevelName.php) +- Removed deprecated SwiftMailerHandler, migrate to SymfonyMailerHandler instead. +- `ResettableInterface::reset()` now requires a void return type. +- All properties have had types added, which may require you to do so as well if you extended + a Monolog class and declared the same property. + +New deprecations: + +- `Logger::DEBUG`, `Logger::ERROR`, etc. are now deprecated in favor of the `Monolog\Level` enum. + e.g. instead of `Logger::WARNING` use `Level::Warning` if you need to pass the enum case + to Monolog or one of its handlers, or `Level::Warning->value` if you need the integer + value equal to what `Logger::WARNING` was giving you. +- `Logger::getLevelName()` is now deprecated. + ### 2.9.1 (2023-02-06) * Fixed Logger not being serializable anymore (#1792) diff --git a/upload/api/vendor/monolog/monolog/README.md b/upload/api/vendor/monolog/monolog/README.md index bfcae0c..eb6740d 100644 --- a/upload/api/vendor/monolog/monolog/README.md +++ b/upload/api/vendor/monolog/monolog/README.md @@ -3,6 +3,8 @@ [![Total Downloads](https://img.shields.io/packagist/dt/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) [![Latest Stable Version](https://img.shields.io/packagist/v/monolog/monolog.svg)](https://packagist.org/packages/monolog/monolog) +> ⚠ This is the **documentation for Monolog 3.x**, if you are using older releases +> see the documentation for [Monolog 2.x](https://github.com/Seldaek/monolog/blob/2.x/README.md) or [Monolog 1.x](https://github.com/Seldaek/monolog/blob/1.x/README.md) ⚠ Monolog sends your logs to files, sockets, inboxes, databases and various web services. See the complete list of handlers below. Special handlers @@ -28,12 +30,13 @@ $ composer require monolog/monolog ```php pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); +$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning)); // add records to the log $log->warning('Foo'); @@ -50,7 +53,7 @@ $log->error('Bar'); ## Support Monolog Financially -Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek). +Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=enterprise) or via [GitHub sponsorship](https://github.com/sponsors/Seldaek). Tidelift delivers commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. @@ -64,11 +67,13 @@ can also add your own there if you publish one. ### Requirements -- Monolog `^2.0` works with PHP 7.2 or above, use Monolog `^1.25` for PHP 5.3+ support. +- Monolog `^3.0` works with PHP 8.1 or above. +- Monolog `^2.5` works with PHP 7.2 or above. +- Monolog `^1.25` works with PHP 5.3 up to 8.1, but is not very maintained anymore and will not receive PHP support fixes anymore. ### Support -Monolog 1.x support is somewhat limited at this point and only important fixes will be done. You should migrate to Monolog 2 where possible to benefit from all the latest features and fixes. +Monolog 1.x support is somewhat limited at this point and only important fixes will be done. You should migrate to Monolog 2 or 3 where possible to benefit from all the latest features and fixes. ### Submitting bugs and feature requests @@ -96,6 +101,7 @@ Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/mono - [Drupal](https://www.drupal.org/) is usable with Monolog via the [monolog](https://www.drupal.org/project/monolog) module. - [Aimeos ecommerce framework](https://aimeos.org/) is usable with Monolog via the [ai-monolog](https://github.com/aimeos/ai-monolog) extension. - [Magento](https://magento.com/) comes out of the box with Monolog. +- [Spiral Framework](https://spiral.dev) comes out of the box with Monolog bridge. ### Author diff --git a/upload/api/vendor/monolog/monolog/composer.json b/upload/api/vendor/monolog/monolog/composer.json index b9437d6..da48d5e 100644 --- a/upload/api/vendor/monolog/monolog/composer.json +++ b/upload/api/vendor/monolog/monolog/composer.json @@ -13,26 +13,25 @@ } ], "require": { - "php": ">=7.2", - "psr/log": "^1.0.1 || ^2.0 || ^3.0" + "php": ">=8.1", + "psr/log": "^2.0 || ^3.0" }, "require-dev": { "ext-json": "*", - "aws/aws-sdk-php": "^2.4.9 || ^3.0", + "aws/aws-sdk-php": "^3.0", "doctrine/couchdb": "~1.0@dev", "elasticsearch/elasticsearch": "^7 || ^8", "graylog2/gelf-php": "^1.4.2 || ^2@dev", - "guzzlehttp/guzzle": "^7.4", + "guzzlehttp/guzzle": "^7.4.5", "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpspec/prophecy": "^1.15", - "phpstan/phpstan": "^0.12.91", - "phpunit/phpunit": "^8.5.14", - "predis/predis": "^1.1 || ^2.0", - "rollbar/rollbar": "^1.3 || ^2 || ^3", + "phpstan/phpstan": "^1.9", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-strict-rules": "^1.4", + "phpunit/phpunit": "^9.5.26", + "predis/predis": "^1.1 || ^2", "ruflin/elastica": "^7", - "swiftmailer/swiftmailer": "^5.3|^6.0", "symfony/mailer": "^5.4 || ^6", "symfony/mime": "^5.4 || ^6" }, @@ -59,11 +58,11 @@ "psr-4": {"Monolog\\": "tests/Monolog"} }, "provide": { - "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" + "psr/log-implementation": "3.0.0" }, "extra": { "branch-alias": { - "dev-main": "2.x-dev" + "dev-main": "3.x-dev" } }, "scripts": { @@ -73,9 +72,6 @@ "config": { "lock": false, "sort-packages": true, - "platform-check": false, - "allow-plugins": { - "composer/package-versions-deprecated": true - } + "platform-check": false } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php index 188bbb0..f8b2502 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php @@ -13,34 +13,24 @@ /** * A reusable attribute to help configure a class or a method as a processor. - * + * * Using it offers no guarantee: it needs to be leveraged by a Monolog third-party consumer. - * + * * Using it with the Monolog library only has no effect at all: processors should still be turned into a callable if * needed and manually pushed to the loggers and to the processable handlers. */ #[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] class AsMonologProcessor { - /** @var string|null */ - public $channel = null; - /** @var string|null */ - public $handler = null; - /** @var string|null */ - public $method = null; - /** - * @param string|null $channel The logging channel the processor should be pushed to. - * @param string|null $handler The handler the processor should be pushed to. - * @param string|null $method The method that processes the records (if the attribute is used at the class level). + * @param string|null $channel The logging channel the processor should be pushed to. + * @param string|null $handler The handler the processor should be pushed to. + * @param string|null $method The method that processes the records (if the attribute is used at the class level). */ public function __construct( - ?string $channel = null, - ?string $handler = null, - ?string $method = null + public readonly ?string $channel = null, + public readonly ?string $handler = null, + public readonly ?string $method = null ) { - $this->channel = $channel; - $this->handler = $handler; - $this->method = $method; } -} +} diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php b/upload/api/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php index 6a1ba9b..274b73e 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php @@ -21,10 +21,7 @@ */ class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable { - /** - * @var bool - */ - private $useMicroseconds; + private bool $useMicroseconds; public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null) { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/ErrorHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/ErrorHandler.php index 576f171..2ed4603 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/ErrorHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/ErrorHandler.php @@ -11,6 +11,7 @@ namespace Monolog; +use Closure; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; @@ -25,35 +26,33 @@ */ class ErrorHandler { - /** @var LoggerInterface */ - private $logger; + private Closure|null $previousExceptionHandler = null; - /** @var ?callable */ - private $previousExceptionHandler = null; /** @var array an array of class name to LogLevel::* constant mapping */ - private $uncaughtExceptionLevelMap = []; + private array $uncaughtExceptionLevelMap = []; + + /** @var Closure|true|null */ + private Closure|bool|null $previousErrorHandler = null; - /** @var callable|true|null */ - private $previousErrorHandler = null; /** @var array an array of E_* constant to LogLevel::* constant mapping */ - private $errorLevelMap = []; - /** @var bool */ - private $handleOnlyReportedErrors = true; - - /** @var bool */ - private $hasFatalErrorHandler = false; - /** @var LogLevel::* */ - private $fatalLevel = LogLevel::ALERT; - /** @var ?string */ - private $reservedMemory = null; + private array $errorLevelMap = []; + + private bool $handleOnlyReportedErrors = true; + + private bool $hasFatalErrorHandler = false; + + private string $fatalLevel = LogLevel::ALERT; + + private string|null $reservedMemory = null; + /** @var ?array{type: int, message: string, file: string, line: int, trace: mixed} */ - private $lastFatalData = null; - /** @var int[] */ - private static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; + private array|null $lastFatalData = null; - public function __construct(LoggerInterface $logger) - { - $this->logger = $logger; + private const FATAL_ERRORS = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; + + public function __construct( + private LoggerInterface $logger + ) { } /** @@ -61,7 +60,6 @@ public function __construct(LoggerInterface $logger) * * By default it will handle errors, exceptions and fatal errors * - * @param LoggerInterface $logger * @param array|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling * @param array|false $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling * @param LogLevel::*|null|false $fatalLevel a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling @@ -99,8 +97,8 @@ public function registerExceptionHandler(array $levelMap = [], bool $callPreviou $this->uncaughtExceptionLevelMap[$class] = $level; } } - if ($callPrevious && $prev) { - $this->previousExceptionHandler = $prev; + if ($callPrevious && null !== $prev) { + $this->previousExceptionHandler = $prev(...); } return $this; @@ -112,10 +110,10 @@ public function registerExceptionHandler(array $levelMap = [], bool $callPreviou */ public function registerErrorHandler(array $levelMap = [], bool $callPrevious = true, int $errorTypes = -1, bool $handleOnlyReportedErrors = true): self { - $prev = set_error_handler([$this, 'handleError'], $errorTypes); + $prev = set_error_handler($this->handleError(...), $errorTypes); $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap); if ($callPrevious) { - $this->previousErrorHandler = $prev ?: true; + $this->previousErrorHandler = $prev !== null ? $prev(...) : true; } else { $this->previousErrorHandler = null; } @@ -131,7 +129,7 @@ public function registerErrorHandler(array $levelMap = [], bool $callPrevious = */ public function registerFatalHandler($level = null, int $reservedMemorySize = 20): self { - register_shutdown_function([$this, 'handleFatalError']); + register_shutdown_function($this->handleFatalError(...)); $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); $this->fatalLevel = null === $level ? LogLevel::ALERT : $level; @@ -175,10 +173,7 @@ protected function defaultErrorLevelMap(): array ]; } - /** - * @phpstan-return never - */ - private function handleException(\Throwable $e): void + private function handleException(\Throwable $e): never { $level = LogLevel::ERROR; foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) { @@ -194,30 +189,25 @@ private function handleException(\Throwable $e): void ['exception' => $e] ); - if ($this->previousExceptionHandler) { + if (null !== $this->previousExceptionHandler) { ($this->previousExceptionHandler)($e); } - if (!headers_sent() && !ini_get('display_errors')) { + if (!headers_sent() && !(bool) ini_get('display_errors')) { http_response_code(500); } exit(255); } - /** - * @private - * - * @param mixed[] $context - */ - public function handleError(int $code, string $message, string $file = '', int $line = 0, ?array $context = []): bool + private function handleError(int $code, string $message, string $file = '', int $line = 0): bool { - if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) { + if ($this->handleOnlyReportedErrors && 0 === (error_reporting() & $code)) { return false; } // 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::FATAL_ERRORS, true)) { $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL; $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]); } else { @@ -228,8 +218,9 @@ public function handleError(int $code, string $message, string $file = '', int $ if ($this->previousErrorHandler === true) { return false; - } elseif ($this->previousErrorHandler) { - return (bool) ($this->previousErrorHandler)($code, $message, $file, $line, $context); + } + if ($this->previousErrorHandler instanceof Closure) { + return (bool) ($this->previousErrorHandler)($code, $message, $file, $line); } return true; @@ -247,8 +238,7 @@ public function handleFatalError(): void } else { $lastError = error_get_last(); } - - if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) { + if (is_array($lastError) && in_array($lastError['type'], self::FATAL_ERRORS, true)) { $trace = $lastError['trace'] ?? null; $this->logger->log( $this->fatalLevel, @@ -264,44 +254,25 @@ public function handleFatalError(): void } } - /** - * @param int $code - */ - private static function codeToString($code): string + private static function codeToString(int $code): string { - switch ($code) { - case E_ERROR: - return 'E_ERROR'; - case E_WARNING: - return 'E_WARNING'; - case E_PARSE: - return 'E_PARSE'; - case E_NOTICE: - return 'E_NOTICE'; - case E_CORE_ERROR: - return 'E_CORE_ERROR'; - case E_CORE_WARNING: - return 'E_CORE_WARNING'; - case E_COMPILE_ERROR: - return 'E_COMPILE_ERROR'; - case E_COMPILE_WARNING: - return 'E_COMPILE_WARNING'; - case E_USER_ERROR: - return 'E_USER_ERROR'; - case E_USER_WARNING: - return 'E_USER_WARNING'; - case E_USER_NOTICE: - return 'E_USER_NOTICE'; - case E_STRICT: - return 'E_STRICT'; - case E_RECOVERABLE_ERROR: - return 'E_RECOVERABLE_ERROR'; - case E_DEPRECATED: - return 'E_DEPRECATED'; - case E_USER_DEPRECATED: - return 'E_USER_DEPRECATED'; - } - - return 'Unknown PHP error'; + return match ($code) { + E_ERROR => 'E_ERROR', + E_WARNING => 'E_WARNING', + E_PARSE => 'E_PARSE', + E_NOTICE => 'E_NOTICE', + E_CORE_ERROR => 'E_CORE_ERROR', + E_CORE_WARNING => 'E_CORE_WARNING', + E_COMPILE_ERROR => 'E_COMPILE_ERROR', + E_COMPILE_WARNING => 'E_COMPILE_WARNING', + E_USER_ERROR => 'E_USER_ERROR', + E_USER_WARNING => 'E_USER_WARNING', + E_USER_NOTICE => 'E_USER_NOTICE', + E_STRICT => 'E_STRICT', + E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', + E_DEPRECATED => 'E_DEPRECATED', + E_USER_DEPRECATED => 'E_USER_DEPRECATED', + default => 'Unknown PHP error', + }; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php index aa1884b..3f1d458 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php @@ -11,7 +11,8 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Formats a log message according to the ChromePHP array format @@ -23,52 +24,55 @@ class ChromePHPFormatter implements FormatterInterface /** * Translates Monolog log levels to Wildfire levels. * - * @var array + * @return 'log'|'info'|'warn'|'error' */ - private $logLevels = [ - Logger::DEBUG => 'log', - Logger::INFO => 'info', - Logger::NOTICE => 'info', - Logger::WARNING => 'warn', - Logger::ERROR => 'error', - Logger::CRITICAL => 'error', - Logger::ALERT => 'error', - Logger::EMERGENCY => 'error', - ]; + private function toWildfireLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'log', + Level::Info => 'info', + Level::Notice => 'info', + Level::Warning => 'warn', + Level::Error => 'error', + Level::Critical => 'error', + Level::Alert => 'error', + Level::Emergency => 'error', + }; + } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record) + public function format(LogRecord $record) { // Retrieve the line and file if set and remove them from the formatted extra $backtrace = 'unknown'; - if (isset($record['extra']['file'], $record['extra']['line'])) { - $backtrace = $record['extra']['file'].' : '.$record['extra']['line']; - unset($record['extra']['file'], $record['extra']['line']); + if (isset($record->extra['file'], $record->extra['line'])) { + $backtrace = $record->extra['file'].' : '.$record->extra['line']; + unset($record->extra['file'], $record->extra['line']); } - $message = ['message' => $record['message']]; - if ($record['context']) { - $message['context'] = $record['context']; + $message = ['message' => $record->message]; + if (\count($record->context) > 0) { + $message['context'] = $record->context; } - if ($record['extra']) { - $message['extra'] = $record['extra']; + if (\count($record->extra) > 0) { + $message['extra'] = $record->extra; } if (count($message) === 1) { $message = reset($message); } return [ - $record['channel'], + $record->channel, $message, $backtrace, - $this->logLevels[$record['level']], + $this->toWildfireLevel($record->level), ]; } /** - * {@inheritDoc} + * @inheritDoc */ public function formatBatch(array $records) { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php index 6c8a9ab..8c92eff 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php @@ -12,29 +12,30 @@ namespace Monolog\Formatter; use Elastica\Document; +use Monolog\LogRecord; /** * Format a log message into an Elastica Document * * @author Jelle Vink - * - * @phpstan-import-type Record from \Monolog\Logger */ class ElasticaFormatter extends NormalizerFormatter { /** * @var string Elastic search index name */ - protected $index; + protected string $index; /** - * @var ?string Elastic search document type + * @var string|null Elastic search document type */ - protected $type; + protected string|null $type; /** * @param string $index Elastic Search index name * @param ?string $type Elastic Search document type, deprecated as of Elastica 7 + * + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(string $index, ?string $type) { @@ -46,9 +47,9 @@ public function __construct(string $index, ?string $type) } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record) + public function format(LogRecord $record) { $record = parent::format($record); @@ -72,14 +73,13 @@ public function getType(): string /** * Convert a log message into an Elastica Document * - * @phpstan-param Record $record + * @param mixed[] $record */ protected function getDocument(array $record): Document { $document = new Document(); $document->setData($record); if (method_exists($document, 'setType')) { - /** @phpstan-ignore-next-line */ $document->setType($this->type); } $document->setIndex($this->index); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php index b792b81..b38aca0 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php @@ -12,6 +12,7 @@ namespace Monolog\Formatter; use DateTimeInterface; +use Monolog\LogRecord; /** * Format a log message into an Elasticsearch record @@ -23,16 +24,18 @@ class ElasticsearchFormatter extends NormalizerFormatter /** * @var string Elasticsearch index name */ - protected $index; + protected string $index; /** * @var string Elasticsearch record type */ - protected $type; + protected string $type; /** * @param string $index Elasticsearch index name * @param string $type Elasticsearch record type + * + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(string $index, string $type) { @@ -44,9 +47,9 @@ public function __construct(string $index, string $type) } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record) + public function format(LogRecord $record) { $record = parent::format($record); @@ -55,8 +58,6 @@ public function format(array $record) /** * Getter index - * - * @return string */ public function getIndex(): string { @@ -65,8 +66,6 @@ public function getIndex(): string /** * Getter type - * - * @return string */ public function getType(): string { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php index 867ae58..c64da7c 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php @@ -11,6 +11,8 @@ namespace Monolog\Formatter; +use Monolog\LogRecord; + /** * formats the record to be used in the FlowdockHandler * @@ -19,15 +21,9 @@ */ class FlowdockFormatter implements FormatterInterface { - /** - * @var string - */ - private $source; + private string $source; - /** - * @var string - */ - private $sourceEmail; + private string $sourceEmail; public function __construct(string $source, string $sourceEmail) { @@ -36,43 +32,41 @@ public function __construct(string $source, string $sourceEmail) } /** - * {@inheritDoc} + * @inheritDoc * * @return mixed[] */ - public function format(array $record): array + public function format(LogRecord $record): array { $tags = [ '#logs', - '#' . strtolower($record['level_name']), - '#' . $record['channel'], + '#' . $record->level->toPsrLogLevel(), + '#' . $record->channel, ]; - foreach ($record['extra'] as $value) { + foreach ($record->extra as $value) { $tags[] = '#' . $value; } $subject = sprintf( 'in %s: %s - %s', $this->source, - $record['level_name'], - $this->getShortMessage($record['message']) + $record->level->getName(), + $this->getShortMessage($record->message) ); - $record['flowdock'] = [ + return [ 'source' => $this->source, 'from_address' => $this->sourceEmail, 'subject' => $subject, - 'content' => $record['message'], + 'content' => $record->message, 'tags' => $tags, 'project' => $this->source, ]; - - return $record; } /** - * {@inheritDoc} + * @inheritDoc * * @return mixed[][] */ diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php index 29b14d3..04495a6 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php @@ -12,6 +12,7 @@ namespace Monolog\Formatter; use Monolog\Utils; +use Monolog\LogRecord; /** * Class FluentdFormatter @@ -39,8 +40,11 @@ class FluentdFormatter implements FormatterInterface /** * @var bool $levelTag should message level be a part of the fluentd tag */ - protected $levelTag = false; + protected bool $levelTag = false; + /** + * @throws \RuntimeException If the function json_encode does not exist + */ public function __construct(bool $levelTag = false) { if (!function_exists('json_encode')) { @@ -55,25 +59,25 @@ public function isUsingLevelsInTag(): bool return $this->levelTag; } - public function format(array $record): string + public function format(LogRecord $record): string { - $tag = $record['channel']; + $tag = $record->channel; if ($this->levelTag) { - $tag .= '.' . strtolower($record['level_name']); + $tag .= '.' . $record->level->toPsrLogLevel(); } $message = [ - 'message' => $record['message'], - 'context' => $record['context'], - 'extra' => $record['extra'], + 'message' => $record->message, + 'context' => $record->context, + 'extra' => $record->extra, ]; if (!$this->levelTag) { - $message['level'] = $record['level']; - $message['level_name'] = $record['level_name']; + $message['level'] = $record->level->value; + $message['level_name'] = $record->level->getName(); } - return Utils::jsonEncode([$tag, $record['datetime']->getTimestamp(), $message]); + return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]); } public function formatBatch(array $records): string diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php index 19617ec..3413a4b 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php @@ -11,32 +11,28 @@ namespace Monolog\Formatter; +use Monolog\LogRecord; + /** * Interface for formatters * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger */ interface FormatterInterface { /** * Formats a log record. * - * @param array $record A record to format - * @return mixed The formatted record - * - * @phpstan-param Record $record + * @param LogRecord $record A record to format + * @return mixed The formatted record */ - public function format(array $record); + public function format(LogRecord $record); /** * Formats a set of log records. * - * @param array $records A set of records to format - * @return mixed The formatted set of records - * - * @phpstan-param Record[] $records + * @param array $records A set of records to format + * @return mixed The formatted set of records */ public function formatBatch(array $records); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php index 3b3e1e7..96cb60f 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php @@ -11,17 +11,16 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Gelf\Message; use Monolog\Utils; +use Monolog\LogRecord; /** * Serializes a log message to GELF * @see http://docs.graylog.org/en/latest/pages/gelf.html * * @author Matt Lehner - * - * @phpstan-import-type Level from \Monolog\Logger */ class GelfMessageFormatter extends NormalizerFormatter { @@ -30,46 +29,43 @@ class GelfMessageFormatter extends NormalizerFormatter /** * @var string the name of the system for the Gelf log message */ - protected $systemName; + protected string $systemName; /** * @var string a prefix for 'extra' fields from the Monolog record (optional) */ - protected $extraPrefix; + protected string $extraPrefix; /** * @var string a prefix for 'context' fields from the Monolog record (optional) */ - protected $contextPrefix; + protected string $contextPrefix; /** * @var int max length per field */ - protected $maxLength; + protected int $maxLength; /** - * @var int + * Translates Monolog log levels to Graylog2 log priorities. */ - private $gelfVersion = 2; + private function getGraylog2Priority(Level $level): int + { + return match ($level) { + Level::Debug => 7, + Level::Info => 6, + Level::Notice => 5, + Level::Warning => 4, + Level::Error => 3, + Level::Critical => 2, + Level::Alert => 1, + Level::Emergency => 0, + }; + } /** - * Translates Monolog log levels to Graylog2 log priorities. - * - * @var array - * - * @phpstan-var array + * @throws \RuntimeException */ - private $logLevels = [ - Logger::DEBUG => 7, - Logger::INFO => 6, - Logger::NOTICE => 5, - Logger::WARNING => 4, - Logger::ERROR => 3, - Logger::CRITICAL => 2, - Logger::ALERT => 1, - Logger::EMERGENCY => 0, - ]; - public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null) { if (!class_exists(Message::class)) { @@ -78,64 +74,44 @@ public function __construct(?string $systemName = null, ?string $extraPrefix = n parent::__construct('U.u'); - $this->systemName = (is_null($systemName) || $systemName === '') ? (string) gethostname() : $systemName; + $this->systemName = (null === $systemName || $systemName === '') ? (string) gethostname() : $systemName; - $this->extraPrefix = is_null($extraPrefix) ? '' : $extraPrefix; + $this->extraPrefix = null === $extraPrefix ? '' : $extraPrefix; $this->contextPrefix = $contextPrefix; - $this->maxLength = is_null($maxLength) ? self::DEFAULT_MAX_LENGTH : $maxLength; - - if (method_exists(Message::class, 'setFacility')) { - $this->gelfVersion = 1; - } + $this->maxLength = null === $maxLength ? self::DEFAULT_MAX_LENGTH : $maxLength; } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record): Message + public function format(LogRecord $record): Message { $context = $extra = []; - if (isset($record['context'])) { + if (isset($record->context)) { /** @var mixed[] $context */ - $context = parent::normalize($record['context']); + $context = parent::normalize($record->context); } - if (isset($record['extra'])) { + if (isset($record->extra)) { /** @var mixed[] $extra */ - $extra = parent::normalize($record['extra']); - } - - if (!isset($record['datetime'], $record['message'], $record['level'])) { - throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, '.var_export($record, true).' given'); + $extra = parent::normalize($record->extra); } $message = new Message(); $message - ->setTimestamp($record['datetime']) - ->setShortMessage((string) $record['message']) + ->setTimestamp($record->datetime) + ->setShortMessage($record->message) ->setHost($this->systemName) - ->setLevel($this->logLevels[$record['level']]); + ->setLevel($this->getGraylog2Priority($record->level)); // message length + system name length + 200 for padding / metadata - $len = 200 + strlen((string) $record['message']) + strlen($this->systemName); + $len = 200 + strlen($record->message) + strlen($this->systemName); if ($len > $this->maxLength) { - $message->setShortMessage(Utils::substr($record['message'], 0, $this->maxLength)); + $message->setShortMessage(Utils::substr($record->message, 0, $this->maxLength)); } - if ($this->gelfVersion === 1) { - if (isset($record['channel'])) { - $message->setFacility($record['channel']); - } - if (isset($extra['line'])) { - $message->setLine($extra['line']); - unset($extra['line']); - } - if (isset($extra['file'])) { - $message->setFile($extra['file']); - unset($extra['file']); - } - } else { - $message->setAdditional('facility', $record['channel']); + if (isset($record->channel)) { + $message->setAdditional('facility', $record->channel); } foreach ($extra as $key => $val) { @@ -160,13 +136,10 @@ public function format(array $record): Message $message->setAdditional($this->contextPrefix . $key, $val); } - if ($this->gelfVersion === 1) { - /** @phpstan-ignore-next-line */ - if (null === $message->getFile() && isset($context['exception']['file'])) { - if (preg_match("/^(.+):([0-9]+)$/", $context['exception']['file'], $matches)) { - $message->setFile($matches[1]); - $message->setLine($matches[2]); - } + if (!$message->hasAdditional('file') && isset($context['exception']['file'])) { + if (1 === preg_match("/^(.+):([0-9]+)$/", $context['exception']['file'], $matches)) { + $message->setAdditional('file', $matches[1]); + $message->setAdditional('line', $matches[2]); } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php index ca52ebf..ea555d4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php @@ -24,17 +24,17 @@ */ final class GoogleCloudLoggingFormatter extends JsonFormatter { - /** {@inheritdoc} **/ - public function format(array $record): string + protected function normalizeRecord(LogRecord $record): array { + $normalized = parent::normalizeRecord($record); + // Re-key level for GCP logging - $record['severity'] = $record['level_name']; - $record['time'] = $record['datetime']->format(DateTimeInterface::RFC3339_EXTENDED); + $normalized['severity'] = $normalized['level_name']; + $normalized['time'] = $record->datetime->format(DateTimeInterface::RFC3339_EXTENDED); // Remove keys that are not used by GCP - unset($record['level'], $record['level_name'], $record['datetime']); + unset($normalized['level'], $normalized['level_name'], $normalized['datetime']); - return parent::format($record); + return $normalized; } } - diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php index 10a4311..c316b65 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php @@ -11,8 +11,9 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Formats incoming records into an HTML table @@ -25,22 +26,24 @@ class HtmlFormatter extends NormalizerFormatter { /** * Translates Monolog log levels to html color priorities. - * - * @var array */ - protected $logLevels = [ - Logger::DEBUG => '#CCCCCC', - Logger::INFO => '#28A745', - Logger::NOTICE => '#17A2B8', - Logger::WARNING => '#FFC107', - Logger::ERROR => '#FD7E14', - Logger::CRITICAL => '#DC3545', - Logger::ALERT => '#821722', - Logger::EMERGENCY => '#000000', - ]; + protected function getLevelColor(Level $level): string + { + return match ($level) { + Level::Debug => '#CCCCCC', + Level::Info => '#28A745', + Level::Notice => '#17A2B8', + Level::Warning => '#FFC107', + Level::Error => '#FD7E14', + Level::Critical => '#DC3545', + Level::Alert => '#821722', + Level::Emergency => '#000000', + }; + } /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(?string $dateFormat = null) { @@ -67,15 +70,13 @@ protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): /** * Create a HTML h1 tag * - * @param string $title Text to be in the h1 - * @param int $level Error level - * @return string + * @param string $title Text to be in the h1 */ - protected function addTitle(string $title, int $level): string + protected function addTitle(string $title, Level $level): string { $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); - return '

'.$title.'

'; + return '

'.$title.'

'; } /** @@ -83,25 +84,25 @@ protected function addTitle(string $title, int $level): string * * @return string The formatted record */ - public function format(array $record): string + public function format(LogRecord $record): string { - $output = $this->addTitle($record['level_name'], $record['level']); + $output = $this->addTitle($record->level->getName(), $record->level); $output .= ''; - $output .= $this->addRow('Message', (string) $record['message']); - $output .= $this->addRow('Time', $this->formatDate($record['datetime'])); - $output .= $this->addRow('Channel', $record['channel']); - if ($record['context']) { + $output .= $this->addRow('Message', $record->message); + $output .= $this->addRow('Time', $this->formatDate($record->datetime)); + $output .= $this->addRow('Channel', $record->channel); + if (\count($record->context) > 0) { $embeddedTable = '
'; - foreach ($record['context'] as $key => $value) { + foreach ($record->context as $key => $value) { $embeddedTable .= $this->addRow((string) $key, $this->convertToString($value)); } $embeddedTable .= '
'; $output .= $this->addRow('Context', $embeddedTable, false); } - if ($record['extra']) { + if (\count($record->extra) > 0) { $embeddedTable = ''; - foreach ($record['extra'] as $key => $value) { + foreach ($record->extra as $key => $value) { $embeddedTable .= $this->addRow((string) $key, $this->convertToString($value)); } $embeddedTable .= '
'; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php index b737d82..039c38d 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php @@ -11,7 +11,9 @@ namespace Monolog\Formatter; +use Stringable; use Throwable; +use Monolog\LogRecord; /** * Encodes whatever record data is passed to it as json @@ -19,8 +21,6 @@ * This can be useful to log to databases or remote APIs * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger */ class JsonFormatter extends NormalizerFormatter { @@ -28,16 +28,18 @@ class JsonFormatter extends NormalizerFormatter public const BATCH_MODE_NEWLINES = 2; /** @var self::BATCH_MODE_* */ - protected $batchMode; - /** @var bool */ - protected $appendNewline; - /** @var bool */ - protected $ignoreEmptyContextAndExtra; - /** @var bool */ - protected $includeStacktraces = false; + protected int $batchMode; + + protected bool $appendNewline; + + protected bool $ignoreEmptyContextAndExtra; + + protected bool $includeStacktraces = false; /** * @param self::BATCH_MODE_* $batchMode + * + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) { @@ -70,11 +72,11 @@ public function isAppendingNewlines(): bool } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record): string + public function format(LogRecord $record): string { - $normalized = $this->normalize($record); + $normalized = parent::format($record); if (isset($normalized['context']) && $normalized['context'] === []) { if ($this->ignoreEmptyContextAndExtra) { @@ -95,23 +97,16 @@ public function format(array $record): string } /** - * {@inheritDoc} + * @inheritDoc */ public function formatBatch(array $records): string { - switch ($this->batchMode) { - case static::BATCH_MODE_NEWLINES: - return $this->formatBatchNewlines($records); - - case static::BATCH_MODE_JSON: - default: - return $this->formatBatchJson($records); - } + return match ($this->batchMode) { + static::BATCH_MODE_NEWLINES => $this->formatBatchNewlines($records), + default => $this->formatBatchJson($records), + }; } - /** - * @return self - */ public function includeStacktraces(bool $include = true): self { $this->includeStacktraces = $include; @@ -122,7 +117,7 @@ public function includeStacktraces(bool $include = true): self /** * Return a JSON-encoded array of records. * - * @phpstan-param Record[] $records + * @phpstan-param LogRecord[] $records */ protected function formatBatchJson(array $records): string { @@ -133,30 +128,24 @@ protected function formatBatchJson(array $records): string * Use new lines to separate records instead of a * JSON-encoded array. * - * @phpstan-param Record[] $records + * @phpstan-param LogRecord[] $records */ protected function formatBatchNewlines(array $records): string { - $instance = $this; - $oldNewline = $this->appendNewline; $this->appendNewline = false; - array_walk($records, function (&$value, $key) use ($instance) { - $value = $instance->format($value); - }); + $formatted = array_map(fn (LogRecord $record) => $this->format($record), $records); $this->appendNewline = $oldNewline; - return implode("\n", $records); + return implode("\n", $formatted); } /** * Normalizes given $data. * - * @param mixed $data - * - * @return mixed + * @return null|scalar|array|object */ - protected function normalize($data, int $depth = 0) + protected function normalize(mixed $data, int $depth = 0): mixed { if ($depth > $this->maxNormalizeDepth) { return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization'; @@ -192,7 +181,7 @@ protected function normalize($data, int $depth = 0) return $data; } - if (method_exists($data, '__toString')) { + if ($data instanceof Stringable) { return $data->__toString(); } @@ -210,7 +199,7 @@ protected function normalize($data, int $depth = 0) * Normalizes given exception with or without its own stack trace based on * `includeStacktraces` property. * - * {@inheritDoc} + * @inheritDoc */ protected function normalizeException(Throwable $e, int $depth = 0): array { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php index b31b297..76ac770 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php @@ -11,7 +11,9 @@ namespace Monolog\Formatter; +use Closure; use Monolog\Utils; +use Monolog\LogRecord; /** * Formats incoming records into a one-line string @@ -25,22 +27,18 @@ class LineFormatter extends NormalizerFormatter { public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"; - /** @var string */ - protected $format; - /** @var bool */ - protected $allowInlineLineBreaks; - /** @var bool */ - protected $ignoreEmptyContextAndExtra; - /** @var bool */ - protected $includeStacktraces; - /** @var ?callable */ - protected $stacktracesParser; + protected string $format; + protected bool $allowInlineLineBreaks; + protected bool $ignoreEmptyContextAndExtra; + protected bool $includeStacktraces; + protected Closure|null $stacktracesParser = null; /** - * @param string|null $format The format of the message - * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format - * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries - * @param bool $ignoreEmptyContextAndExtra + * @param string|null $format The format of the message + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries + * + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) { @@ -51,7 +49,7 @@ public function __construct(?string $format = null, ?string $dateFormat = null, parent::__construct($dateFormat); } - public function includeStacktraces(bool $include = true, ?callable $parser = null): self + public function includeStacktraces(bool $include = true, ?Closure $parser = null): self { $this->includeStacktraces = $include; if ($this->includeStacktraces) { @@ -77,14 +75,13 @@ public function ignoreEmptyContextAndExtra(bool $ignore = true): self } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record): string + public function format(LogRecord $record): string { $vars = parent::format($record); $output = $this->format; - foreach ($vars['extra'] as $var => $val) { if (false !== strpos($output, '%extra.'.$var.'%')) { $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output); @@ -100,12 +97,12 @@ public function format(array $record): string } if ($this->ignoreEmptyContextAndExtra) { - if (empty($vars['context'])) { + if (\count($vars['context']) === 0) { unset($vars['context']); $output = str_replace('%context%', '', $output); } - if (empty($vars['extra'])) { + if (\count($vars['extra']) === 0) { unset($vars['extra']); $output = str_replace('%extra%', '', $output); } @@ -122,6 +119,7 @@ public function format(array $record): string $output = preg_replace('/%(?:extra|context)\..+?%/', '', $output); if (null === $output) { $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); } } @@ -151,7 +149,7 @@ protected function normalizeException(\Throwable $e, int $depth = 0): string { $str = $this->formatException($e); - if ($previous = $e->getPrevious()) { + if (($previous = $e->getPrevious()) instanceof \Throwable) { do { $depth++; if ($depth > $this->maxNormalizeDepth) { @@ -232,7 +230,7 @@ private function stacktracesParser(\Throwable $e): string { $trace = $e->getTraceAsString(); - if ($this->stacktracesParser) { + if ($this->stacktracesParser !== null) { $trace = $this->stacktracesParserCustom($trace); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php index 29841aa..5f0b6a4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php @@ -11,6 +11,8 @@ namespace Monolog\Formatter; +use Monolog\LogRecord; + /** * Encodes message information into JSON in a format compatible with Loggly. * @@ -33,13 +35,13 @@ public function __construct(int $batchMode = self::BATCH_MODE_NEWLINES, bool $ap * @see https://www.loggly.com/docs/automated-parsing/#json * @see \Monolog\Formatter\JsonFormatter::format() */ - public function format(array $record): string + protected function normalizeRecord(LogRecord $record): array { - if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) { - $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO"); - unset($record["datetime"]); - } + $recordData = parent::normalizeRecord($record); + + $recordData["timestamp"] = $record->datetime->format("Y-m-d\TH:i:s.uO"); + unset($recordData["datetime"]); - return parent::format($record); + return $recordData; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php index b0451ab..10ad0d9 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php @@ -11,6 +11,8 @@ namespace Monolog\Formatter; +use Monolog\LogRecord; + /** * Encodes message information into JSON in a format compatible with Logmatic. * @@ -20,15 +22,9 @@ class LogmaticFormatter extends JsonFormatter { protected const MARKERS = ["sourcecode", "php"]; - /** - * @var string - */ - protected $hostname = ''; + protected string $hostname = ''; - /** - * @var string - */ - protected $appname = ''; + protected string $appName = ''; public function setHostname(string $hostname): self { @@ -37,9 +33,9 @@ public function setHostname(string $hostname): self return $this; } - public function setAppname(string $appname): self + public function setAppName(string $appName): self { - $this->appname = $appname; + $this->appName = $appName; return $this; } @@ -50,17 +46,19 @@ public function setAppname(string $appname): self * @see http://doc.logmatic.io/docs/basics-to-send-data * @see \Monolog\Formatter\JsonFormatter::format() */ - public function format(array $record): string + public function normalizeRecord(LogRecord $record): array { - if (!empty($this->hostname)) { + $record = parent::normalizeRecord($record); + + if ($this->hostname !== '') { $record["hostname"] = $this->hostname; } - if (!empty($this->appname)) { - $record["appname"] = $this->appname; + if ($this->appName !== '') { + $record["appname"] = $this->appName; } $record["@marker"] = static::MARKERS; - return parent::format($record); + return $record; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php index f8de0d3..abee3cd 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php @@ -11,6 +11,8 @@ namespace Monolog\Formatter; +use Monolog\LogRecord; + /** * Serializes a log message to Logstash Event Format * @@ -24,28 +26,30 @@ class LogstashFormatter extends NormalizerFormatter /** * @var string the name of the system for the Logstash log message, used to fill the @source field */ - protected $systemName; + protected string $systemName; /** * @var string an application name for the Logstash log message, used to fill the @type field */ - protected $applicationName; + protected string $applicationName; /** * @var string the key for 'extra' fields from the Monolog record */ - protected $extraKey; + protected string $extraKey; /** * @var string the key for 'context' fields from the Monolog record */ - protected $contextKey; + protected string $contextKey; /** * @param string $applicationName The application that sends the data, used as the "type" field of logstash * @param string|null $systemName The system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine * @param string $extraKey The key for extra keys inside logstash "fields", defaults to extra * @param string $contextKey The key for context keys inside logstash "fields", defaults to context + * + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(string $applicationName, ?string $systemName = null, string $extraKey = 'extra', string $contextKey = 'context') { @@ -59,41 +63,38 @@ public function __construct(string $applicationName, ?string $systemName = null, } /** - * {@inheritDoc} + * @inheritDoc */ - public function format(array $record): string + public function format(LogRecord $record): string { - $record = parent::format($record); + $recordData = parent::format($record); - if (empty($record['datetime'])) { - $record['datetime'] = gmdate('c'); - } $message = [ - '@timestamp' => $record['datetime'], + '@timestamp' => $recordData['datetime'], '@version' => 1, 'host' => $this->systemName, ]; - if (isset($record['message'])) { - $message['message'] = $record['message']; + if (isset($recordData['message'])) { + $message['message'] = $recordData['message']; } - if (isset($record['channel'])) { - $message['type'] = $record['channel']; - $message['channel'] = $record['channel']; + if (isset($recordData['channel'])) { + $message['type'] = $recordData['channel']; + $message['channel'] = $recordData['channel']; } - if (isset($record['level_name'])) { - $message['level'] = $record['level_name']; + if (isset($recordData['level_name'])) { + $message['level'] = $recordData['level_name']; } - if (isset($record['level'])) { - $message['monolog_level'] = $record['level']; + if (isset($recordData['level'])) { + $message['monolog_level'] = $recordData['level']; } - if ($this->applicationName) { + if ('' !== $this->applicationName) { $message['type'] = $this->applicationName; } - if (!empty($record['extra'])) { - $message[$this->extraKey] = $record['extra']; + if (\count($recordData['extra']) > 0) { + $message[$this->extraKey] = $recordData['extra']; } - if (!empty($record['context'])) { - $message[$this->contextKey] = $record['context']; + if (\count($recordData['context']) > 0) { + $message[$this->contextKey] = $recordData['context']; } return $this->toJson($message) . "\n"; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php index fca69a8..a3bdd4f 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php @@ -14,6 +14,7 @@ use MongoDB\BSON\Type; use MongoDB\BSON\UTCDateTime; use Monolog\Utils; +use Monolog\LogRecord; /** * Formats a record for use with the MongoDBHandler. @@ -22,15 +23,12 @@ */ class MongoDBFormatter implements FormatterInterface { - /** @var bool */ - private $exceptionTraceAsString; - /** @var int */ - private $maxNestingLevel; - /** @var bool */ - private $isLegacyMongoExt; + private bool $exceptionTraceAsString; + private int $maxNestingLevel; + private bool $isLegacyMongoExt; /** - * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2 + * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record->context is 2 * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings */ public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsString = true) @@ -42,20 +40,20 @@ public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsStri } /** - * {@inheritDoc} + * @inheritDoc * * @return mixed[] */ - public function format(array $record): array + public function format(LogRecord $record): array { /** @var mixed[] $res */ - $res = $this->formatArray($record); + $res = $this->formatArray($record->toArray()); return $res; } /** - * {@inheritDoc} + * @inheritDoc * * @return array */ diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php index 5441bc0..b1214f0 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php @@ -14,6 +14,7 @@ use Monolog\DateTimeImmutable; use Monolog\Utils; use Throwable; +use Monolog\LogRecord; /** * Normalizes incoming records to remove objects/resources so it's easier to dump to various targets @@ -24,18 +25,15 @@ class NormalizerFormatter implements FormatterInterface { public const SIMPLE_DATE = "Y-m-d\TH:i:sP"; - /** @var string */ - protected $dateFormat; - /** @var int */ - protected $maxNormalizeDepth = 9; - /** @var int */ - protected $maxNormalizeItemCount = 1000; + protected string $dateFormat; + protected int $maxNormalizeDepth = 9; + protected int $maxNormalizeItemCount = 1000; - /** @var int */ - private $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS; + private int $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS; /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(?string $dateFormat = null) { @@ -46,17 +44,25 @@ public function __construct(?string $dateFormat = null) } /** - * {@inheritDoc} + * @inheritDoc + */ + public function format(LogRecord $record) + { + return $this->normalizeRecord($record); + } + + /** + * Normalize an arbitrary value to a scalar|array|null * - * @param mixed[] $record + * @return null|scalar|array */ - public function format(array $record) + public function normalizeValue(mixed $data): mixed { - return $this->normalize($record); + return $this->normalize($data); } /** - * {@inheritDoc} + * @inheritDoc */ public function formatBatch(array $records) { @@ -124,10 +130,25 @@ public function setJsonPrettyPrint(bool $enable): self } /** - * @param mixed $data - * @return null|scalar|array + * Provided as extension point + * + * Because normalize is called with sub-values of context data etc, normalizeRecord can be + * extended when data needs to be appended on the record array but not to other normalized data. + * + * @return array */ - protected function normalize($data, int $depth = 0) + protected function normalizeRecord(LogRecord $record): array + { + /** @var array $normalized */ + $normalized = $this->normalize($record->toArray()); + + return $normalized; + } + + /** + * @return null|scalar|array + */ + protected function normalize(mixed $data, int $depth = 0): mixed { if ($depth > $this->maxNormalizeDepth) { return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; @@ -172,14 +193,14 @@ protected function normalize($data, int $depth = 0) } if ($data instanceof \JsonSerializable) { - /** @var null|scalar|array $value */ + /** @var null|scalar|array $value */ $value = $data->jsonSerialize(); } elseif (method_exists($data, '__toString')) { /** @var string $value */ $value = $data->__toString(); } else { // the rest is normalized by json encoding and decoding it - /** @var null|scalar|array $value */ + /** @var null|scalar|array $value */ $value = json_decode($this->toJson($data, true), true); } @@ -233,12 +254,12 @@ protected function normalizeException(Throwable $e, int $depth = 0) $trace = $e->getTrace(); foreach ($trace as $frame) { - if (isset($frame['file'])) { + if (isset($frame['file'], $frame['line'])) { $data['trace'][] = $frame['file'].':'.$frame['line']; } } - if ($previous = $e->getPrevious()) { + if (($previous = $e->getPrevious()) instanceof \Throwable) { $data['previous'] = $this->normalizeException($previous, $depth + 1); } @@ -257,10 +278,7 @@ protected function toJson($data, bool $ignoreErrors = false): string return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors); } - /** - * @return string - */ - protected function formatDate(\DateTimeInterface $date) + protected function formatDate(\DateTimeInterface $date): string { // in case the date format isn't custom then we defer to the custom DateTimeImmutable // formatting logic, which will pick the right format based on whether useMicroseconds is on diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php index 187bc55..4bc20a0 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php @@ -11,8 +11,10 @@ namespace Monolog\Formatter; +use Monolog\LogRecord; + /** - * Formats data into an associative array of scalar values. + * Formats data into an associative array of scalar (+ null) values. * Objects and arrays will be JSON encoded. * * @author Andrew Lawson @@ -20,25 +22,21 @@ class ScalarFormatter extends NormalizerFormatter { /** - * {@inheritDoc} + * @inheritDoc * * @phpstan-return array $record */ - public function format(array $record): array + public function format(LogRecord $record): array { $result = []; - foreach ($record as $key => $value) { - $result[$key] = $this->normalizeValue($value); + foreach ($record->toArray() as $key => $value) { + $result[$key] = $this->toScalar($value); } return $result; } - /** - * @param mixed $value - * @return scalar|null - */ - protected function normalizeValue($value) + protected function toScalar(mixed $value): string|int|float|bool|null { $normalized = $this->normalize($value); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php index 6539b34..2e28b3a 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php @@ -11,7 +11,8 @@ namespace Monolog\Formatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Serializes a log message according to Wildfire's header requirements @@ -19,29 +20,13 @@ * @author Eric Clemmons (@ericclemmons) * @author Christophe Coevoet * @author Kirill chEbba Chebunin - * - * @phpstan-import-type Level from \Monolog\Logger */ class WildfireFormatter extends NormalizerFormatter { - /** - * Translates Monolog log levels to Wildfire levels. - * - * @var array - */ - private $logLevels = [ - Logger::DEBUG => 'LOG', - Logger::INFO => 'INFO', - Logger::NOTICE => 'INFO', - Logger::WARNING => 'WARN', - Logger::ERROR => 'ERROR', - Logger::CRITICAL => 'ERROR', - Logger::ALERT => 'ERROR', - Logger::EMERGENCY => 'ERROR', - ]; - /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * + * @throws \RuntimeException If the function json_encode does not exist */ public function __construct(?string $dateFormat = null) { @@ -52,46 +37,61 @@ public function __construct(?string $dateFormat = null) } /** - * {@inheritDoc} + * Translates Monolog log levels to Wildfire levels. * - * @return string + * @return 'LOG'|'INFO'|'WARN'|'ERROR' + */ + private function toWildfireLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'LOG', + Level::Info => 'INFO', + Level::Notice => 'INFO', + Level::Warning => 'WARN', + Level::Error => 'ERROR', + Level::Critical => 'ERROR', + Level::Alert => 'ERROR', + Level::Emergency => 'ERROR', + }; + } + + /** + * @inheritDoc */ - public function format(array $record): string + public function format(LogRecord $record): string { // Retrieve the line and file if set and remove them from the formatted extra $file = $line = ''; - if (isset($record['extra']['file'])) { - $file = $record['extra']['file']; - unset($record['extra']['file']); + if (isset($record->extra['file'])) { + $file = $record->extra['file']; + unset($record->extra['file']); } - if (isset($record['extra']['line'])) { - $line = $record['extra']['line']; - unset($record['extra']['line']); + if (isset($record->extra['line'])) { + $line = $record->extra['line']; + unset($record->extra['line']); } - /** @var mixed[] $record */ - $record = $this->normalize($record); - $message = ['message' => $record['message']]; + $message = ['message' => $record->message]; $handleError = false; - if ($record['context']) { - $message['context'] = $record['context']; + if (count($record->context) > 0) { + $message['context'] = $this->normalize($record->context); $handleError = true; } - if ($record['extra']) { - $message['extra'] = $record['extra']; + if (count($record->extra) > 0) { + $message['extra'] = $this->normalize($record->extra); $handleError = true; } if (count($message) === 1) { $message = reset($message); } - if (isset($record['context']['table'])) { + if (is_array($message) && isset($message['context']['table'])) { $type = 'TABLE'; - $label = $record['channel'] .': '. $record['message']; - $message = $record['context']['table']; + $label = $record->channel .': '. $record->message; + $message = $message['context']['table']; } else { - $type = $this->logLevels[$record['level']]; - $label = $record['channel']; + $type = $this->toWildfireLevel($record->level); + $label = $record->channel; } // Create JSON object describing the appearance of the message in the console @@ -114,7 +114,7 @@ public function format(array $record): string } /** - * {@inheritDoc} + * @inheritDoc * * @phpstan-return never */ @@ -124,11 +124,11 @@ public function formatBatch(array $records) } /** - * {@inheritDoc} + * @inheritDoc * - * @return null|scalar|array|object + * @return null|scalar|array|object */ - protected function normalize($data, int $depth = 0) + protected function normalize(mixed $data, int $depth = 0): mixed { if (is_object($data) && !$data instanceof \DateTimeInterface) { return $data; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php index a5cdaa7..3399a54 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php @@ -11,55 +11,50 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Logger; use Monolog\ResettableInterface; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Base Handler class providing basic level/bubble support * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ abstract class AbstractHandler extends Handler implements ResettableInterface { - /** - * @var int - * @phpstan-var Level - */ - protected $level = Logger::DEBUG; - /** @var bool */ - protected $bubble = true; + protected Level $level = Level::Debug; + protected bool $bubble = true; /** - * @param int|string $level The minimum logging level at which this handler will be triggered - * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param int|string|Level|LogLevel::* $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 * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG, bool $bubble = true) + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) { $this->setLevel($level); $this->bubble = $bubble; } /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { - return $record['level'] >= $this->level; + return $record->level->value >= $this->level->value; } /** * Sets minimum logging level at which this handler will be triggered. * - * @param Level|LevelName|LogLevel::* $level Level or level name - * @return self + * @param Level|LogLevel::* $level Level or level name + * + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function setLevel($level): self + public function setLevel(int|string|Level $level): self { $this->level = Logger::toMonologLevel($level); @@ -68,12 +63,8 @@ public function setLevel($level): self /** * Gets minimum logging level at which this handler will be triggered. - * - * @return int - * - * @phpstan-return Level */ - public function getLevel(): int + public function getLevel(): Level { return $this->level; } @@ -81,9 +72,8 @@ public function getLevel(): int /** * Sets the bubbling behavior. * - * @param bool $bubble true means that this handler allows bubbling. - * false means that bubbling is not permitted. - * @return self + * @param bool $bubble true means that this handler allows bubbling. + * false means that bubbling is not permitted. */ public function setBubble(bool $bubble): self { @@ -104,9 +94,9 @@ public function getBubble(): bool } /** - * {@inheritDoc} + * @inheritDoc */ - public function reset() + public function reset(): void { } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php index 77e533f..de13a76 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php @@ -11,6 +11,8 @@ namespace Monolog\Handler; +use Monolog\LogRecord; + /** * Base Handler class providing the Handler structure, including processors and formatters * @@ -18,11 +20,6 @@ * * @author Jordi Boggiano * @author Christophe Coevoet - * - * @phpstan-import-type LevelName from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-type FormattedRecord array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[], formatted: mixed} */ abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface { @@ -30,20 +27,19 @@ abstract class AbstractProcessingHandler extends AbstractHandler implements Proc use FormattableHandlerTrait; /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { if (!$this->isHandling($record)) { return false; } - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } - $record['formatted'] = $this->getFormatter()->format($record); + $record->formatted = $this->getFormatter()->format($record); $this->write($record); @@ -51,16 +47,11 @@ public function handle(array $record): bool } /** - * Writes the record down to the log of the implementing handler - * - * @phpstan-param FormattedRecord $record + * Writes the (already formatted) record down to the log of the implementing handler */ - abstract protected function write(array $record): void; + abstract protected function write(LogRecord $record): void; - /** - * @return void - */ - public function reset() + public function reset(): void { parent::reset(); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php index 5e5ad1c..695a1c0 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php @@ -11,70 +11,59 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; /** * Common syslog functionality - * - * @phpstan-import-type Level from \Monolog\Logger */ abstract class AbstractSyslogHandler extends AbstractProcessingHandler { - /** @var int */ - protected $facility; + protected int $facility; /** - * Translates Monolog log levels to syslog log priorities. - * @var array - * @phpstan-var array + * List of valid log facility names. + * @var array */ - protected $logLevels = [ - Logger::DEBUG => LOG_DEBUG, - Logger::INFO => LOG_INFO, - Logger::NOTICE => LOG_NOTICE, - Logger::WARNING => LOG_WARNING, - Logger::ERROR => LOG_ERR, - Logger::CRITICAL => LOG_CRIT, - Logger::ALERT => LOG_ALERT, - Logger::EMERGENCY => LOG_EMERG, + protected array $facilities = [ + 'auth' => \LOG_AUTH, + 'authpriv' => \LOG_AUTHPRIV, + 'cron' => \LOG_CRON, + 'daemon' => \LOG_DAEMON, + 'kern' => \LOG_KERN, + 'lpr' => \LOG_LPR, + 'mail' => \LOG_MAIL, + 'news' => \LOG_NEWS, + 'syslog' => \LOG_SYSLOG, + 'user' => \LOG_USER, + 'uucp' => \LOG_UUCP, ]; /** - * List of valid log facility names. - * @var array + * Translates Monolog log levels to syslog log priorities. */ - protected $facilities = [ - 'auth' => LOG_AUTH, - 'authpriv' => LOG_AUTHPRIV, - 'cron' => LOG_CRON, - 'daemon' => LOG_DAEMON, - 'kern' => LOG_KERN, - 'lpr' => LOG_LPR, - 'mail' => LOG_MAIL, - 'news' => LOG_NEWS, - 'syslog' => LOG_SYSLOG, - 'user' => LOG_USER, - 'uucp' => LOG_UUCP, - ]; + protected function toSyslogPriority(Level $level): int + { + return $level->toRFC5424Level(); + } /** * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant */ - public function __construct($facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(string|int $facility = \LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); if (!defined('PHP_WINDOWS_VERSION_BUILD')) { - $this->facilities['local0'] = LOG_LOCAL0; - $this->facilities['local1'] = LOG_LOCAL1; - $this->facilities['local2'] = LOG_LOCAL2; - $this->facilities['local3'] = LOG_LOCAL3; - $this->facilities['local4'] = LOG_LOCAL4; - $this->facilities['local5'] = LOG_LOCAL5; - $this->facilities['local6'] = LOG_LOCAL6; - $this->facilities['local7'] = LOG_LOCAL7; + $this->facilities['local0'] = \LOG_LOCAL0; + $this->facilities['local1'] = \LOG_LOCAL1; + $this->facilities['local2'] = \LOG_LOCAL2; + $this->facilities['local3'] = \LOG_LOCAL3; + $this->facilities['local4'] = \LOG_LOCAL4; + $this->facilities['local5'] = \LOG_LOCAL5; + $this->facilities['local6'] = \LOG_LOCAL6; + $this->facilities['local7'] = \LOG_LOCAL7; } else { $this->facilities['local0'] = 128; // LOG_LOCAL0 $this->facilities['local1'] = 136; // LOG_LOCAL1 @@ -97,7 +86,7 @@ public function __construct($facility = LOG_USER, $level = Logger::DEBUG, bool $ } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php index 994872c..72265d4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php @@ -11,24 +11,38 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\JsonFormatter; use PhpAmqpLib\Message\AMQPMessage; use PhpAmqpLib\Channel\AMQPChannel; use AMQPExchange; +use Monolog\LogRecord; -/** - * @phpstan-import-type Record from \Monolog\Logger - */ class AmqpHandler extends AbstractProcessingHandler { + protected AMQPExchange|AMQPChannel $exchange; + + /** @var array */ + private array $extraAttributes = []; + + protected string $exchangeName; + /** - * @var AMQPExchange|AMQPChannel $exchange + * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use + * @param string|null $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only */ - protected $exchange; - /** @var array */ - private $extraAttributes = []; + public function __construct(AMQPExchange|AMQPChannel $exchange, ?string $exchangeName = null, int|string|Level $level = Level::Debug, bool $bubble = true) + { + if ($exchange instanceof AMQPChannel) { + $this->exchangeName = (string) $exchangeName; + } elseif ($exchangeName !== null) { + @trigger_error('The $exchangeName parameter can only be passed when using PhpAmqpLib, if using an AMQPExchange instance configure it beforehand', E_USER_DEPRECATED); + } + $this->exchange = $exchange; + + parent::__construct($level, $bubble); + } /** * @return array @@ -45,7 +59,7 @@ public function getExtraAttributes(): array * message_id, user_id, app_id, delivery_mode, * priority, timestamp, expiration, type * or reply_to, headers. - * @return AmqpHandler + * @return $this */ public function setExtraAttributes(array $extraAttributes): self { @@ -54,34 +68,11 @@ public function setExtraAttributes(array $extraAttributes): self } /** - * @var string + * @inheritDoc */ - protected $exchangeName; - - /** - * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use - * @param string|null $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only - */ - public function __construct($exchange, ?string $exchangeName = null, $level = Logger::DEBUG, bool $bubble = true) + protected function write(LogRecord $record): void { - if ($exchange instanceof AMQPChannel) { - $this->exchangeName = (string) $exchangeName; - } elseif (!$exchange instanceof AMQPExchange) { - throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required'); - } elseif ($exchangeName) { - @trigger_error('The $exchangeName parameter can only be passed when using PhpAmqpLib, if using an AMQPExchange instance configure it beforehand', E_USER_DEPRECATED); - } - $this->exchange = $exchange; - - parent::__construct($level, $bubble); - } - - /** - * {@inheritDoc} - */ - protected function write(array $record): void - { - $data = $record["formatted"]; + $data = $record->formatted; $routingKey = $this->getRoutingKey($record); if ($this->exchange instanceof AMQPExchange) { @@ -89,7 +80,7 @@ protected function write(array $record): void 'delivery_mode' => 2, 'content_type' => 'application/json', ]; - if ($this->extraAttributes) { + if (\count($this->extraAttributes) > 0) { $attributes = array_merge($attributes, $this->extraAttributes); } $this->exchange->publish( @@ -108,7 +99,7 @@ protected function write(array $record): void } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { @@ -123,7 +114,6 @@ public function handleBatch(array $records): void continue; } - /** @var Record $record */ $record = $this->processRecord($record); $data = $this->getFormatter()->format($record); @@ -139,12 +129,10 @@ public function handleBatch(array $records): void /** * Gets the routing key for the AMQP exchange - * - * @phpstan-param Record $record */ - protected function getRoutingKey(array $record): string + protected function getRoutingKey(LogRecord $record): string { - $routingKey = sprintf('%s.%s', $record['level_name'], $record['channel']); + $routingKey = sprintf('%s.%s', $record->level->name, $record->channel); return strtolower($routingKey); } @@ -155,14 +143,14 @@ private function createAmqpMessage(string $data): AMQPMessage 'delivery_mode' => 2, 'content_type' => 'application/json', ]; - if ($this->extraAttributes) { + if (\count($this->extraAttributes) > 0) { $attributes = array_merge($attributes, $this->extraAttributes); } return new AMQPMessage($data, $attributes); } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php index 95bbfed..5930ca4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php @@ -14,35 +14,31 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; use Monolog\Utils; -use Monolog\Logger; +use Monolog\LogRecord; +use Monolog\Level; use function count; use function headers_list; use function stripos; -use function trigger_error; - -use const E_USER_DEPRECATED; /** * Handler sending logs to browser's javascript console with no browser extension required * * @author Olivier Poitrey - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class BrowserConsoleHandler extends AbstractProcessingHandler { - /** @var bool */ - protected static $initialized = false; - /** @var FormattedRecord[] */ - protected static $records = []; + protected static bool $initialized = false; + + /** @var LogRecord[] */ + protected static array $records = []; protected const FORMAT_HTML = 'html'; protected const FORMAT_JS = 'js'; protected const FORMAT_UNKNOWN = 'unknown'; /** - * {@inheritDoc} + * @inheritDoc * * Formatted output may contain some formatting markers to be transferred to `console.log` using the %c format. * @@ -56,9 +52,9 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { // Accumulate records static::$records[] = $record; @@ -81,11 +77,11 @@ public static function send(): void return; } - if (count(static::$records)) { + if (count(static::$records) > 0) { if ($format === self::FORMAT_HTML) { - static::writeOutput(''); - } elseif ($format === self::FORMAT_JS) { - static::writeOutput(static::generateScript()); + static::writeOutput(''); + } else { // js format + static::writeOutput(self::generateScript()); } static::resetStatic(); } @@ -96,7 +92,7 @@ public function close(): void self::resetStatic(); } - public function reset() + public function reset(): void { parent::reset(); @@ -174,18 +170,18 @@ private static function generateScript(): string { $script = []; foreach (static::$records as $record) { - $context = static::dump('Context', $record['context']); - $extra = static::dump('Extra', $record['extra']); + $context = self::dump('Context', $record->context); + $extra = self::dump('Extra', $record->extra); - if (empty($context) && empty($extra)) { - $script[] = static::call_array(static::getConsoleMethodForLevel($record['level']), static::handleStyles($record['formatted'])); + if (\count($context) === 0 && \count($extra) === 0) { + $script[] = self::call_array(self::getConsoleMethodForLevel($record->level), self::handleStyles($record->formatted)); } else { $script = array_merge( $script, - [static::call_array('groupCollapsed', static::handleStyles($record['formatted']))], + [self::call_array('groupCollapsed', self::handleStyles($record->formatted))], $context, $extra, - [static::call('groupEnd')] + [self::call('groupEnd')] ); } } @@ -193,18 +189,14 @@ private static function generateScript(): string return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);"; } - private static function getConsoleMethodForLevel(int $level): string + private static function getConsoleMethodForLevel(Level $level): string { - return [ - Logger::DEBUG => 'debug', - Logger::INFO => 'info', - Logger::NOTICE => 'info', - Logger::WARNING => 'warn', - Logger::ERROR => 'error', - Logger::CRITICAL => 'error', - Logger::ALERT => 'error', - Logger::EMERGENCY => 'error', - ][$level] ?? 'log'; + return match ($level) { + Level::Debug => 'debug', + Level::Info, Level::Notice => 'info', + Level::Warning => 'warn', + Level::Error, Level::Critical, Level::Alert, Level::Emergency => 'error', + }; } /** @@ -218,14 +210,14 @@ private static function handleStyles(string $formatted): array foreach (array_reverse($matches) as $match) { $args[] = '"font-weight: normal"'; - $args[] = static::quote(static::handleCustomStyles($match[2][0], $match[1][0])); + $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0])); $pos = $match[0][1]; $format = Utils::substr($format, 0, $pos) . '%c' . $match[1][0] . '%c' . Utils::substr($format, $pos + strlen($match[0][0])); } - $args[] = static::quote('font-weight: normal'); - $args[] = static::quote($format); + $args[] = self::quote('font-weight: normal'); + $args[] = self::quote($format); return array_reverse($args); } @@ -251,6 +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)); } @@ -265,16 +258,16 @@ private static function dump(string $title, array $dict): array { $script = []; $dict = array_filter($dict); - if (empty($dict)) { + if (\count($dict) === 0) { return $script; } - $script[] = static::call('log', static::quote('%c%s'), static::quote('font-weight: bold'), static::quote($title)); + $script[] = self::call('log', self::quote('%c%s'), self::quote('font-weight: bold'), self::quote($title)); foreach ($dict as $key => $value) { $value = json_encode($value); - if (empty($value)) { - $value = static::quote(''); + if (false === $value) { + $value = self::quote(''); } - $script[] = static::call('log', static::quote('%s: %o'), static::quote((string) $key), $value); + $script[] = self::call('log', self::quote('%s: %o'), self::quote((string) $key), $value); } return $script; @@ -295,7 +288,7 @@ private static function call(...$args): string throw new \UnexpectedValueException('Expected the first arg to be a string, got: '.var_export($method, true)); } - return static::call_array($method, $args); + return self::call_array($method, $args); } /** diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php index fcce5d6..ff89faa 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php @@ -11,9 +11,10 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Buffers all records until closing the handler and then pass them as batch. @@ -22,32 +23,30 @@ * sending one per log message. * * @author Christophe Coevoet - * - * @phpstan-import-type Record from \Monolog\Logger */ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface { use ProcessableHandlerTrait; - /** @var HandlerInterface */ - protected $handler; - /** @var int */ - protected $bufferSize = 0; - /** @var int */ - protected $bufferLimit; - /** @var bool */ - protected $flushOnOverflow; - /** @var Record[] */ - protected $buffer = []; - /** @var bool */ - protected $initialized = false; + protected HandlerInterface $handler; + + protected int $bufferSize = 0; + + protected int $bufferLimit; + + protected bool $flushOnOverflow; + + /** @var LogRecord[] */ + protected array $buffer = []; + + protected bool $initialized = false; /** * @param HandlerInterface $handler Handler. * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. * @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded */ - public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, bool $flushOnOverflow = false) + public function __construct(HandlerInterface $handler, int $bufferLimit = 0, int|string|Level $level = Level::Debug, bool $bubble = true, bool $flushOnOverflow = false) { parent::__construct($level, $bubble); $this->handler = $handler; @@ -56,11 +55,11 @@ public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $le } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - if ($record['level'] < $this->level) { + if ($record->level->isLowerThan($this->level)) { return false; } @@ -79,8 +78,7 @@ public function handle(array $record): bool } } - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } @@ -108,7 +106,7 @@ public function __destruct() } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { @@ -126,7 +124,7 @@ public function clear(): void $this->buffer = []; } - public function reset() + public function reset(): void { $this->flush(); @@ -140,7 +138,7 @@ public function reset() } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -154,7 +152,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php index 234ecf6..2f7f21d 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php @@ -13,8 +13,10 @@ use Monolog\Formatter\ChromePHPFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; +use Monolog\DateTimeImmutable; /** * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/) @@ -22,8 +24,6 @@ * This also works out of the box with Firefox 43+ * * @author Christophe Coevoet - * - * @phpstan-import-type Record from \Monolog\Logger */ class ChromePHPHandler extends AbstractProcessingHandler { @@ -44,29 +44,28 @@ class ChromePHPHandler extends AbstractProcessingHandler */ protected const USER_AGENT_REGEX = '{\b(?:Chrome/\d+(?:\.\d+)*|HeadlessChrome|Firefox/(?:4[3-9]|[5-9]\d|\d{3,})(?:\.\d)*)\b}'; - /** @var bool */ - protected static $initialized = false; + protected static bool $initialized = false; /** * Tracks whether we sent too much data * * Chrome limits the headers to 4KB, so when we sent 3KB we stop sending - * - * @var bool */ - protected static $overflowed = false; + protected static bool $overflowed = false; /** @var mixed[] */ - protected static $json = [ + protected static array $json = [ 'version' => self::VERSION, 'columns' => ['label', 'log', 'backtrace', 'type'], 'rows' => [], ]; - /** @var bool */ - protected static $sendHeaders = true; + protected static bool $sendHeaders = true; - public function __construct($level = Logger::DEBUG, bool $bubble = true) + /** + * @throws \RuntimeException If the function json_encode does not exist + */ + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); if (!function_exists('json_encode')) { @@ -75,7 +74,7 @@ public function __construct($level = Logger::DEBUG, bool $bubble = true) } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { @@ -86,15 +85,15 @@ public function handleBatch(array $records): void $messages = []; foreach ($records as $record) { - if ($record['level'] < $this->level) { + if ($record->level < $this->level) { continue; } - /** @var Record $message */ + $message = $this->processRecord($record); $messages[] = $message; } - if (!empty($messages)) { + if (\count($messages) > 0) { $messages = $this->getFormatter()->formatBatch($messages); self::$json['rows'] = array_merge(self::$json['rows'], $messages); $this->send(); @@ -102,7 +101,7 @@ public function handleBatch(array $records): void } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { @@ -115,13 +114,13 @@ protected function getDefaultFormatter(): FormatterInterface * @see sendHeader() * @see send() */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!$this->isWebRequest()) { return; } - self::$json['rows'][] = $record['formatted']; + self::$json['rows'][] = $record->formatted; $this->send(); } @@ -153,15 +152,12 @@ protected function send(): void if (strlen($data) > 3 * 1024) { self::$overflowed = true; - $record = [ - 'message' => 'Incomplete logs, chrome header size limit reached', - 'context' => [], - 'level' => Logger::WARNING, - 'level_name' => Logger::getLevelName(Logger::WARNING), - 'channel' => 'monolog', - 'datetime' => new \DateTimeImmutable(), - 'extra' => [], - ]; + $record = new LogRecord( + message: 'Incomplete logs, chrome header size limit reached', + level: Level::Warning, + channel: 'monolog', + datetime: new DateTimeImmutable(true), + ); self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record); $json = Utils::jsonEncode(self::$json, Utils::DEFAULT_JSON_FLAGS & ~JSON_UNESCAPED_UNICODE, true); $data = base64_encode($json); @@ -187,7 +183,7 @@ protected function sendHeader(string $header, string $content): void */ protected function headersAccepted(): bool { - if (empty($_SERVER['HTTP_USER_AGENT'])) { + if (!isset($_SERVER['HTTP_USER_AGENT'])) { return false; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php index 5265761..8d9c10e 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php @@ -13,22 +13,42 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\JsonFormatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * CouchDB handler * * @author Markus Bachmann + * @phpstan-type Options array{ + * host: string, + * port: int, + * dbname: string, + * username: string|null, + * password: string|null + * } + * @phpstan-type InputOptions array{ + * host?: string, + * port?: int, + * dbname?: string, + * username?: string|null, + * password?: string|null + * } */ class CouchDBHandler extends AbstractProcessingHandler { - /** @var mixed[] */ - private $options; + /** + * @var mixed[] + * @phpstan-var Options + */ + private array $options; /** * @param mixed[] $options + * + * @phpstan-param InputOptions $options */ - public function __construct(array $options = [], $level = Logger::DEBUG, bool $bubble = true) + public function __construct(array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) { $this->options = array_merge([ 'host' => 'localhost', @@ -42,12 +62,12 @@ public function __construct(array $options = [], $level = Logger::DEBUG, bool $b } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { $basicAuth = null; - if ($this->options['username']) { + if (null !== $this->options['username'] && null !== $this->options['password']) { $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']); } @@ -55,7 +75,7 @@ protected function write(array $record): void $context = stream_context_create([ 'http' => [ 'method' => 'POST', - 'content' => $record['formatted'], + 'content' => $record->formatted, 'ignore_errors' => true, 'max_redirects' => 0, 'header' => 'Content-type: application/json', @@ -68,7 +88,7 @@ protected function write(array $record): void } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php index 3535a4f..8388f5a 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Logs to Cube. @@ -23,18 +24,13 @@ */ class CubeHandler extends AbstractProcessingHandler { - /** @var resource|\Socket|null */ - private $udpConnection = null; - /** @var resource|\CurlHandle|null */ - private $httpConnection = null; - /** @var string */ - private $scheme; - /** @var string */ - private $host; - /** @var int */ - private $port; + private ?\Socket $udpConnection = null; + private ?\CurlHandle $httpConnection = null; + private string $scheme; + private string $host; + private int $port; /** @var string[] */ - private $acceptedSchemes = ['http', 'udp']; + private array $acceptedSchemes = ['http', 'udp']; /** * Create a Cube handler @@ -43,7 +39,7 @@ class CubeHandler extends AbstractProcessingHandler * A valid url must consist of three parts : protocol://host:port * Only valid protocols used by Cube are http and udp */ - public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(string $url, int|string|Level $level = Level::Debug, bool $bubble = true) { $urlInfo = parse_url($url); @@ -51,7 +47,7 @@ public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = throw new \UnexpectedValueException('URL "'.$url.'" is not valid'); } - if (!in_array($urlInfo['scheme'], $this->acceptedSchemes)) { + if (!in_array($urlInfo['scheme'], $this->acceptedSchemes, true)) { throw new \UnexpectedValueException( 'Invalid protocol (' . $urlInfo['scheme'] . ').' . ' Valid options are ' . implode(', ', $this->acceptedSchemes) @@ -60,7 +56,7 @@ public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = $this->scheme = $urlInfo['scheme']; $this->host = $urlInfo['host']; - $this->port = (int) $urlInfo['port']; + $this->port = $urlInfo['port']; parent::__construct($level, $bubble); } @@ -111,24 +107,24 @@ protected function connectHttp(): void } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $date = $record['datetime']; + $date = $record->datetime; $data = ['time' => $date->format('Y-m-d\TH:i:s.uO')]; - unset($record['datetime']); + $context = $record->context; - if (isset($record['context']['type'])) { - $data['type'] = $record['context']['type']; - unset($record['context']['type']); + if (isset($context['type'])) { + $data['type'] = $context['type']; + unset($context['type']); } else { - $data['type'] = $record['channel']; + $data['type'] = $record->channel; } - $data['data'] = $record['context']; - $data['data']['level'] = $record['level']; + $data['data'] = $context; + $data['data']['level'] = $record->level; if ($this->scheme === 'http') { $this->writeHttp(Utils::jsonEncode($data)); @@ -139,16 +135,20 @@ protected function write(array $record): void private function writeUdp(string $data): void { - if (!$this->udpConnection) { + if (null === $this->udpConnection) { $this->connectUdp(); } + if (null === $this->udpConnection) { + throw new \LogicException('No UDP socket could be opened'); + } + socket_send($this->udpConnection, $data, strlen($data), 0); } private function writeHttp(string $data): void { - if (!$this->httpConnection) { + if (null === $this->httpConnection) { $this->connectHttp(); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php index 7213e8e..4decf0e 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php @@ -21,7 +21,7 @@ final class Util { /** @var array */ - private static $retriableErrorCodes = [ + private static array $retriableErrorCodes = [ CURLE_COULDNT_RESOLVE_HOST, CURLE_COULDNT_CONNECT, CURLE_HTTP_NOT_FOUND, @@ -34,19 +34,17 @@ final class Util /** * Executes a CURL request with optional retries and exception on failure * - * @param resource|CurlHandle $ch curl handler - * @param int $retries - * @param bool $closeAfterDone - * @return bool|string @see curl_exec + * @param CurlHandle $ch curl handler + * @return bool|string @see curl_exec */ - public static function execute($ch, int $retries = 5, bool $closeAfterDone = true) + public static function execute(CurlHandle $ch, int $retries = 5, bool $closeAfterDone = true) { while ($retries--) { $curlResponse = curl_exec($ch); if ($curlResponse === false) { $curlErrno = curl_errno($ch); - if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) { + if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || $retries === 0) { $curlError = curl_error($ch); if ($closeAfterDone) { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php index 9b85ae7..b8ec900 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php @@ -11,8 +11,10 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Simple handler wrapper that deduplicates log records across multiple requests @@ -33,45 +35,29 @@ * same way. * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ class DeduplicationHandler extends BufferHandler { - /** - * @var string - */ - protected $deduplicationStore; + protected string $deduplicationStore; - /** - * @var Level - */ - protected $deduplicationLevel; + protected Level $deduplicationLevel; - /** - * @var int - */ - protected $time; + protected int $time; - /** - * @var bool - */ - private $gc = false; + private bool $gc = false; /** - * @param HandlerInterface $handler Handler. - * @param string $deduplicationStore The file/path where the deduplication log should be kept - * @param string|int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes - * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through - * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param HandlerInterface $handler Handler. + * @param string|null $deduplicationStore The file/path where the deduplication log should be kept + * @param int|string|Level|LogLevel::* $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes + * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not * - * @phpstan-param Level|LevelName|LogLevel::* $deduplicationLevel + * @phpstan-param value-of|value-of|Level|LogLevel::* $deduplicationLevel */ - public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, int $time = 60, bool $bubble = true) + public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, int|string|Level $deduplicationLevel = Level::Error, int $time = 60, bool $bubble = true) { - parent::__construct($handler, 0, Logger::DEBUG, $bubble, false); + parent::__construct($handler, 0, Level::Debug, $bubble, false); $this->deduplicationStore = $deduplicationStore === null ? sys_get_temp_dir() . '/monolog-dedup-' . substr(md5(__FILE__), 0, 20) .'.log' : $deduplicationStore; $this->deduplicationLevel = Logger::toMonologLevel($deduplicationLevel); @@ -87,8 +73,8 @@ public function flush(): void $passthru = null; foreach ($this->buffer as $record) { - if ($record['level'] >= $this->deduplicationLevel) { - $passthru = $passthru || !$this->isDuplicate($record); + if ($record->level->value >= $this->deduplicationLevel->value) { + $passthru = $passthru === true || !$this->isDuplicate($record); if ($passthru) { $this->appendRecord($record); } @@ -107,10 +93,7 @@ public function flush(): void } } - /** - * @phpstan-param Record $record - */ - private function isDuplicate(array $record): bool + private function isDuplicate(LogRecord $record): bool { if (!file_exists($this->deduplicationStore)) { return false; @@ -122,13 +105,13 @@ private function isDuplicate(array $record): bool } $yesterday = time() - 86400; - $timestampValidity = $record['datetime']->getTimestamp() - $this->time; - $expectedMessage = preg_replace('{[\r\n].*}', '', $record['message']); + $timestampValidity = $record->datetime->getTimestamp() - $this->time; + $expectedMessage = preg_replace('{[\r\n].*}', '', $record->message); for ($i = count($store) - 1; $i >= 0; $i--) { list($timestamp, $level, $message) = explode(':', $store[$i], 3); - if ($level === $record['level_name'] && $message === $expectedMessage && $timestamp > $timestampValidity) { + if ($level === $record->level->getName() && $message === $expectedMessage && $timestamp > $timestampValidity) { return true; } @@ -148,7 +131,7 @@ private function collectLogs(): void $handle = fopen($this->deduplicationStore, 'rw+'); - if (!$handle) { + if (false === $handle) { throw new \RuntimeException('Failed to open file for reading and writing: ' . $this->deduplicationStore); } @@ -159,7 +142,7 @@ private function collectLogs(): void while (!feof($handle)) { $log = fgets($handle); - if ($log && substr($log, 0, 10) >= $timestampValidity) { + if (is_string($log) && '' !== $log && substr($log, 0, 10) >= $timestampValidity) { $validLogs[] = $log; } } @@ -176,11 +159,8 @@ private function collectLogs(): void $this->gc = false; } - /** - * @phpstan-param Record $record - */ - private function appendRecord(array $record): void + private function appendRecord(LogRecord $record): void { - file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND); + file_put_contents($this->deduplicationStore, $record->datetime->getTimestamp() . ':' . $record->level->getName() . ':' . preg_replace('{[\r\n].*}', '', $record->message) . "\n", FILE_APPEND); } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php index ebd52c3..eab9f10 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php @@ -11,10 +11,11 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; use Doctrine\CouchDB\CouchDBClient; +use Monolog\LogRecord; /** * CouchDB handler for Doctrine CouchDB ODM @@ -23,21 +24,20 @@ */ class DoctrineCouchDBHandler extends AbstractProcessingHandler { - /** @var CouchDBClient */ - private $client; + private CouchDBClient $client; - public function __construct(CouchDBClient $client, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(CouchDBClient $client, int|string|Level $level = Level::Debug, bool $bubble = true) { $this->client = $client; parent::__construct($level, $bubble); } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->client->postDocument($record['formatted']); + $this->client->postDocument($record->formatted); } protected function getDefaultFormatter(): FormatterInterface diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php index 21840bf..f1c5a95 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php @@ -16,7 +16,8 @@ use Monolog\Formatter\FormatterInterface; use Aws\DynamoDb\Marshaler; use Monolog\Formatter\ScalarFormatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/) @@ -28,35 +29,15 @@ class DynamoDbHandler extends AbstractProcessingHandler { public const DATE_FORMAT = 'Y-m-d\TH:i:s.uO'; - /** - * @var DynamoDbClient - */ - protected $client; + protected DynamoDbClient $client; - /** - * @var string - */ - protected $table; + protected string $table; - /** - * @var int - */ - protected $version; - - /** - * @var Marshaler - */ - protected $marshaler; + protected Marshaler $marshaler; - public function __construct(DynamoDbClient $client, string $table, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(DynamoDbClient $client, string $table, int|string|Level $level = Level::Debug, bool $bubble = true) { - /** @phpstan-ignore-next-line */ - if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) { - $this->version = 3; - $this->marshaler = new Marshaler; - } else { - $this->version = 2; - } + $this->marshaler = new Marshaler; $this->client = $client; $this->table = $table; @@ -65,17 +46,12 @@ public function __construct(DynamoDbClient $client, string $table, $level = Logg } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $filtered = $this->filterEmptyFields($record['formatted']); - if ($this->version === 3) { - $formatted = $this->marshaler->marshalItem($filtered); - } else { - /** @phpstan-ignore-next-line */ - $formatted = $this->client->formatAttributes($filtered); - } + $filtered = $this->filterEmptyFields($record->formatted); + $formatted = $this->marshaler->marshalItem($filtered); $this->client->putItem([ 'TableName' => $this->table, @@ -90,12 +66,12 @@ protected function write(array $record): void protected function filterEmptyFields(array $record): array { return array_filter($record, function ($value) { - return !empty($value) || false === $value || 0 === $value; + return [] !== $value; }); } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php index fc92ca4..d9b85b4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php @@ -14,9 +14,10 @@ use Elastica\Document; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\ElasticaFormatter; -use Monolog\Logger; +use Monolog\Level; use Elastica\Client; use Elastica\Exception\ExceptionInterface; +use Monolog\LogRecord; /** * Elastic Search handler @@ -33,24 +34,34 @@ * $log->pushHandler($handler); * * @author Jelle Vink + * @phpstan-type Options array{ + * index: string, + * type: string, + * ignore_error: bool + * } + * @phpstan-type InputOptions array{ + * index?: string, + * type?: string, + * ignore_error?: bool + * } */ class ElasticaHandler extends AbstractProcessingHandler { - /** - * @var Client - */ - protected $client; + protected Client $client; /** * @var mixed[] Handler config options + * @phpstan-var Options */ - protected $options = []; + protected array $options; /** * @param Client $client Elastica Client object * @param mixed[] $options Handler configuration + * + * @phpstan-param InputOptions $options */ - public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) + public function __construct(Client $client, array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); $this->client = $client; @@ -65,15 +76,15 @@ public function __construct(Client $client, array $options = [], $level = Logger } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->bulkSend([$record['formatted']]); + $this->bulkSend([$record->formatted]); } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -86,6 +97,8 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface /** * @return mixed[] + * + * @phpstan-return Options */ public function getOptions(): array { @@ -93,7 +106,7 @@ public function getOptions(): array } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { @@ -101,7 +114,7 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php index e88375c..74cc7b6 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php @@ -14,12 +14,13 @@ use Elastic\Elasticsearch\Response\Elasticsearch; use Throwable; use RuntimeException; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\ElasticsearchFormatter; use InvalidArgumentException; use Elasticsearch\Common\Exceptions\RuntimeException as ElasticsearchRuntimeException; use Elasticsearch\Client; +use Monolog\LogRecord; use Elastic\Elasticsearch\Exception\InvalidArgumentException as ElasticInvalidArgumentException; use Elastic\Elasticsearch\Client as Client8; @@ -43,18 +44,28 @@ * $log->pushHandler($handler); * * @author Avtandil Kikabidze + * @phpstan-type Options array{ + * index: string, + * type: string, + * ignore_error: bool, + * op_type: 'index'|'create' + * } + * @phpstan-type InputOptions array{ + * index?: string, + * type?: string, + * ignore_error?: bool, + * op_type?: 'index'|'create' + * } */ class ElasticsearchHandler extends AbstractProcessingHandler { - /** - * @var Client|Client8 - */ - protected $client; + protected Client|Client8 $client; /** * @var mixed[] Handler config options + * @phpstan-var Options */ - protected $options = []; + protected array $options; /** * @var bool @@ -64,13 +75,11 @@ class ElasticsearchHandler extends AbstractProcessingHandler /** * @param Client|Client8 $client Elasticsearch Client object * @param mixed[] $options Handler configuration + * + * @phpstan-param InputOptions $options */ - public function __construct($client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) + public function __construct(Client|Client8 $client, array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) { - if (!$client instanceof Client && !$client instanceof Client8) { - throw new \TypeError('Elasticsearch\Client or Elastic\Elasticsearch\Client instance required'); - } - parent::__construct($level, $bubble); $this->client = $client; $this->options = array_merge( @@ -78,6 +87,7 @@ public function __construct($client, array $options = [], $level = Logger::DEBUG 'index' => 'monolog', // Elastic index name 'type' => '_doc', // Elastic document type 'ignore_error' => false, // Suppress Elasticsearch exceptions + 'op_type' => 'index', // Elastic op_type (index or create) (https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#docs-index-api-op_type) ], $options ); @@ -92,15 +102,15 @@ public function __construct($client, array $options = [], $level = Logger::DEBUG } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->bulkSend([$record['formatted']]); + $this->bulkSend([$record->formatted]); } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -115,6 +125,8 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface * Getter options * * @return mixed[] + * + * @phpstan-return Options */ public function getOptions(): array { @@ -122,7 +134,7 @@ public function getOptions(): array } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { @@ -130,7 +142,7 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { @@ -141,7 +153,7 @@ public function handleBatch(array $records): void /** * Use Elasticsearch bulk API to send list of documents * - * @param array[] $records Records + _index/_type keys + * @param array> $records Records + _index/_type keys * @throws \RuntimeException */ protected function bulkSend(array $records): void @@ -153,7 +165,7 @@ protected function bulkSend(array $records): void foreach ($records as $record) { $params['body'][] = [ - 'index' => $this->needsType ? [ + $this->options['op_type'] => $this->needsType ? [ '_index' => $record['_index'], '_type' => $record['_type'], ] : [ diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php index f2e2203..571c439 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php @@ -13,8 +13,9 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Stores to PHP error_log() handler. @@ -26,16 +27,16 @@ class ErrorLogHandler extends AbstractProcessingHandler public const OPERATING_SYSTEM = 0; public const SAPI = 4; - /** @var int */ - protected $messageType; - /** @var bool */ - protected $expandNewlines; + protected int $messageType; + protected bool $expandNewlines; /** * @param int $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 */ - public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, bool $expandNewlines = false) + public function __construct(int $messageType = self::OPERATING_SYSTEM, int|string|Level $level = Level::Debug, bool $bubble = true, bool $expandNewlines = false) { parent::__construct($level, $bubble); @@ -61,7 +62,7 @@ public static function getAvailableTypes(): array } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { @@ -69,19 +70,20 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!$this->expandNewlines) { - error_log((string) $record['formatted'], $this->messageType); + error_log((string) $record->formatted, $this->messageType); return; } - $lines = preg_split('{[\r\n]+}', (string) $record['formatted']); + $lines = preg_split('{[\r\n]+}', (string) $record->formatted); if ($lines === false) { $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to preg_split formatted string: ' . $pcreErrorCode . ' / '. Utils::pcreLastErrorMessage($pcreErrorCode)); } foreach ($lines as $line) { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php index d4e234c..1776eb5 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php @@ -12,6 +12,7 @@ namespace Monolog\Handler; use Throwable; +use Monolog\LogRecord; /** * Forwards records to at most one handler @@ -19,18 +20,15 @@ * If a handler fails, the exception is suppressed and the record is forwarded to the next handler. * * As soon as one handler handles a record successfully, the handling stops there. - * - * @phpstan-import-type Record from \Monolog\Logger */ class FallbackGroupHandler extends GroupHandler { /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } foreach ($this->handlers as $handler) { @@ -46,16 +44,15 @@ public function handle(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { - if ($this->processors) { + if (\count($this->processors) > 0) { $processed = []; foreach ($records as $record) { $processed[] = $this->processRecord($record); } - /** @var Record[] $records */ $records = $processed; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php index 718f17e..00381ab 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php @@ -11,10 +11,13 @@ namespace Monolog\Handler; +use Closure; +use Monolog\Level; use Monolog\Logger; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Simple handler wrapper that filters records based on a list of levels @@ -23,110 +26,99 @@ * * @author Hennadiy Verkh * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class FilterHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface { use ProcessableHandlerTrait; /** - * Handler or factory callable($record, $this) + * Handler or factory Closure($record, $this) * - * @var callable|HandlerInterface - * @phpstan-var callable(?Record, HandlerInterface): HandlerInterface|HandlerInterface + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface */ - protected $handler; + protected Closure|HandlerInterface $handler; /** * Minimum level for logs that are passed to handler * - * @var int[] - * @phpstan-var array + * @var bool[] Map of Level value => true + * @phpstan-var array, true> */ - protected $acceptedLevels; + protected array $acceptedLevels; /** * Whether the messages that are handled can bubble up the stack or not - * - * @var bool */ - protected $bubble; + protected bool $bubble; /** - * @psalm-param HandlerInterface|callable(?Record, HandlerInterface): HandlerInterface $handler + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler * - * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $filterHandler). - * @param int|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided - * @param int|string $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array - * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $filterHandler). + * @param int|string|Level|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided + * @param int|string|Level|LogLevel::* $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not * - * @phpstan-param Level|LevelName|LogLevel::*|array $minLevelOrList - * @phpstan-param Level|LevelName|LogLevel::* $maxLevel + * @phpstan-param value-of|value-of|Level|LogLevel::*|array|value-of|Level|LogLevel::*> $minLevelOrList + * @phpstan-param value-of|value-of|Level|LogLevel::* $maxLevel */ - public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, bool $bubble = true) + public function __construct(Closure|HandlerInterface $handler, int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency, bool $bubble = true) { $this->handler = $handler; $this->bubble = $bubble; $this->setAcceptedLevels($minLevelOrList, $maxLevel); - - if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { - throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); - } } /** - * @phpstan-return array + * @phpstan-return list List of levels */ public function getAcceptedLevels(): array { - return array_flip($this->acceptedLevels); + return array_map(fn (int $level) => Level::from($level), array_keys($this->acceptedLevels)); } /** - * @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided - * @param int|string $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array + * @param int|string|Level|LogLevel::*|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided + * @param int|string|Level|LogLevel::* $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array * - * @phpstan-param Level|LevelName|LogLevel::*|array $minLevelOrList - * @phpstan-param Level|LevelName|LogLevel::* $maxLevel + * @phpstan-param value-of|value-of|Level|LogLevel::*|array|value-of|Level|LogLevel::*> $minLevelOrList + * @phpstan-param value-of|value-of|Level|LogLevel::* $maxLevel */ - public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY): self + public function setAcceptedLevels(int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency): self { if (is_array($minLevelOrList)) { - $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); + $acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList); } else { $minLevelOrList = Logger::toMonologLevel($minLevelOrList); $maxLevel = Logger::toMonologLevel($maxLevel); - $acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) { - return $level >= $minLevelOrList && $level <= $maxLevel; - })); + $acceptedLevels = array_values(array_filter(Level::cases(), fn (Level $level) => $level->value >= $minLevelOrList->value && $level->value <= $maxLevel->value)); + } + $this->acceptedLevels = []; + foreach ($acceptedLevels as $level) { + $this->acceptedLevels[$level->value] = true; } - $this->acceptedLevels = array_flip($acceptedLevels); return $this; } /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { - return isset($this->acceptedLevels[$record['level']]); + return isset($this->acceptedLevels[$record->level->value]); } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { if (!$this->isHandling($record)) { return false; } - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } @@ -136,7 +128,7 @@ public function handle(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { @@ -155,26 +147,23 @@ public function handleBatch(array $records): void /** * Return the nested handler * - * If the handler was provided as a factory callable, this will trigger the handler's instantiation. - * - * @return HandlerInterface - * - * @phpstan-param Record $record + * If the handler was provided as a factory, this will trigger the handler's instantiation. */ - public function getHandler(array $record = null) + public function getHandler(LogRecord $record = null): HandlerInterface { if (!$this->handler instanceof HandlerInterface) { - $this->handler = ($this->handler)($record, $this); - if (!$this->handler instanceof HandlerInterface) { - throw new \RuntimeException("The factory callable should return a HandlerInterface"); + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); } + $this->handler = $handler; } return $this->handler; } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -189,7 +178,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { @@ -201,7 +190,7 @@ public function getFormatter(): FormatterInterface throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); } - public function reset() + public function reset(): void { $this->resetProcessors(); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php index 0aa5607..e8a1b0b 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php @@ -11,19 +11,17 @@ namespace Monolog\Handler\FingersCrossed; +use Monolog\LogRecord; + /** * Interface for activation strategies for the FingersCrossedHandler. * * @author Johannes M. Schmitt - * - * @phpstan-import-type Record from \Monolog\Logger */ interface ActivationStrategyInterface { /** * Returns whether the given record activates the handler. - * - * @phpstan-param Record $record */ - public function isHandlerActivated(array $record): bool; + public function isHandlerActivated(LogRecord $record): bool; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php index 7b9abb5..383e19a 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php @@ -11,8 +11,10 @@ namespace Monolog\Handler\FingersCrossed; +use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Channel and Error level based monolog activation strategy. Allows to trigger activation @@ -23,55 +25,45 @@ * * * $activationStrategy = new ChannelLevelActivationStrategy( - * Logger::CRITICAL, + * Level::Critical, * array( - * 'request' => Logger::ALERT, - * 'sensitive' => Logger::ERROR, + * 'request' => Level::Alert, + * 'sensitive' => Level::Error, * ) * ); * $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy); * * * @author Mike Meessen - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class ChannelLevelActivationStrategy implements ActivationStrategyInterface { - /** - * @var Level - */ - private $defaultActionLevel; + private Level $defaultActionLevel; /** * @var array */ - private $channelToActionLevel; + private array $channelToActionLevel; /** - * @param int|string $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 int|string|Level|LogLevel::* $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. * - * @phpstan-param array $channelToActionLevel - * @phpstan-param Level|LevelName|LogLevel::* $defaultActionLevel + * @phpstan-param value-of|value-of|Level|LogLevel::* $defaultActionLevel + * @phpstan-param array|value-of|Level|LogLevel::*> $channelToActionLevel */ - public function __construct($defaultActionLevel, array $channelToActionLevel = []) + public function __construct(int|string|Level $defaultActionLevel, array $channelToActionLevel = []) { $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); - $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel); + $this->channelToActionLevel = array_map(Logger::toMonologLevel(...), $channelToActionLevel); } - /** - * @phpstan-param Record $record - */ - public function isHandlerActivated(array $record): bool + public function isHandlerActivated(LogRecord $record): bool { - if (isset($this->channelToActionLevel[$record['channel']])) { - return $record['level'] >= $this->channelToActionLevel[$record['channel']]; + if (isset($this->channelToActionLevel[$record->channel])) { + return $record->level->value >= $this->channelToActionLevel[$record->channel]->value; } - return $record['level'] >= $this->defaultActionLevel; + return $record->level->value >= $this->defaultActionLevel->value; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php index 5ec88ea..c3ca296 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php @@ -11,6 +11,8 @@ namespace Monolog\Handler\FingersCrossed; +use Monolog\Level; +use Monolog\LogRecord; use Monolog\Logger; use Psr\Log\LogLevel; @@ -18,29 +20,23 @@ * Error level based activation strategy. * * @author Johannes M. Schmitt - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class ErrorLevelActivationStrategy implements ActivationStrategyInterface { - /** - * @var Level - */ - private $actionLevel; + private Level $actionLevel; /** - * @param int|string $actionLevel Level or name or value + * @param int|string|Level $actionLevel Level or name or value * - * @phpstan-param Level|LevelName|LogLevel::* $actionLevel + * @phpstan-param value-of|value-of|Level|LogLevel::* $actionLevel */ - public function __construct($actionLevel) + public function __construct(int|string|Level $actionLevel) { $this->actionLevel = Logger::toMonologLevel($actionLevel); } - public function isHandlerActivated(array $record): bool + public function isHandlerActivated(LogRecord $record): bool { - return $record['level'] >= $this->actionLevel; + return $record->level->value >= $this->actionLevel->value; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php index 0627b44..ce2a3a8 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php @@ -11,12 +11,15 @@ namespace Monolog\Handler; +use Closure; use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; use Monolog\Handler\FingersCrossed\ActivationStrategyInterface; +use Monolog\Level; use Monolog\Logger; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Buffers all records until a certain level is reached @@ -33,55 +36,50 @@ * Monolog\Handler\FingersCrossed\ namespace. * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface, FormattableHandlerInterface { use ProcessableHandlerTrait; /** - * @var callable|HandlerInterface - * @phpstan-var callable(?Record, HandlerInterface): HandlerInterface|HandlerInterface - */ - protected $handler; - /** @var ActivationStrategyInterface */ - protected $activationStrategy; - /** @var bool */ - protected $buffering = true; - /** @var int */ - protected $bufferSize; - /** @var Record[] */ - protected $buffer = []; - /** @var bool */ - protected $stopBuffering; - /** - * @var ?int - * @phpstan-var ?Level + * Handler or factory Closure($record, $this) + * + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface */ - protected $passthruLevel; - /** @var bool */ - protected $bubble; + protected Closure|HandlerInterface $handler; + + protected ActivationStrategyInterface $activationStrategy; + + protected bool $buffering = true; + + protected int $bufferSize; + + /** @var LogRecord[] */ + protected array $buffer = []; + + protected bool $stopBuffering; + + protected Level|null $passthruLevel = null; + + protected bool $bubble; /** - * @psalm-param HandlerInterface|callable(?Record, HandlerInterface): HandlerInterface $handler + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler * - * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $fingersCrossedHandler). - * @param int|string|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated - * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. - * @param bool $bubble Whether the messages that are handled can bubble up the stack or not - * @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true) - * @param int|string $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $fingersCrossedHandler). + * @param int|string|Level|LogLevel::* $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated + * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true) + * @param int|string|Level|LogLevel::*|null $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered * - * @phpstan-param Level|LevelName|LogLevel::* $passthruLevel - * @phpstan-param Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy + * @phpstan-param value-of|value-of|Level|LogLevel::*|ActivationStrategyInterface $activationStrategy + * @phpstan-param value-of|value-of|Level|LogLevel::* $passthruLevel */ - public function __construct($handler, $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, $passthruLevel = null) + public function __construct(Closure|HandlerInterface $handler, int|string|Level|ActivationStrategyInterface $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, int|string|Level|null $passthruLevel = null) { if (null === $activationStrategy) { - $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); + $activationStrategy = new ErrorLevelActivationStrategy(Level::Warning); } // convert simple int activationStrategy to an object @@ -98,16 +96,12 @@ public function __construct($handler, $activationStrategy = null, int $bufferSiz if ($passthruLevel !== null) { $this->passthruLevel = Logger::toMonologLevel($passthruLevel); } - - if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { - throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); - } } /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { return true; } @@ -126,12 +120,11 @@ public function activate(): void } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } @@ -151,7 +144,7 @@ public function handle(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { @@ -160,7 +153,7 @@ public function close(): void $this->getHandler()->close(); } - public function reset() + public function reset(): void { $this->flushBuffer(); @@ -190,7 +183,7 @@ private function flushBuffer(): void if (null !== $this->passthruLevel) { $level = $this->passthruLevel; $this->buffer = array_filter($this->buffer, function ($record) use ($level) { - return $record['level'] >= $level; + return $record->level >= $level; }); if (count($this->buffer) > 0) { $this->getHandler(end($this->buffer))->handleBatch($this->buffer); @@ -204,26 +197,23 @@ private function flushBuffer(): void /** * Return the nested handler * - * If the handler was provided as a factory callable, this will trigger the handler's instantiation. - * - * @return HandlerInterface - * - * @phpstan-param Record $record + * If the handler was provided as a factory, this will trigger the handler's instantiation. */ - public function getHandler(array $record = null) + public function getHandler(LogRecord $record = null): HandlerInterface { if (!$this->handler instanceof HandlerInterface) { - $this->handler = ($this->handler)($record, $this); - if (!$this->handler instanceof HandlerInterface) { - throw new \RuntimeException("The factory callable should return a HandlerInterface"); + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); } + $this->handler = $handler; } return $this->handler; } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -238,7 +228,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php index 72718de..6b9e510 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php @@ -13,13 +13,12 @@ use Monolog\Formatter\WildfireFormatter; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Simple FirePHP Handler (http://www.firephp.org/), which uses the Wildfire protocol. * * @author Eric Clemmons (@ericclemmons) - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class FirePHPHandler extends AbstractProcessingHandler { @@ -47,18 +46,15 @@ class FirePHPHandler extends AbstractProcessingHandler /** * Whether or not Wildfire vendor-specific headers have been generated & sent yet - * @var bool */ - protected static $initialized = false; + protected static bool $initialized = false; /** * Shared static message index between potentially multiple handlers - * @var int */ - protected static $messageIndex = 1; + protected static int $messageIndex = 1; - /** @var bool */ - protected static $sendHeaders = true; + protected static bool $sendHeaders = true; /** * Base header creation function used by init headers & record headers @@ -85,21 +81,19 @@ protected function createHeader(array $meta, string $message): array * @phpstan-return non-empty-array * * @see createHeader() - * - * @phpstan-param FormattedRecord $record */ - protected function createRecordHeader(array $record): array + protected function createRecordHeader(LogRecord $record): array { // 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. return $this->createHeader( [1, 1, 1, self::$messageIndex++], - $record['formatted'] + $record->formatted ); } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { @@ -140,7 +134,7 @@ protected function sendHeader(string $header, string $content): void * @see sendHeader() * @see sendInitHeaders() */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!self::$sendHeaders || !$this->isWebRequest()) { return; @@ -171,7 +165,7 @@ protected function write(array $record): void */ protected function headersAccepted(): bool { - if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { + if (isset($_SERVER['HTTP_USER_AGENT']) && 1 === preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { return true; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php index 85c95b9..2206482 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php @@ -13,7 +13,8 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Sends logs to Fleep.io using Webhook integrations @@ -22,8 +23,6 @@ * * @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation * @author Ando Roots - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class FleepHookHandler extends SocketHandler { @@ -34,7 +33,7 @@ class FleepHookHandler extends SocketHandler /** * @var string Webhook token (specifies the conversation where logs are sent) */ - protected $token; + protected string $token; /** * Construct a new Fleep.io Handler. @@ -42,12 +41,12 @@ class FleepHookHandler extends SocketHandler * For instructions on how to create a new web hook in your conversations * see https://fleep.io/integrations/webhooks/ * - * @param string $token Webhook token - * @throws MissingExtensionException + * @param string $token Webhook token + * @throws MissingExtensionException if OpenSSL is missing */ public function __construct( string $token, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -89,16 +88,16 @@ protected function getDefaultFormatter(): FormatterInterface /** * Handles a log record */ - public function write(array $record): void + public function write(LogRecord $record): void { parent::write($record); $this->closeSocket(); } /** - * {@inheritDoc} + * @inheritDoc */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { $content = $this->buildContent($record); @@ -121,13 +120,11 @@ private function buildHeader(string $content): string /** * Builds the body of API call - * - * @phpstan-param FormattedRecord $record */ - private function buildContent(array $record): string + private function buildContent(LogRecord $record): string { $dataArray = [ - 'message' => $record['formatted'], + 'message' => $record->formatted, ]; return http_build_query($dataArray); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php index 5715d58..d24bec4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php @@ -11,10 +11,11 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Formatter\FlowdockFormatter; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Sends notifications through the Flowdock push API @@ -26,23 +27,18 @@ * * @author Dominik Liebler * @see https://www.flowdock.com/api/push - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler * @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4 */ class FlowdockHandler extends SocketHandler { - /** - * @var string - */ - protected $apiToken; + protected string $apiToken; /** * @throws MissingExtensionException if OpenSSL is missing */ public function __construct( string $apiToken, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -68,7 +64,7 @@ public function __construct( } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -88,9 +84,9 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { parent::write($record); @@ -98,9 +94,9 @@ protected function write(array $record): void } /** - * {@inheritDoc} + * @inheritDoc */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { $content = $this->buildContent($record); @@ -109,12 +105,10 @@ protected function generateDataStream(array $record): string /** * Builds the body of API call - * - * @phpstan-param FormattedRecord $record */ - private function buildContent(array $record): string + private function buildContent(LogRecord $record): string { - return Utils::jsonEncode($record['formatted']['flowdock']); + return Utils::jsonEncode($record->formatted); } /** diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php index fc1693c..72da59e 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php @@ -23,15 +23,12 @@ interface FormattableHandlerInterface /** * Sets the formatter. * - * @param FormatterInterface $formatter - * @return HandlerInterface self + * @return HandlerInterface self */ public function setFormatter(FormatterInterface $formatter): HandlerInterface; /** * Gets the formatter. - * - * @return FormatterInterface */ public function getFormatter(): FormatterInterface; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php index b60bdce..c044e07 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php @@ -21,13 +21,10 @@ */ trait FormattableHandlerTrait { - /** - * @var ?FormatterInterface - */ - protected $formatter; + protected FormatterInterface|null $formatter = null; /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -37,11 +34,11 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { - if (!$this->formatter) { + if (null === $this->formatter) { $this->formatter = $this->getDefaultFormatter(); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php index 4ff26c4..ba5bb97 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php @@ -12,9 +12,10 @@ namespace Monolog\Handler; use Gelf\PublisherInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\GelfMessageFormatter; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Handler to send messages to a Graylog2 (http://www.graylog2.org) server @@ -27,12 +28,12 @@ class GelfHandler extends AbstractProcessingHandler /** * @var PublisherInterface the publisher object that sends the message to the server */ - protected $publisher; + protected PublisherInterface $publisher; /** * @param PublisherInterface $publisher a gelf publisher object */ - public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(PublisherInterface $publisher, int|string|Level $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); @@ -40,15 +41,15 @@ public function __construct(PublisherInterface $publisher, $level = Logger::DEBU } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->publisher->publish($record['formatted']); + $this->publisher->publish($record->formatted); } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php index 3c9dc4b..854b31a 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php @@ -13,26 +13,26 @@ use Monolog\Formatter\FormatterInterface; use Monolog\ResettableInterface; +use Monolog\LogRecord; /** * Forwards records to multiple handlers * * @author Lenar Lõhmus - * - * @phpstan-import-type Record from \Monolog\Logger */ class GroupHandler extends Handler implements ProcessableHandlerInterface, ResettableInterface { use ProcessableHandlerTrait; /** @var HandlerInterface[] */ - protected $handlers; - /** @var bool */ - protected $bubble; + protected array $handlers; + protected bool $bubble; /** * @param HandlerInterface[] $handlers Array of Handlers. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * + * @throws \InvalidArgumentException if an unsupported handler is set */ public function __construct(array $handlers, bool $bubble = true) { @@ -47,9 +47,9 @@ public function __construct(array $handlers, bool $bubble = true) } /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { foreach ($this->handlers as $handler) { if ($handler->isHandling($record)) { @@ -61,12 +61,11 @@ public function isHandling(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } @@ -78,16 +77,15 @@ public function handle(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { - if ($this->processors) { + if (\count($this->processors) > 0) { $processed = []; foreach ($records as $record) { $processed[] = $this->processRecord($record); } - /** @var Record[] $records */ $records = $processed; } @@ -96,7 +94,7 @@ public function handleBatch(array $records): void } } - public function reset() + public function reset(): void { $this->resetProcessors(); @@ -117,7 +115,7 @@ public function close(): void } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Handler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Handler.php index 34b4935..e89f969 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Handler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Handler.php @@ -19,7 +19,7 @@ abstract class Handler implements HandlerInterface { /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { @@ -29,7 +29,7 @@ public function handleBatch(array $records): void } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php index affcc51..83905c3 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php @@ -11,13 +11,12 @@ namespace Monolog\Handler; +use Monolog\LogRecord; + /** * Interface that all Monolog Handlers must implement * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ interface HandlerInterface { @@ -30,13 +29,9 @@ interface HandlerInterface * is no guarantee that handle() will not be called, and isHandling() might not be called * for a given record. * - * @param array $record Partial log record containing only a level key - * - * @return bool - * - * @phpstan-param array{level: Level} $record + * @param LogRecord $record Partial log record having only a level initialized */ - public function isHandling(array $record): bool; + public function isHandling(LogRecord $record): bool; /** * Handles a record. @@ -48,20 +43,16 @@ public function isHandling(array $record): bool; * Unless the bubbling is interrupted (by returning true), the Logger class will keep on * calling further handlers in the stack with a given log record. * - * @param array $record The record to handle - * @return bool true means that this handler handled the record, and that bubbling is not permitted. - * false means the record was either not processed or that this handler allows bubbling. - * - * @phpstan-param Record $record + * @param LogRecord $record The record to handle + * @return bool true means that this handler handled the record, and that bubbling is not permitted. + * false means the record was either not processed or that this handler allows bubbling. */ - public function handle(array $record): bool; + public function handle(LogRecord $record): bool; /** * Handles a set of records at once. * - * @param array $records The records to handle (an array of record arrays) - * - * @phpstan-param Record[] $records + * @param array $records The records to handle */ public function handleBatch(array $records): void; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php index d4351b9..541ec25 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php @@ -13,6 +13,7 @@ use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * This simple wrapper class can be used to extend handlers functionality. @@ -21,7 +22,7 @@ * * Inherit from this class and override handle() like this: * - * public function handle(array $record) + * public function handle(LogRecord $record) * { * if ($record meets certain conditions) { * return false; @@ -33,10 +34,7 @@ */ class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, FormattableHandlerInterface, ResettableInterface { - /** - * @var HandlerInterface - */ - protected $handler; + protected HandlerInterface $handler; public function __construct(HandlerInterface $handler) { @@ -44,23 +42,23 @@ public function __construct(HandlerInterface $handler) } /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { return $this->handler->isHandling($record); } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { return $this->handler->handle($record); } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { @@ -68,7 +66,7 @@ public function handleBatch(array $records): void } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { @@ -76,7 +74,7 @@ public function close(): void } /** - * {@inheritDoc} + * @inheritDoc */ public function pushProcessor(callable $callback): HandlerInterface { @@ -90,7 +88,7 @@ public function pushProcessor(callable $callback): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function popProcessor(): callable { @@ -102,7 +100,7 @@ public function popProcessor(): callable } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -116,7 +114,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { @@ -127,7 +125,7 @@ public function getFormatter(): FormatterInterface throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class); } - public function reset() + public function reset(): void { if ($this->handler instanceof ResettableInterface) { $this->handler->reset(); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php index 000ccea..418f2ba 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * IFTTTHandler uses cURL to trigger IFTTT Maker actions @@ -27,16 +28,16 @@ */ class IFTTTHandler extends AbstractProcessingHandler { - /** @var string */ - private $eventName; - /** @var string */ - private $secretKey; + private string $eventName; + private string $secretKey; /** * @param string $eventName The name of the IFTTT Maker event that should be triggered * @param string $secretKey A valid IFTTT secret key + * + * @throws MissingExtensionException If the curl extension is missing */ - public function __construct(string $eventName, string $secretKey, $level = Logger::ERROR, bool $bubble = true) + public function __construct(string $eventName, string $secretKey, int|string|Level $level = Level::Error, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); @@ -49,14 +50,14 @@ public function __construct(string $eventName, string $secretKey, $level = Logge } /** - * {@inheritDoc} + * @inheritDoc */ - public function write(array $record): void + public function write(LogRecord $record): void { $postData = [ - "value1" => $record["channel"], + "value1" => $record->channel, "value2" => $record["level_name"], - "value3" => $record["message"], + "value3" => $record->message, ]; $postString = Utils::jsonEncode($postData); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php index 71f64a2..abb2f88 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php @@ -11,7 +11,8 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Inspired on LogEntriesHandler. @@ -21,15 +22,12 @@ */ class InsightOpsHandler extends SocketHandler { - /** - * @var string - */ - protected $logToken; + protected string $logToken; /** - * @param string $token Log token supplied by InsightOps - * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'. - * @param bool $useSSL Whether or not SSL encryption should be used + * @param string $token Log token supplied by InsightOps + * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'. + * @param bool $useSSL Whether or not SSL encryption should be used * * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing */ @@ -37,7 +35,7 @@ public function __construct( string $token, string $region = 'us', bool $useSSL = true, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -67,10 +65,10 @@ public function __construct( } /** - * {@inheritDoc} + * @inheritDoc */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { - return $this->logToken . ' ' . $record['formatted']; + return $this->logToken . ' ' . $record->formatted; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php index 25fcd15..0025983 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php @@ -11,29 +11,27 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * @author Robert Kaufmann III */ class LogEntriesHandler extends SocketHandler { - /** - * @var string - */ - protected $logToken; + protected string $logToken; /** - * @param string $token Log token supplied by LogEntries - * @param bool $useSSL Whether or not SSL encryption should be used. - * @param string $host Custom hostname to send the data to if needed + * @param string $token Log token supplied by LogEntries + * @param bool $useSSL Whether or not SSL encryption should be used. + * @param string $host Custom hostname to send the data to if needed * * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing */ public function __construct( string $token, bool $useSSL = true, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, string $host = 'data.logentries.com', bool $persistent = false, @@ -61,10 +59,10 @@ public function __construct( } /** - * {@inheritDoc} + * @inheritDoc */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { - return $this->logToken . ' ' . $record['formatted']; + return $this->logToken . ' ' . $record->formatted; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php index 6d13db3..2d8e66f 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php @@ -11,11 +11,12 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LogglyFormatter; use function array_key_exists; use CurlHandle; +use Monolog\LogRecord; /** * Sends errors to Loggly. @@ -33,22 +34,21 @@ class LogglyHandler extends AbstractProcessingHandler /** * Caches the curl handlers for every given endpoint. * - * @var resource[]|CurlHandle[] + * @var CurlHandle[] */ - protected $curlHandlers = []; + protected array $curlHandlers = []; - /** @var string */ - protected $token; + protected string $token; /** @var string[] */ - protected $tag = []; + protected array $tag = []; /** * @param string $token API token supplied by Loggly * * @throws MissingExtensionException If the curl extension is missing */ - public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(string $token, int|string|Level $level = Level::Debug, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); @@ -61,12 +61,8 @@ public function __construct(string $token, $level = Logger::DEBUG, bool $bubble /** * Loads and returns the shared curl handler for the given endpoint. - * - * @param string $endpoint - * - * @return resource|CurlHandle */ - protected function getCurlHandler(string $endpoint) + protected function getCurlHandler(string $endpoint): CurlHandle { if (!array_key_exists($endpoint, $this->curlHandlers)) { $this->curlHandlers[$endpoint] = $this->loadCurlHandle($endpoint); @@ -77,12 +73,8 @@ protected function getCurlHandler(string $endpoint) /** * Starts a fresh curl session for the given endpoint and returns its handler. - * - * @param string $endpoint - * - * @return resource|CurlHandle */ - private function loadCurlHandle(string $endpoint) + private function loadCurlHandle(string $endpoint): CurlHandle { $url = sprintf("https://%s/%s/%s/", static::HOST, $endpoint, $this->token); @@ -98,10 +90,13 @@ private function loadCurlHandle(string $endpoint) /** * @param string[]|string $tag */ - public function setTag($tag): self + public function setTag(string|array $tag): self { - $tag = !empty($tag) ? $tag : []; - $this->tag = is_array($tag) ? $tag : [$tag]; + if ('' === $tag || [] === $tag) { + $this->tag = []; + } else { + $this->tag = is_array($tag) ? $tag : [$tag]; + } return $this; } @@ -109,9 +104,9 @@ public function setTag($tag): self /** * @param string[]|string $tag */ - public function addTag($tag): self + public function addTag(string|array $tag): self { - if (!empty($tag)) { + if ('' !== $tag) { $tag = is_array($tag) ? $tag : [$tag]; $this->tag = array_unique(array_merge($this->tag, $tag)); } @@ -119,9 +114,9 @@ public function addTag($tag): self return $this; } - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->send($record["formatted"], static::ENDPOINT_SINGLE); + $this->send($record->formatted, static::ENDPOINT_SINGLE); } public function handleBatch(array $records): void @@ -129,10 +124,10 @@ public function handleBatch(array $records): void $level = $this->level; $records = array_filter($records, function ($record) use ($level) { - return ($record['level'] >= $level); + return ($record->level >= $level); }); - if ($records) { + if (\count($records) > 0) { $this->send($this->getFormatter()->formatBatch($records), static::ENDPOINT_BATCH); } } @@ -143,7 +138,7 @@ protected function send(string $data, string $endpoint): void $headers = ['Content-Type: application/json']; - if (!empty($this->tag)) { + if (\count($this->tag) > 0) { $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php index 859a469..876b1a9 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php @@ -11,44 +11,36 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LogmaticFormatter; +use Monolog\LogRecord; /** * @author Julien Breux */ class LogmaticHandler extends SocketHandler { - /** - * @var string - */ - private $logToken; + private string $logToken; - /** - * @var string - */ - private $hostname; + private string $hostname; - /** - * @var string - */ - private $appname; + private string $appName; /** - * @param string $token Log token supplied by Logmatic. - * @param string $hostname Host name supplied by Logmatic. - * @param string $appname Application name supplied by Logmatic. - * @param bool $useSSL Whether or not SSL encryption should be used. + * @param string $token Log token supplied by Logmatic. + * @param string $hostname Host name supplied by Logmatic. + * @param string $appName Application name supplied by Logmatic. + * @param bool $useSSL Whether or not SSL encryption should be used. * * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing */ public function __construct( string $token, string $hostname = '', - string $appname = '', + string $appName = '', bool $useSSL = true, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -76,29 +68,29 @@ public function __construct( $this->logToken = $token; $this->hostname = $hostname; - $this->appname = $appname; + $this->appName = $appName; } /** - * {@inheritDoc} + * @inheritDoc */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { - return $this->logToken . ' ' . $record['formatted']; + return $this->logToken . ' ' . $record->formatted; } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { $formatter = new LogmaticFormatter(); - if (!empty($this->hostname)) { + if ($this->hostname !== '') { $formatter->setHostname($this->hostname); } - if (!empty($this->appname)) { - $formatter->setAppname($this->appname); + if ($this->appName !== '') { + $formatter->setAppName($this->appName); } return $formatter; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php index 97f3432..b6c8227 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php @@ -13,33 +13,32 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\HtmlFormatter; +use Monolog\LogRecord; /** * Base class for all mail handlers * * @author Gyula Sallai - * - * @phpstan-import-type Record from \Monolog\Logger */ abstract class MailHandler extends AbstractProcessingHandler { /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { $messages = []; foreach ($records as $record) { - if ($record['level'] < $this->level) { + if ($record->level->isLowerThan($this->level)) { continue; } - /** @var Record $message */ + $message = $this->processRecord($record); $messages[] = $message; } - if (!empty($messages)) { + if (\count($messages) > 0) { $this->send((string) $this->getFormatter()->formatBatch($messages), $messages); } } @@ -50,27 +49,26 @@ public function handleBatch(array $records): void * @param string $content formatted email body to be sent * @param array $records the array of log records that formed this content * - * @phpstan-param Record[] $records + * @phpstan-param non-empty-array $records */ abstract protected function send(string $content, array $records): void; /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->send((string) $record['formatted'], [$record]); + $this->send((string) $record->formatted, [$record]); } /** - * @phpstan-param non-empty-array $records - * @phpstan-return Record + * @phpstan-param non-empty-array $records */ - protected function getHighestRecord(array $records): array + protected function getHighestRecord(array $records): LogRecord { $highestRecord = null; foreach ($records as $record) { - if ($highestRecord === null || $highestRecord['level'] < $record['level']) { + if ($highestRecord === null || $record->level->isHigherThan($highestRecord->level)) { $highestRecord = $record; } } @@ -85,8 +83,6 @@ protected function isHtmlBody(string $body): bool /** * Gets the default formatter. - * - * @return FormatterInterface */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php index 3003500..64e16c9 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Swift; use Swift_Message; @@ -22,22 +22,22 @@ */ class MandrillHandler extends MailHandler { - /** @var Swift_Message */ - protected $message; - /** @var string */ - protected $apiKey; + protected Swift_Message $message; + protected string $apiKey; /** - * @psalm-param Swift_Message|callable(): Swift_Message $message + * @phpstan-param (Swift_Message|callable(): Swift_Message) $message * * @param string $apiKey A valid Mandrill API key * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced + * + * @throws \InvalidArgumentException if not a Swift Message is set */ - public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true) + public function __construct(string $apiKey, callable|Swift_Message $message, int|string|Level $level = Level::Error, bool $bubble = true) { parent::__construct($level, $bubble); - if (!$message instanceof Swift_Message && is_callable($message)) { + if (!$message instanceof Swift_Message) { $message = $message(); } if (!$message instanceof Swift_Message) { @@ -48,7 +48,7 @@ public function __construct(string $apiKey, $message, $level = Logger::ERROR, bo } /** - * {@inheritDoc} + * @inheritDoc */ protected function send(string $content, array $records): void { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php index 3063091..33ab68c 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php @@ -14,9 +14,10 @@ use MongoDB\Driver\BulkWrite; use MongoDB\Driver\Manager; use MongoDB\Client; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\MongoDBFormatter; +use Monolog\LogRecord; /** * Logs to a MongoDB database. @@ -33,12 +34,11 @@ */ class MongoDBHandler extends AbstractProcessingHandler { - /** @var \MongoDB\Collection */ - private $collection; - /** @var Client|Manager */ - private $manager; - /** @var string */ - private $namespace; + private \MongoDB\Collection $collection; + + private Client|Manager $manager; + + private string|null $namespace = null; /** * Constructor. @@ -47,12 +47,8 @@ class MongoDBHandler extends AbstractProcessingHandler * @param string $database Database name * @param string $collection Collection name */ - public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(Client|Manager $mongodb, string $database, string $collection, int|string|Level $level = Level::Debug, bool $bubble = true) { - if (!($mongodb instanceof Client || $mongodb instanceof Manager)) { - throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required'); - } - if ($mongodb instanceof Client) { $this->collection = $mongodb->selectCollection($database, $collection); } else { @@ -63,21 +59,21 @@ public function __construct($mongodb, string $database, string $collection, $lev parent::__construct($level, $bubble); } - protected function write(array $record): void + protected function write(LogRecord $record): void { if (isset($this->collection)) { - $this->collection->insertOne($record['formatted']); + $this->collection->insertOne($record->formatted); } if (isset($this->manager, $this->namespace)) { $bulk = new BulkWrite; - $bulk->insert($record["formatted"]); + $bulk->insert($record->formatted); $this->manager->executeBulkWrite($this->namespace, $bulk); } } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php index 0c0a3bd..d4c9d80 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\LineFormatter; /** @@ -26,43 +26,39 @@ class NativeMailerHandler extends MailHandler * The email addresses to which the message will be sent * @var string[] */ - protected $to; + protected array $to; /** * The subject of the email - * @var string */ - protected $subject; + protected string $subject; /** * Optional headers for the message * @var string[] */ - protected $headers = []; + protected array $headers = []; /** * Optional parameters for the message * @var string[] */ - protected $parameters = []; + protected array $parameters = []; /** * The wordwrap length for the message - * @var int */ - protected $maxColumnWidth; + protected int $maxColumnWidth; /** * The Content-type for the message - * @var string|null */ - protected $contentType; + protected string|null $contentType = null; /** * The encoding for the message - * @var string */ - protected $encoding = 'utf-8'; + protected string $encoding = 'utf-8'; /** * @param string|string[] $to The receiver of the mail @@ -70,7 +66,7 @@ class NativeMailerHandler extends MailHandler * @param string $from The sender of the mail * @param int $maxColumnWidth The maximum column width that the message lines will have */ - public function __construct($to, string $subject, string $from, $level = Logger::ERROR, bool $bubble = true, int $maxColumnWidth = 70) + public function __construct(string|array $to, string $subject, string $from, int|string|Level $level = Level::Error, bool $bubble = true, int $maxColumnWidth = 70) { parent::__construct($level, $bubble); $this->to = (array) $to; @@ -109,11 +105,11 @@ public function addParameter($parameters): self } /** - * {@inheritDoc} + * @inheritDoc */ protected function send(string $content, array $records): void { - $contentType = $this->getContentType() ?: ($this->isHtmlBody($content) ? 'text/html' : 'text/plain'); + $contentType = $this->getContentType() ?? ($this->isHtmlBody($content) ? 'text/html' : 'text/plain'); if ($contentType !== 'text/html') { $content = wordwrap($content, $this->maxColumnWidth); @@ -125,11 +121,8 @@ protected function send(string $content, array $records): void $headers .= 'MIME-Version: 1.0' . "\r\n"; } - $subject = $this->subject; - if ($records) { - $subjectFormatter = new LineFormatter($this->subject); - $subject = $subjectFormatter->format($this->getHighestRecord($records)); - } + $subjectFormatter = new LineFormatter($this->subject); + $subject = $subjectFormatter->format($this->getHighestRecord($records)); $parameters = implode(' ', $this->parameters); foreach ($this->to as $to) { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php index 114d749..b8cb378 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php @@ -11,16 +11,17 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Class to record a log on a NewRelic application. * Enabling New Relic High Security mode may prevent capture of useful information. * - * This handler requires a NormalizerFormatter to function and expects an array in $record['formatted'] + * This handler requires a NormalizerFormatter to function and expects an array in $record->formatted * * @see https://docs.newrelic.com/docs/agents/php-agent * @see https://docs.newrelic.com/docs/accounts-partnerships/accounts/security/high-security @@ -28,75 +29,58 @@ class NewRelicHandler extends AbstractProcessingHandler { /** - * Name of the New Relic application that will receive logs from this handler. - * - * @var ?string - */ - protected $appName; - - /** - * Name of the current transaction - * - * @var ?string - */ - protected $transactionName; - - /** - * Some context and extra data is passed into the handler as arrays of values. Do we send them as is - * (useful if we are using the API), or explode them for display on the NewRelic RPM website? - * - * @var bool - */ - protected $explodeArrays; - - /** - * {@inheritDoc} - * - * @param string|null $appName - * @param bool $explodeArrays - * @param string|null $transactionName + * @inheritDoc */ public function __construct( - $level = Logger::ERROR, + int|string|Level $level = Level::Error, bool $bubble = true, - ?string $appName = null, - bool $explodeArrays = false, - ?string $transactionName = null + + /** + * Name of the New Relic application that will receive logs from this handler. + */ + protected string|null $appName = null, + + /** + * Some context and extra data is passed into the handler as arrays of values. Do we send them as is + * (useful if we are using the API), or explode them for display on the NewRelic RPM website? + */ + protected bool $explodeArrays = false, + + /** + * Name of the current transaction + */ + protected string|null $transactionName = null ) { parent::__construct($level, $bubble); - - $this->appName = $appName; - $this->explodeArrays = $explodeArrays; - $this->transactionName = $transactionName; } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!$this->isNewRelicEnabled()) { throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler'); } - if ($appName = $this->getAppName($record['context'])) { + if (null !== ($appName = $this->getAppName($record->context))) { $this->setNewRelicAppName($appName); } - if ($transactionName = $this->getTransactionName($record['context'])) { + if (null !== ($transactionName = $this->getTransactionName($record->context))) { $this->setNewRelicTransactionName($transactionName); - unset($record['formatted']['context']['transaction_name']); + unset($record->formatted['context']['transaction_name']); } - if (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) { - newrelic_notice_error($record['message'], $record['context']['exception']); - unset($record['formatted']['context']['exception']); + if (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) { + newrelic_notice_error($record->message, $record->context['exception']); + unset($record->formatted['context']['exception']); } else { - newrelic_notice_error($record['message']); + newrelic_notice_error($record->message); } - if (isset($record['formatted']['context']) && is_array($record['formatted']['context'])) { - foreach ($record['formatted']['context'] as $key => $parameter) { + if (isset($record->formatted['context']) && is_array($record->formatted['context'])) { + foreach ($record->formatted['context'] as $key => $parameter) { if (is_array($parameter) && $this->explodeArrays) { foreach ($parameter as $paramKey => $paramValue) { $this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue); @@ -107,8 +91,8 @@ protected function write(array $record): void } } - if (isset($record['formatted']['extra']) && is_array($record['formatted']['extra'])) { - foreach ($record['formatted']['extra'] as $key => $parameter) { + if (isset($record->formatted['extra']) && is_array($record->formatted['extra'])) { + foreach ($record->formatted['extra'] as $key => $parameter) { if (is_array($parameter) && $this->explodeArrays) { foreach ($parameter as $paramKey => $paramValue) { $this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue); @@ -122,8 +106,6 @@ protected function write(array $record): void /** * Checks whether the NewRelic extension is enabled in the system. - * - * @return bool */ protected function isNewRelicEnabled(): bool { @@ -177,8 +159,7 @@ protected function setNewRelicTransactionName(string $transactionName): void } /** - * @param string $key - * @param mixed $value + * @param mixed $value */ protected function setNewRelicParameter(string $key, $value): void { @@ -190,7 +171,7 @@ protected function setNewRelicParameter(string $key, $value): void } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php index 1ddf0be..d9fea18 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php @@ -11,6 +11,8 @@ namespace Monolog\Handler; +use Monolog\LogRecord; + /** * No-op * @@ -23,17 +25,17 @@ class NoopHandler extends Handler { /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { return true; } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { return false; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php index e75ee0c..1aa84e4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php @@ -11,8 +11,10 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Psr\Log\LogLevel; +use Monolog\Logger; +use Monolog\LogRecord; /** * Blackhole @@ -21,40 +23,34 @@ * to put on top of an existing stack to override it temporarily. * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class NullHandler extends Handler { - /** - * @var int - */ - private $level; + private Level $level; /** - * @param string|int $level The minimum logging level at which this handler will be triggered + * @param string|int|Level $level The minimum logging level at which this handler will be triggered * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG) + public function __construct(string|int|Level $level = Level::Debug) { $this->level = Logger::toMonologLevel($level); } /** - * {@inheritDoc} + * @inheritDoc */ - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { - return $record['level'] >= $this->level; + return $record->level->value >= $this->level->value; } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - return $record['level'] >= $this->level; + return $record->level->value >= $this->level->value; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php index 22068c9..a72b7a1 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Handler to only pass log messages when a certain threshold of number of messages is reached. @@ -27,7 +28,7 @@ * $handler = new SomeHandler(...) * * // Pass all warnings to the handler when more than 10 & all error messages when more then 5 - * $overflow = new OverflowHandler($handler, [Logger::WARNING => 10, Logger::ERROR => 5]); + * $overflow = new OverflowHandler($handler, [Level::Warning->value => 10, Level::Error->value => 5]); * * $log->pushHandler($overflow); *``` @@ -36,36 +37,25 @@ */ class OverflowHandler extends AbstractHandler implements FormattableHandlerInterface { - /** @var HandlerInterface */ - private $handler; - - /** @var int[] */ - private $thresholdMap = [ - Logger::DEBUG => 0, - Logger::INFO => 0, - Logger::NOTICE => 0, - Logger::WARNING => 0, - Logger::ERROR => 0, - Logger::CRITICAL => 0, - Logger::ALERT => 0, - Logger::EMERGENCY => 0, - ]; + private HandlerInterface $handler; + + /** @var array */ + private array $thresholdMap = []; /** * Buffer of all messages passed to the handler before the threshold was reached * * @var mixed[][] */ - private $buffer = []; + private array $buffer = []; /** - * @param HandlerInterface $handler - * @param int[] $thresholdMap Dictionary of logger level => threshold + * @param array $thresholdMap Dictionary of log level value => threshold */ public function __construct( HandlerInterface $handler, array $thresholdMap = [], - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true ) { $this->handler = $handler; @@ -85,15 +75,15 @@ public function __construct( * Unless the bubbling is interrupted (by returning true), the Logger class will keep on * calling further handlers in the stack with a given log record. * - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - if ($record['level'] < $this->level) { + if ($record->level->isLowerThan($this->level)) { return false; } - $level = $record['level']; + $level = $record->level->value; if (!isset($this->thresholdMap[$level])) { $this->thresholdMap[$level] = 0; @@ -122,7 +112,7 @@ public function handle(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -136,7 +126,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php index 23a1d11..8aa78e4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php @@ -13,11 +13,13 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use PhpConsole\Connector; use PhpConsole\Handler as VendorPhpConsoleHandler; use PhpConsole\Helper; +use Monolog\LogRecord; +use PhpConsole\Storage; /** * Monolog handler for Google Chrome extension "PHP Console" @@ -37,14 +39,59 @@ * PC::debug($_SERVER); // PHP Console debugger for any type of vars * * @author Sergey Barbushin https://www.linkedin.com/in/barbushin + * @phpstan-type Options array{ + * enabled: bool, + * classesPartialsTraceIgnore: string[], + * debugTagsKeysInContext: array, + * useOwnErrorsHandler: bool, + * useOwnExceptionsHandler: bool, + * sourcesBasePath: string|null, + * registerHelper: bool, + * serverEncoding: string|null, + * headersLimit: int|null, + * password: string|null, + * enableSslOnlyMode: bool, + * ipMasks: string[], + * enableEvalListener: bool, + * dumperDetectCallbacks: bool, + * dumperLevelLimit: int, + * dumperItemsCountLimit: int, + * dumperItemSizeLimit: int, + * dumperDumpSizeLimit: int, + * detectDumpTraceAndSource: bool, + * dataStorage: Storage|null + * } + * @phpstan-type InputOptions array{ + * enabled?: bool, + * classesPartialsTraceIgnore?: string[], + * debugTagsKeysInContext?: array, + * useOwnErrorsHandler?: bool, + * useOwnExceptionsHandler?: bool, + * sourcesBasePath?: string|null, + * registerHelper?: bool, + * serverEncoding?: string|null, + * headersLimit?: int|null, + * password?: string|null, + * enableSslOnlyMode?: bool, + * ipMasks?: string[], + * enableEvalListener?: bool, + * dumperDetectCallbacks?: bool, + * dumperLevelLimit?: int, + * dumperItemsCountLimit?: int, + * dumperItemSizeLimit?: int, + * dumperDumpSizeLimit?: int, + * detectDumpTraceAndSource?: bool, + * dataStorage?: Storage|null + * } * - * @phpstan-import-type Record from \Monolog\Logger * @deprecated Since 2.8.0 and 3.2.0, PHPConsole is abandoned and thus we will drop this handler in Monolog 4 */ class PHPConsoleHandler extends AbstractProcessingHandler { - /** @var array */ - private $options = [ + /** + * @phpstan-var Options + */ + private array $options = [ 'enabled' => true, // bool Is PHP Console server enabled 'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with... 'debugTagsKeysInContext' => [0, 'tag'], // bool Is PHP Console server enabled @@ -67,15 +114,15 @@ class PHPConsoleHandler extends AbstractProcessingHandler 'dataStorage' => null, // \PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ) ]; - /** @var Connector */ - private $connector; + private Connector $connector; /** * @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) * @throws \RuntimeException + * @phpstan-param InputOptions $options */ - public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(array $options = [], ?Connector $connector = null, int|string|Level $level = Level::Debug, bool $bubble = true) { if (!class_exists('PhpConsole\Connector')) { throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation'); @@ -86,14 +133,16 @@ public function __construct(array $options = [], ?Connector $connector = null, $ } /** - * @param array $options - * + * @param array $options * @return array + * + * @phpstan-param InputOptions $options + * @phpstan-return Options */ private function initOptions(array $options): array { $wrongOptions = array_diff(array_keys($options), array_keys($this->options)); - if ($wrongOptions) { + if (\count($wrongOptions) > 0) { throw new \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions)); } @@ -102,8 +151,8 @@ private function initOptions(array $options): array private function initConnector(?Connector $connector = null): Connector { - if (!$connector) { - if ($this->options['dataStorage']) { + if (null === $connector) { + if ($this->options['dataStorage'] instanceof Storage) { Connector::setPostponeStorage($this->options['dataStorage']); } $connector = Connector::getInstance(); @@ -120,22 +169,22 @@ private function initConnector(?Connector $connector = null): Connector $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']); $handler->start(); } - if ($this->options['sourcesBasePath']) { + if (null !== $this->options['sourcesBasePath']) { $connector->setSourcesBasePath($this->options['sourcesBasePath']); } - if ($this->options['serverEncoding']) { + if (null !== $this->options['serverEncoding']) { $connector->setServerEncoding($this->options['serverEncoding']); } - if ($this->options['password']) { + if (null !== $this->options['password']) { $connector->setPassword($this->options['password']); } if ($this->options['enableSslOnlyMode']) { $connector->enableSslOnlyMode(); } - if ($this->options['ipMasks']) { + if (\count($this->options['ipMasks']) > 0) { $connector->setAllowedIpMasks($this->options['ipMasks']); } - if ($this->options['headersLimit']) { + if (null !== $this->options['headersLimit'] && $this->options['headersLimit'] > 0) { $connector->setHeadersLimit($this->options['headersLimit']); } if ($this->options['detectDumpTraceAndSource']) { @@ -168,7 +217,7 @@ public function getOptions(): array return $this->options; } - public function handle(array $record): bool + public function handle(LogRecord $record): bool { if ($this->options['enabled'] && $this->connector->isActiveClient()) { return parent::handle($record); @@ -180,48 +229,39 @@ public function handle(array $record): bool /** * Writes the record down to the log of the implementing handler */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - if ($record['level'] < Logger::NOTICE) { + if ($record->level->isLowerThan(Level::Notice)) { $this->handleDebugRecord($record); - } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) { + } elseif (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) { $this->handleExceptionRecord($record); } else { $this->handleErrorRecord($record); } } - /** - * @phpstan-param Record $record - */ - private function handleDebugRecord(array $record): void + private function handleDebugRecord(LogRecord $record): void { - $tags = $this->getRecordTags($record); - $message = $record['message']; - if ($record['context']) { - $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($record['context'])), null, true); + [$tags, $filteredContext] = $this->getRecordTags($record); + $message = $record->message; + if (\count($filteredContext) > 0) { + $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($filteredContext)), null, true); } $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']); } - /** - * @phpstan-param Record $record - */ - private function handleExceptionRecord(array $record): void + private function handleExceptionRecord(LogRecord $record): void { - $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']); + $this->connector->getErrorsDispatcher()->dispatchException($record->context['exception']); } - /** - * @phpstan-param Record $record - */ - private function handleErrorRecord(array $record): void + private function handleErrorRecord(LogRecord $record): void { - $context = $record['context']; + $context = $record->context; $this->connector->getErrorsDispatcher()->dispatchError( $context['code'] ?? null, - $context['message'] ?? $record['message'], + $context['message'] ?? $record->message, $context['file'] ?? null, $context['line'] ?? null, $this->options['classesPartialsTraceIgnore'] @@ -229,32 +269,32 @@ private function handleErrorRecord(array $record): void } /** - * @phpstan-param Record $record - * @return string + * @return array{string, mixed[]} */ - private function getRecordTags(array &$record) + private function getRecordTags(LogRecord $record): array { $tags = null; - if (!empty($record['context'])) { - $context = & $record['context']; + $filteredContext = []; + if ($record->context !== []) { + $filteredContext = $record->context; foreach ($this->options['debugTagsKeysInContext'] as $key) { - if (!empty($context[$key])) { - $tags = $context[$key]; + if (isset($filteredContext[$key])) { + $tags = $filteredContext[$key]; if ($key === 0) { - array_shift($context); + array_shift($filteredContext); } else { - unset($context[$key]); + unset($filteredContext[$key]); } break; } } } - return $tags ?: strtolower($record['level_name']); + return [$tags ?? $record->level->toPsrLogLevel(), $filteredContext]; } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php index 8a8cf1b..9edc9ac 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php @@ -11,7 +11,8 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Stores to STDIN of any process, specified by a command. @@ -33,20 +34,14 @@ class ProcessHandler extends AbstractProcessingHandler */ private $process; - /** - * @var string - */ - private $command; + private string $command; - /** - * @var string|null - */ - private $cwd; + private ?string $cwd; /** * @var resource[] */ - private $pipes = []; + private array $pipes = []; /** * @var array @@ -63,7 +58,7 @@ class ProcessHandler extends AbstractProcessingHandler * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in. * @throws \InvalidArgumentException */ - public function __construct(string $command, $level = Logger::DEBUG, bool $bubble = true, ?string $cwd = null) + public function __construct(string $command, int|string|Level $level = Level::Debug, bool $bubble = true, ?string $cwd = null) { if ($command === '') { throw new \InvalidArgumentException('The command argument must be a non-empty string.'); @@ -83,14 +78,14 @@ public function __construct(string $command, $level = Logger::DEBUG, bool $bubbl * * @throws \UnexpectedValueException */ - protected function write(array $record): void + protected function write(LogRecord $record): void { $this->ensureProcessIsStarted(); - $this->writeProcessInput($record['formatted']); + $this->writeProcessInput($record->formatted); $errors = $this->readProcessErrors(); - if (empty($errors) === false) { + if ($errors !== '') { throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors)); } } @@ -134,7 +129,7 @@ private function handleStartupErrors(): void $errors = $this->readProcessErrors(); - if (is_resource($this->process) === false || empty($errors) === false) { + if (is_resource($this->process) === false || $errors !== '') { throw new \UnexpectedValueException( sprintf('The process "%s" could not be opened: ' . $errors, $this->command) ); @@ -176,7 +171,7 @@ protected function writeProcessInput(string $string): void } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php index 3adec7a..9fb290f 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php @@ -12,20 +12,19 @@ namespace Monolog\Handler; use Monolog\Processor\ProcessorInterface; +use Monolog\LogRecord; /** * Interface to describe loggers that have processors * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger */ interface ProcessableHandlerInterface { /** * Adds a processor in the stack. * - * @psalm-param ProcessorInterface|callable(Record): Record $callback + * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback * * @param ProcessorInterface|callable $callback * @return HandlerInterface self @@ -35,7 +34,7 @@ public function pushProcessor(callable $callback): HandlerInterface; /** * Removes the processor on top of the stack and returns it. * - * @psalm-return ProcessorInterface|callable(Record): Record $callback + * @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord) $callback * * @throws \LogicException In case the processor stack is empty * @return callable|ProcessorInterface diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php index 9ef6e30..74eeddd 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php @@ -13,24 +13,23 @@ use Monolog\ResettableInterface; use Monolog\Processor\ProcessorInterface; +use Monolog\LogRecord; /** * Helper trait for implementing ProcessableInterface * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger */ trait ProcessableHandlerTrait { /** * @var callable[] - * @phpstan-var array + * @phpstan-var array<(callable(LogRecord): LogRecord)|ProcessorInterface> */ - protected $processors = []; + protected array $processors = []; /** - * {@inheritDoc} + * @inheritDoc */ public function pushProcessor(callable $callback): HandlerInterface { @@ -40,24 +39,18 @@ public function pushProcessor(callable $callback): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function popProcessor(): callable { - if (!$this->processors) { + if (\count($this->processors) === 0) { throw new \LogicException('You tried to pop from an empty processor stack.'); } return array_shift($this->processors); } - /** - * Processes a record. - * - * @phpstan-param Record $record - * @phpstan-return Record - */ - protected function processRecord(array $record): array + protected function processRecord(LogRecord $record): LogRecord { foreach ($this->processors as $processor) { $record = $processor($record); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php index 36e19cc..6599a83 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php @@ -11,9 +11,10 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Psr\Log\LoggerInterface; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Proxies log messages to an existing PSR-3 compliant logger. @@ -28,20 +29,15 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface { /** * PSR-3 compliant logger - * - * @var LoggerInterface */ - protected $logger; + protected LoggerInterface $logger; - /** - * @var FormatterInterface|null - */ - protected $formatter; + protected FormatterInterface|null $formatter = null; /** * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied */ - public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(LoggerInterface $logger, int|string|Level $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); @@ -49,19 +45,19 @@ public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, boo } /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { if (!$this->isHandling($record)) { return false; } - if ($this->formatter) { + if ($this->formatter !== null) { $formatted = $this->formatter->format($record); - $this->logger->log(strtolower($record['level_name']), (string) $formatted, $record['context']); + $this->logger->log($record->level->toPsrLogLevel(), (string) $formatted, $record->context); } else { - $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']); + $this->logger->log($record->level->toPsrLogLevel(), $record->message, $record->context); } return false === $this->bubble; @@ -69,8 +65,6 @@ public function handle(array $record): bool /** * Sets the formatter. - * - * @param FormatterInterface $formatter */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -81,12 +75,10 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface /** * Gets the formatter. - * - * @return FormatterInterface */ public function getFormatter(): FormatterInterface { - if (!$this->formatter) { + if ($this->formatter === null) { throw new \LogicException('No formatter has been set and this handler does not have a default formatter'); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php index fed2303..118f576 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php @@ -11,48 +11,45 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Logger; use Monolog\Utils; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Sends notifications through the pushover api to mobile phones * * @author Sebastian Göttschkes * @see https://www.pushover.net/api - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class PushoverHandler extends SocketHandler { - /** @var string */ - private $token; + private string $token; + /** @var array */ - private $users; - /** @var string */ - private $title; - /** @var string|int|null */ - private $user = null; - /** @var int */ - private $retry; - /** @var int */ - private $expire; - - /** @var int */ - private $highPriorityLevel; - /** @var int */ - private $emergencyLevel; - /** @var bool */ - private $useFormattedMessage = false; + private array $users; + + private string $title; + + private string|int|null $user = null; + + private int $retry; + + private int $expire; + + private Level $highPriorityLevel; + + private Level $emergencyLevel; + + private bool $useFormattedMessage = false; /** * All parameters that can be sent to Pushover * @see https://pushover.net/api * @var array */ - private $parameterNames = [ + private array $parameterNames = [ 'token' => true, 'user' => true, 'message' => true, @@ -73,40 +70,42 @@ class PushoverHandler extends SocketHandler * @see https://pushover.net/api#sounds * @var string[] */ - private $sounds = [ + private array $sounds = [ 'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming', 'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb', 'persistent', 'echo', 'updown', 'none', ]; /** - * @param string $token Pushover api token - * @param string|array $users Pushover user id or array of ids the message will be sent to - * @param string|null $title Title sent to the Pushover API - * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not - * the pushover.net app owner. OpenSSL is required for this option. - * @param string|int $highPriorityLevel The minimum logging level at which this handler will start - * sending "high priority" requests to the Pushover API - * @param string|int $emergencyLevel The minimum logging level at which this handler will start - * sending "emergency" requests to the Pushover API - * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will - * send the same notification to the user. - * @param int $expire The expire parameter specifies how many seconds your notification will continue - * to be retried for (every retry seconds). + * @param string $token Pushover api token + * @param string|array $users Pushover user id or array of ids the message will be sent to + * @param string|null $title Title sent to the Pushover API + * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not + * the pushover.net app owner. OpenSSL is required for this option. + * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will + * send the same notification to the user. + * @param int $expire The expire parameter specifies how many seconds your notification will continue + * to be retried for (every retry seconds). + * + * @param int|string|Level|LogLevel::* $highPriorityLevel The minimum logging level at which this handler will start + * sending "high priority" requests to the Pushover API + * @param int|string|Level|LogLevel::* $emergencyLevel The minimum logging level at which this handler will start + * sending "emergency" requests to the Pushover API + * * * @phpstan-param string|array $users - * @phpstan-param Level|LevelName|LogLevel::* $highPriorityLevel - * @phpstan-param Level|LevelName|LogLevel::* $emergencyLevel + * @phpstan-param value-of|value-of|Level|LogLevel::* $highPriorityLevel + * @phpstan-param value-of|value-of|Level|LogLevel::* $emergencyLevel */ public function __construct( string $token, $users, ?string $title = null, - $level = Logger::CRITICAL, + int|string|Level $level = Level::Critical, bool $bubble = true, bool $useSSL = true, - $highPriorityLevel = Logger::CRITICAL, - $emergencyLevel = Logger::EMERGENCY, + int|string|Level $highPriorityLevel = Level::Critical, + int|string|Level $emergencyLevel = Level::Emergency, int $retry = 30, int $expire = 25200, bool $persistent = false, @@ -129,32 +128,29 @@ public function __construct( $this->token = $token; $this->users = (array) $users; - $this->title = $title ?: (string) gethostname(); + $this->title = $title ?? (string) gethostname(); $this->highPriorityLevel = Logger::toMonologLevel($highPriorityLevel); $this->emergencyLevel = Logger::toMonologLevel($emergencyLevel); $this->retry = $retry; $this->expire = $expire; } - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { $content = $this->buildContent($record); return $this->buildHeader($content) . $content; } - /** - * @phpstan-param FormattedRecord $record - */ - private function buildContent(array $record): string + private function buildContent(LogRecord $record): string { // Pushover has a limit of 512 characters on title and message combined. $maxMessageLength = 512 - strlen($this->title); - $message = ($this->useFormattedMessage) ? $record['formatted'] : $record['message']; + $message = ($this->useFormattedMessage) ? $record->formatted : $record->message; $message = Utils::substr($message, 0, $maxMessageLength); - $timestamp = $record['datetime']->getTimestamp(); + $timestamp = $record->datetime->getTimestamp(); $dataArray = [ 'token' => $this->token, @@ -164,23 +160,23 @@ private function buildContent(array $record): string 'timestamp' => $timestamp, ]; - if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) { + if ($record->level->value >= $this->emergencyLevel->value) { $dataArray['priority'] = 2; $dataArray['retry'] = $this->retry; $dataArray['expire'] = $this->expire; - } elseif (isset($record['level']) && $record['level'] >= $this->highPriorityLevel) { + } elseif ($record->level->value >= $this->highPriorityLevel->value) { $dataArray['priority'] = 1; } // First determine the available parameters - $context = array_intersect_key($record['context'], $this->parameterNames); - $extra = array_intersect_key($record['extra'], $this->parameterNames); + $context = array_intersect_key($record->context, $this->parameterNames); + $extra = array_intersect_key($record->extra, $this->parameterNames); // Least important info should be merged with subsequent info $dataArray = array_merge($extra, $context, $dataArray); // Only pass sounds that are supported by the API - if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds)) { + if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds, true)) { unset($dataArray['sound']); } @@ -198,7 +194,7 @@ private function buildHeader(string $content): string return $header; } - protected function write(array $record): void + protected function write(LogRecord $record): void { foreach ($this->users as $user) { $this->user = $user; @@ -211,25 +207,25 @@ protected function write(array $record): void } /** - * @param int|string $value + * @param int|string|Level|LogLevel::* $level * - * @phpstan-param Level|LevelName|LogLevel::* $value + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function setHighPriorityLevel($value): self + public function setHighPriorityLevel(int|string|Level $level): self { - $this->highPriorityLevel = Logger::toMonologLevel($value); + $this->highPriorityLevel = Logger::toMonologLevel($level); return $this; } /** - * @param int|string $value + * @param int|string|Level|LogLevel::* $level * - * @phpstan-param Level|LevelName|LogLevel::* $value + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function setEmergencyLevel($value): self + public function setEmergencyLevel(int|string|Level $level): self { - $this->emergencyLevel = Logger::toMonologLevel($value); + $this->emergencyLevel = Logger::toMonologLevel($level); return $this; } @@ -237,9 +233,9 @@ public function setEmergencyLevel($value): self /** * Use the formatted message? */ - public function useFormattedMessage(bool $value): self + public function useFormattedMessage(bool $useFormattedMessage): self { - $this->useFormattedMessage = $value; + $this->useFormattedMessage = $useFormattedMessage; return $this; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php index 91d16ea..5eee5dc 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php @@ -13,7 +13,10 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; +use Predis\Client as Predis; +use Redis; /** * Logs to a Redis key using rpush @@ -25,29 +28,21 @@ * $log->pushHandler($redis); * * @author Thomas Tourlourat - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class RedisHandler extends AbstractProcessingHandler { - /** @var \Predis\Client<\Predis\Client>|\Redis */ - private $redisClient; - /** @var string */ - private $redisKey; - /** @var int */ - protected $capSize; + /** @var Predis|Redis */ + private Predis|Redis $redisClient; + private string $redisKey; + protected int $capSize; /** - * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance - * @param string $key The key name to push records to - * @param int $capSize Number of entries to limit list size to, 0 = unlimited + * @param Predis|Redis $redis The redis instance + * @param string $key The key name to push records to + * @param int $capSize Number of entries to limit list size to, 0 = unlimited */ - public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true, int $capSize = 0) + public function __construct(Predis|Redis $redis, string $key, int|string|Level $level = Level::Debug, bool $bubble = true, int $capSize = 0) { - if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { - throw new \InvalidArgumentException('Predis\Client or Redis instance required'); - } - $this->redisClient = $redis; $this->redisKey = $key; $this->capSize = $capSize; @@ -56,43 +51,41 @@ public function __construct($redis, string $key, $level = Logger::DEBUG, bool $b } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - if ($this->capSize) { + if ($this->capSize > 0) { $this->writeCapped($record); } else { - $this->redisClient->rpush($this->redisKey, $record["formatted"]); + $this->redisClient->rpush($this->redisKey, $record->formatted); } } /** * Write and cap the collection * Writes the record to the redis list and caps its - * - * @phpstan-param FormattedRecord $record */ - protected function writeCapped(array $record): void + protected function writeCapped(LogRecord $record): void { - if ($this->redisClient instanceof \Redis) { - $mode = defined('\Redis::MULTI') ? \Redis::MULTI : 1; + if ($this->redisClient instanceof Redis) { + $mode = defined('Redis::MULTI') ? Redis::MULTI : 1; $this->redisClient->multi($mode) - ->rpush($this->redisKey, $record["formatted"]) + ->rPush($this->redisKey, $record->formatted) ->ltrim($this->redisKey, -$this->capSize, -1) ->exec(); } else { $redisKey = $this->redisKey; $capSize = $this->capSize; $this->redisClient->transaction(function ($tx) use ($record, $redisKey, $capSize) { - $tx->rpush($redisKey, $record["formatted"]); + $tx->rpush($redisKey, $record->formatted); $tx->ltrim($redisKey, -$capSize, -1); }); } } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php index 7789309..fa8e9e9 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php @@ -13,7 +13,10 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; +use Predis\Client as Predis; +use Redis; /** * Sends the message to a Redis Pub/Sub channel using PUBLISH @@ -21,28 +24,23 @@ * usage example: * * $log = new Logger('application'); - * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Logger::WARNING); + * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Level::Warning); * $log->pushHandler($redis); * * @author Gaëtan Faugère */ class RedisPubSubHandler extends AbstractProcessingHandler { - /** @var \Predis\Client<\Predis\Client>|\Redis */ - private $redisClient; - /** @var string */ - private $channelKey; + /** @var Predis|Redis */ + private Predis|Redis $redisClient; + private string $channelKey; /** - * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance - * @param string $key The channel key to publish records to + * @param Predis|Redis $redis The redis instance + * @param string $key The channel key to publish records to */ - public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(Predis|Redis $redis, string $key, int|string|Level $level = Level::Debug, bool $bubble = true) { - if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) { - throw new \InvalidArgumentException('Predis\Client or Redis instance required'); - } - $this->redisClient = $redis; $this->channelKey = $key; @@ -50,15 +48,15 @@ public function __construct($redis, string $key, $level = Logger::DEBUG, bool $b } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->redisClient->publish($this->channelKey, $record["formatted"]); + $this->redisClient->publish($this->channelKey, $record->formatted); } /** - * {@inheritDoc} + * @inheritDoc */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php index adcc939..1d12472 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php @@ -11,9 +11,10 @@ namespace Monolog\Handler; +use Monolog\Level; use Rollbar\RollbarLogger; use Throwable; -use Monolog\Logger; +use Monolog\LogRecord; /** * Sends errors to Rollbar @@ -33,37 +34,19 @@ */ class RollbarHandler extends AbstractProcessingHandler { - /** - * @var RollbarLogger - */ - protected $rollbarLogger; - - /** @var string[] */ - protected $levelMap = [ - Logger::DEBUG => 'debug', - Logger::INFO => 'info', - Logger::NOTICE => 'info', - Logger::WARNING => 'warning', - Logger::ERROR => 'error', - Logger::CRITICAL => 'critical', - Logger::ALERT => 'critical', - Logger::EMERGENCY => 'critical', - ]; + protected RollbarLogger $rollbarLogger; /** * Records whether any log records have been added since the last flush of the rollbar notifier - * - * @var bool */ - private $hasRecords = false; + private bool $hasRecords = false; - /** @var bool */ - protected $initialized = false; + protected bool $initialized = false; /** * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token */ - public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true) + public function __construct(RollbarLogger $rollbarLogger, int|string|Level $level = Level::Error, bool $bubble = true) { $this->rollbarLogger = $rollbarLogger; @@ -71,22 +54,41 @@ public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR } /** - * {@inheritDoc} + * Translates Monolog log levels to Rollbar levels. + * + * @return 'debug'|'info'|'warning'|'error'|'critical' + */ + protected function toRollbarLevel(Level $level): string + { + return match ($level) { + Level::Debug => 'debug', + Level::Info => 'info', + Level::Notice => 'info', + Level::Warning => 'warning', + Level::Error => 'error', + Level::Critical => 'critical', + Level::Alert => 'critical', + Level::Emergency => 'critical', + }; + } + + /** + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!$this->initialized) { // __destructor() doesn't get called on Fatal errors - register_shutdown_function(array($this, 'close')); + register_shutdown_function([$this, 'close']); $this->initialized = true; } - $context = $record['context']; - $context = array_merge($context, $record['extra'], [ - 'level' => $this->levelMap[$record['level']], - 'monolog_level' => $record['level_name'], - 'channel' => $record['channel'], - 'datetime' => $record['datetime']->format('U'), + $context = $record->context; + $context = array_merge($context, $record->extra, [ + 'level' => $this->toRollbarLevel($record->level), + 'monolog_level' => $record->level->getName(), + 'channel' => $record->channel, + 'datetime' => $record->datetime->format('U'), ]); if (isset($context['exception']) && $context['exception'] instanceof Throwable) { @@ -94,7 +96,7 @@ protected function write(array $record): void unset($context['exception']); $toLog = $exception; } else { - $toLog = $record['message']; + $toLog = $record->message; } // @phpstan-ignore-next-line @@ -112,7 +114,7 @@ public function flush(): void } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { @@ -120,9 +122,9 @@ public function close(): void } /** - * {@inheritDoc} + * @inheritDoc */ - public function reset() + public function reset(): void { $this->flush(); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php index 17745d2..9d57af9 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php @@ -12,8 +12,9 @@ namespace Monolog\Handler; use InvalidArgumentException; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Stores logs to files that are rotated every day and a limited number of files are kept. @@ -30,26 +31,19 @@ class RotatingFileHandler extends StreamHandler public const FILE_PER_MONTH = 'Y-m'; public const FILE_PER_YEAR = 'Y'; - /** @var string */ - protected $filename; - /** @var int */ - protected $maxFiles; - /** @var bool */ - protected $mustRotate; - /** @var \DateTimeImmutable */ - protected $nextRotation; - /** @var string */ - protected $filenameFormat; - /** @var string */ - protected $dateFormat; + protected string $filename; + protected int $maxFiles; + protected bool|null $mustRotate = null; + protected \DateTimeImmutable $nextRotation; + protected string $filenameFormat; + protected string $dateFormat; /** - * @param string $filename - * @param int $maxFiles The maximal amount of files to keep (0 means unlimited) - * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) - * @param bool $useLocking Try to lock log file before doing any writes + * @param int $maxFiles The maximal amount of files to keep (0 means unlimited) + * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) + * @param bool $useLocking Try to lock log file before doing any writes */ - public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + public function __construct(string $filename, int $maxFiles = 0, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) { $this->filename = Utils::canonicalizePath($filename); $this->maxFiles = $maxFiles; @@ -61,7 +55,7 @@ public function __construct(string $filename, int $maxFiles = 0, $level = Logger } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { @@ -73,9 +67,9 @@ public function close(): void } /** - * {@inheritDoc} + * @inheritDoc */ - public function reset() + public function reset(): void { parent::reset(); @@ -86,7 +80,7 @@ public function reset() public function setFilenameFormat(string $filenameFormat, string $dateFormat): self { - if (!preg_match('{^[Yy](([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) { + if (0 === preg_match('{^[Yy](([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) { throw new InvalidArgumentException( 'Invalid date format - format must be one of '. 'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '. @@ -108,16 +102,16 @@ public function setFilenameFormat(string $filenameFormat, string $dateFormat): s } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { // on the first record written, if the log is new, we should rotate (once per day) if (null === $this->mustRotate) { $this->mustRotate = null === $this->url || !file_exists($this->url); } - if ($this->nextRotation <= $record['datetime']) { + if ($this->nextRotation <= $record->datetime) { $this->mustRotate = true; $this->close(); } @@ -176,7 +170,7 @@ protected function getTimedFilename(): string $timedFilename = str_replace( ['{filename}', '{date}'], [$fileInfo['filename'], date($this->dateFormat)], - $fileInfo['dirname'] . '/' . $this->filenameFormat + ($fileInfo['dirname'] ?? '') . '/' . $this->filenameFormat ); if (isset($fileInfo['extension'])) { @@ -196,7 +190,7 @@ protected function getGlobPattern(): string ['[0-9][0-9][0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]'], $this->dateFormat) ], - $fileInfo['dirname'] . '/' . $this->filenameFormat + ($fileInfo['dirname'] ?? '') . '/' . $this->filenameFormat ); if (isset($fileInfo['extension'])) { $glob .= '.'.$fileInfo['extension']; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php index c128a32..511ec58 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php @@ -11,7 +11,9 @@ namespace Monolog\Handler; +use Closure; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Sampling handler @@ -26,52 +28,42 @@ * * @author Bryan Davis * @author Kunal Mehta - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface { use ProcessableHandlerTrait; /** - * @var HandlerInterface|callable - * @phpstan-var HandlerInterface|callable(Record|array{level: Level}|null, HandlerInterface): HandlerInterface + * Handler or factory Closure($record, $this) + * + * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface */ - protected $handler; + protected Closure|HandlerInterface $handler; - /** - * @var int $factor - */ - protected $factor; + protected int $factor; /** - * @psalm-param HandlerInterface|callable(Record|array{level: Level}|null, HandlerInterface): HandlerInterface $handler + * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler * - * @param callable|HandlerInterface $handler Handler or factory callable($record|null, $samplingHandler). - * @param int $factor Sample factor (e.g. 10 means every ~10th record is sampled) + * @param Closure|HandlerInterface $handler Handler or factory Closure($record|null, $samplingHandler). + * @param int $factor Sample factor (e.g. 10 means every ~10th record is sampled) */ - public function __construct($handler, int $factor) + public function __construct(Closure|HandlerInterface $handler, int $factor) { parent::__construct(); $this->handler = $handler; $this->factor = $factor; - - if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) { - throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object"); - } } - public function isHandling(array $record): bool + public function isHandling(LogRecord $record): bool { return $this->getHandler($record)->isHandling($record); } - public function handle(array $record): bool + public function handle(LogRecord $record): bool { if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) { - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } @@ -84,26 +76,23 @@ public function handle(array $record): bool /** * Return the nested handler * - * If the handler was provided as a factory callable, this will trigger the handler's instantiation. - * - * @phpstan-param Record|array{level: Level}|null $record - * - * @return HandlerInterface + * If the handler was provided as a factory, this will trigger the handler's instantiation. */ - public function getHandler(array $record = null) + public function getHandler(LogRecord $record = null): HandlerInterface { if (!$this->handler instanceof HandlerInterface) { - $this->handler = ($this->handler)($record, $this); - if (!$this->handler instanceof HandlerInterface) { - throw new \RuntimeException("The factory callable should return a HandlerInterface"); + $handler = ($this->handler)($record, $this); + if (!$handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory Closure should return a HandlerInterface"); } + $this->handler = $handler; } return $this->handler; } /** - * {@inheritDoc} + * @inheritDoc */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -118,7 +107,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function getFormatter(): FormatterInterface { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php index 1280ee7..b8f574b 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; /** * SendGridrHandler uses the SendGrid API v2 function to send Log emails, more information in https://sendgrid.com/docs/API_Reference/Web_API/mail.html @@ -22,33 +22,29 @@ class SendGridHandler extends MailHandler { /** * The SendGrid API User - * @var string */ - protected $apiUser; + protected string $apiUser; /** * The SendGrid API Key - * @var string */ - protected $apiKey; + protected string $apiKey; /** * The email addresses to which the message will be sent - * @var string */ - protected $from; + protected string $from; /** * The email addresses to which the message will be sent * @var string[] */ - protected $to; + protected array $to; /** * The subject of the email - * @var string */ - protected $subject; + protected string $subject; /** * @param string $apiUser The SendGrid API User @@ -56,8 +52,10 @@ class SendGridHandler extends MailHandler * @param string $from The sender of the email * @param string|string[] $to The recipients of the email * @param string $subject The subject of the mail + * + * @throws MissingExtensionException If the curl extension is missing */ - public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, $level = Logger::ERROR, bool $bubble = true) + public function __construct(string $apiUser, string $apiKey, string $from, string|array $to, string $subject, int|string|Level $level = Level::Error, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); @@ -72,7 +70,7 @@ public function __construct(string $apiUser, string $apiKey, string $from, $to, } /** - * {@inheritDoc} + * @inheritDoc */ protected function send(string $content, array $records): void { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php index 71a4109..7e9cccc 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php @@ -11,10 +11,11 @@ namespace Monolog\Handler\Slack; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; +use Monolog\LogRecord; /** * Slack record utility helping to log to Slack webhooks or API. @@ -23,9 +24,6 @@ * @author Haralan Dobrev * @see https://api.slack.com/incoming-webhooks * @see https://api.slack.com/docs/message-attachments - * - * @phpstan-import-type FormattedRecord from \Monolog\Handler\AbstractProcessingHandler - * @phpstan-import-type Record from \Monolog\Logger */ class SlackRecord { @@ -39,55 +37,43 @@ class SlackRecord /** * Slack channel (encoded ID or name) - * @var string|null */ - private $channel; + private string|null $channel; /** * Name of a bot - * @var string|null */ - private $username; + private string|null $username; /** * User icon e.g. 'ghost', 'http://example.com/user.png' - * @var string|null */ - private $userIcon; + private string|null $userIcon; /** * Whether the message should be added to Slack as attachment (plain text otherwise) - * @var bool */ - private $useAttachment; + private bool $useAttachment; /** * Whether the the context/extra messages added to Slack as attachments are in a short style - * @var bool */ - private $useShortAttachment; + private bool $useShortAttachment; /** * Whether the attachment should include context and extra data - * @var bool */ - private $includeContextAndExtra; + private bool $includeContextAndExtra; /** * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] * @var string[] */ - private $excludeFields; + private array $excludeFields; - /** - * @var ?FormatterInterface - */ - private $formatter; + private FormatterInterface|null $formatter; - /** - * @var NormalizerFormatter - */ - private $normalizerFormatter; + private NormalizerFormatter $normalizerFormatter; /** * @param string[] $excludeFields @@ -99,7 +85,7 @@ public function __construct( ?string $userIcon = null, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - array $excludeFields = array(), + array $excludeFields = [], FormatterInterface $formatter = null ) { $this @@ -121,77 +107,76 @@ public function __construct( * Returns required data in format that Slack * is expecting. * - * @phpstan-param FormattedRecord $record * @phpstan-return mixed[] */ - public function getSlackData(array $record): array + public function getSlackData(LogRecord $record): array { - $dataArray = array(); - $record = $this->removeExcludedFields($record); + $dataArray = []; - if ($this->username) { + if ($this->username !== null) { $dataArray['username'] = $this->username; } - if ($this->channel) { + if ($this->channel !== null) { $dataArray['channel'] = $this->channel; } - if ($this->formatter && !$this->useAttachment) { - /** @phpstan-ignore-next-line */ + if ($this->formatter !== null && !$this->useAttachment) { $message = $this->formatter->format($record); } else { - $message = $record['message']; + $message = $record->message; } + $recordData = $this->removeExcludedFields($record); + if ($this->useAttachment) { - $attachment = array( - 'fallback' => $message, - 'text' => $message, - 'color' => $this->getAttachmentColor($record['level']), - 'fields' => array(), - 'mrkdwn_in' => array('fields'), - 'ts' => $record['datetime']->getTimestamp(), + $attachment = [ + 'fallback' => $message, + 'text' => $message, + 'color' => $this->getAttachmentColor($record->level), + 'fields' => [], + 'mrkdwn_in' => ['fields'], + 'ts' => $recordData['datetime']->getTimestamp(), 'footer' => $this->username, 'footer_icon' => $this->userIcon, - ); + ]; if ($this->useShortAttachment) { - $attachment['title'] = $record['level_name']; + $attachment['title'] = $recordData['level_name']; } else { $attachment['title'] = 'Message'; - $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']); + $attachment['fields'][] = $this->generateAttachmentField('Level', $recordData['level_name']); } if ($this->includeContextAndExtra) { - foreach (array('extra', 'context') as $key) { - if (empty($record[$key])) { + foreach (['extra', 'context'] as $key) { + if (!isset($recordData[$key]) || \count($recordData[$key]) === 0) { continue; } if ($this->useShortAttachment) { $attachment['fields'][] = $this->generateAttachmentField( - (string) $key, - $record[$key] + $key, + $recordData[$key] ); } else { // Add all extra fields as individual fields in attachment $attachment['fields'] = array_merge( $attachment['fields'], - $this->generateAttachmentFields($record[$key]) + $this->generateAttachmentFields($recordData[$key]) ); } } } - $dataArray['attachments'] = array($attachment); + $dataArray['attachments'] = [$attachment]; } else { $dataArray['text'] = $message; } - if ($this->userIcon) { - if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) { - $dataArray['icon_url'] = $this->userIcon; + if ($this->userIcon !== null) { + if (false !== ($iconUrl = filter_var($this->userIcon, FILTER_VALIDATE_URL))) { + $dataArray['icon_url'] = $iconUrl; } else { $dataArray['icon_emoji'] = ":{$this->userIcon}:"; } @@ -204,18 +189,14 @@ public function getSlackData(array $record): array * Returns a Slack message attachment color associated with * provided level. */ - public function getAttachmentColor(int $level): string + public function getAttachmentColor(Level $level): string { - switch (true) { - case $level >= Logger::ERROR: - return static::COLOR_DANGER; - case $level >= Logger::WARNING: - return static::COLOR_WARNING; - case $level >= Logger::INFO: - return static::COLOR_GOOD; - default: - return static::COLOR_DEFAULT; - } + return match ($level) { + Level::Error, Level::Critical, Level::Alert, Level::Emergency => static::COLOR_DANGER, + Level::Warning => static::COLOR_WARNING, + Level::Info, Level::Notice => static::COLOR_GOOD, + Level::Debug => static::COLOR_DEFAULT + }; } /** @@ -225,13 +206,13 @@ public function getAttachmentColor(int $level): string */ public function stringify(array $fields): string { - /** @var Record $fields */ - $normalized = $this->normalizerFormatter->format($fields); + /** @var array $normalized */ + $normalized = $this->normalizerFormatter->normalizeValue($fields); - $hasSecondDimension = count(array_filter($normalized, 'is_array')); - $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric')); + $hasSecondDimension = \count(array_filter($normalized, 'is_array')) > 0; + $hasOnlyNonNumericKeys = \count(array_filter(array_keys($normalized), 'is_numeric')) === 0; - return $hasSecondDimension || $hasNonNumericKeys + return $hasSecondDimension || $hasOnlyNonNumericKeys ? Utils::jsonEncode($normalized, JSON_PRETTY_PRINT|Utils::DEFAULT_JSON_FLAGS) : Utils::jsonEncode($normalized, Utils::DEFAULT_JSON_FLAGS); } @@ -330,11 +311,11 @@ private function generateAttachmentField(string $title, $value): array ? sprintf('```%s```', substr($this->stringify($value), 0, 1990)) : $value; - return array( + return [ 'title' => ucfirst($title), 'value' => $value, 'short' => false, - ); + ]; } /** @@ -346,10 +327,10 @@ private function generateAttachmentField(string $title, $value): array */ private function generateAttachmentFields(array $data): array { - /** @var Record $data */ - $normalized = $this->normalizerFormatter->format($data); + /** @var array $normalized */ + $normalized = $this->normalizerFormatter->normalizeValue($data); - $fields = array(); + $fields = []; foreach ($normalized as $key => $value) { $fields[] = $this->generateAttachmentField((string) $key, $value); } @@ -360,15 +341,14 @@ private function generateAttachmentFields(array $data): array /** * Get a copy of record with fields excluded according to $this->excludeFields * - * @phpstan-param FormattedRecord $record - * * @return mixed[] */ - private function removeExcludedFields(array $record): array + private function removeExcludedFields(LogRecord $record): array { + $recordData = $record->toArray(); foreach ($this->excludeFields as $field) { $keys = explode('.', $field); - $node = &$record; + $node = &$recordData; $lastKey = end($keys); foreach ($keys as $key) { if (!isset($node[$key])) { @@ -382,6 +362,6 @@ private function removeExcludedFields(array $record): array } } - return $record; + return $recordData; } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php index a648513..321d866 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php @@ -12,31 +12,28 @@ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Handler\Slack\SlackRecord; +use Monolog\LogRecord; /** * Sends notifications through Slack API * * @author Greg Kedzierski * @see https://api.slack.com/ - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class SlackHandler extends SocketHandler { /** * Slack API token - * @var string */ - private $token; + private string $token; /** * Instance of the SlackRecord util class preparing data for Slack API. - * @var SlackRecord */ - private $slackRecord; + private SlackRecord $slackRecord; /** * @param string $token Slack API token @@ -55,11 +52,11 @@ public function __construct( ?string $username = null, bool $useAttachment = true, ?string $iconEmoji = null, - $level = Logger::CRITICAL, + $level = Level::Critical, bool $bubble = true, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - array $excludeFields = array(), + array $excludeFields = [], bool $persistent = false, float $timeout = 0.0, float $writingTimeout = 10.0, @@ -105,9 +102,9 @@ public function getToken(): string } /** - * {@inheritDoc} + * @inheritDoc */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { $content = $this->buildContent($record); @@ -116,10 +113,8 @@ protected function generateDataStream(array $record): string /** * Builds the body of API call - * - * @phpstan-param FormattedRecord $record */ - private function buildContent(array $record): string + private function buildContent(LogRecord $record): string { $dataArray = $this->prepareContentData($record); @@ -127,15 +122,14 @@ private function buildContent(array $record): string } /** - * @phpstan-param FormattedRecord $record * @return string[] */ - protected function prepareContentData(array $record): array + protected function prepareContentData(LogRecord $record): array { $dataArray = $this->slackRecord->getSlackData($record); $dataArray['token'] = $this->token; - if (!empty($dataArray['attachments'])) { + if (isset($dataArray['attachments']) && is_array($dataArray['attachments']) && \count($dataArray['attachments']) > 0) { $dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']); } @@ -157,9 +151,9 @@ private function buildHeader(string $content): string } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { parent::write($record); $this->finalizeWrite(); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php index 8ae3c78..6466ba3 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php @@ -12,9 +12,10 @@ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; use Monolog\Handler\Slack\SlackRecord; +use Monolog\LogRecord; /** * Sends notifications through Slack Webhooks @@ -26,15 +27,13 @@ class SlackWebhookHandler extends AbstractProcessingHandler { /** * Slack Webhook token - * @var string */ - private $webhookUrl; + private string $webhookUrl; /** * Instance of the SlackRecord util class preparing data for Slack API. - * @var SlackRecord */ - private $slackRecord; + private SlackRecord $slackRecord; /** * @param string $webhookUrl Slack Webhook URL @@ -45,6 +44,8 @@ class SlackWebhookHandler extends AbstractProcessingHandler * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style * @param bool $includeContextAndExtra Whether the attachment should include context and extra data * @param string[] $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] + * + * @throws MissingExtensionException If the curl extension is missing */ public function __construct( string $webhookUrl, @@ -54,9 +55,9 @@ public function __construct( ?string $iconEmoji = null, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - $level = Logger::CRITICAL, + $level = Level::Critical, bool $bubble = true, - array $excludeFields = array() + array $excludeFields = [] ) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler'); @@ -88,21 +89,21 @@ public function getWebhookUrl(): string } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { $postData = $this->slackRecord->getSlackData($record); $postString = Utils::jsonEncode($postData); $ch = curl_init(); - $options = array( + $options = [ CURLOPT_URL => $this->webhookUrl, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, - CURLOPT_HTTPHEADER => array('Content-type: application/json'), + CURLOPT_HTTPHEADER => ['Content-type: application/json'], CURLOPT_POSTFIELDS => $postString, - ); + ]; if (defined('CURLOPT_SAFE_UPLOAD')) { $options[CURLOPT_SAFE_UPLOAD] = true; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php index 21701af..c5f7088 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php @@ -11,41 +11,29 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Stores to any socket - uses fsockopen() or pfsockopen(). * * @author Pablo de Leon Belloc * @see http://php.net/manual/en/function.fsockopen.php - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class SocketHandler extends AbstractProcessingHandler { - /** @var string */ - private $connectionString; - /** @var float */ - private $connectionTimeout; + private string $connectionString; + private float $connectionTimeout; /** @var resource|null */ private $resource; - /** @var float */ - private $timeout; - /** @var float */ - private $writingTimeout; - /** @var ?int */ - private $lastSentBytes = null; - /** @var ?int */ - private $chunkSize; - /** @var bool */ - private $persistent; - /** @var ?int */ - private $errno = null; - /** @var ?string */ - private $errstr = null; - /** @var ?float */ - private $lastWritingAt = null; + private float $timeout; + private float $writingTimeout; + private int|null $lastSentBytes = null; + private int|null $chunkSize; + private bool $persistent; + private int|null $errno = null; + private string|null $errstr = null; + private float|null $lastWritingAt = null; /** * @param string $connectionString Socket connection string @@ -56,11 +44,11 @@ class SocketHandler extends AbstractProcessingHandler * established * @param int|null $chunkSize Sets the chunk size. Only has effect during connection in the writing cycle * - * @throws \InvalidArgumentException If an invalid timeout value (less than 0) is passed. + * @throws \InvalidArgumentException If an invalid timeout value (less than 0) is passed. */ public function __construct( string $connectionString, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -87,12 +75,12 @@ public function __construct( /** * Connect (if necessary) and write to the socket * - * {@inheritDoc} + * @inheritDoc * * @throws \UnexpectedValueException * @throws \RuntimeException */ - protected function write(array $record): void + protected function write(LogRecord $record): void { $this->connectIfNotConnected(); $data = $this->generateDataStream($record); @@ -213,8 +201,6 @@ public function getTimeout(): float /** * Get current local writing timeout - * - * @return float */ public function getWritingTimeout(): float { @@ -264,10 +250,8 @@ protected function fsockopen() * Wrapper to allow mocking * * @see http://php.net/manual/en/function.stream-set-timeout.php - * - * @return bool */ - protected function streamSetTimeout() + protected function streamSetTimeout(): bool { $seconds = floor($this->timeout); $microseconds = round(($this->timeout - $seconds) * 1e6); @@ -284,9 +268,9 @@ protected function streamSetTimeout() * * @see http://php.net/manual/en/function.stream-set-chunk-size.php * - * @return int|bool + * @return int|false */ - protected function streamSetChunkSize() + protected function streamSetChunkSize(): int|bool { if (!is_resource($this->resource)) { throw new \LogicException('streamSetChunkSize called but $this->resource is not a resource'); @@ -302,9 +286,9 @@ protected function streamSetChunkSize() /** * Wrapper to allow mocking * - * @return int|bool + * @return int|false */ - protected function fwrite(string $data) + protected function fwrite(string $data): int|bool { if (!is_resource($this->resource)) { throw new \LogicException('fwrite called but $this->resource is not a resource'); @@ -318,7 +302,7 @@ protected function fwrite(string $data) * * @return mixed[]|bool */ - protected function streamGetMetadata() + protected function streamGetMetadata(): array|bool { if (!is_resource($this->resource)) { throw new \LogicException('streamGetMetadata called but $this->resource is not a resource'); @@ -342,12 +326,9 @@ private function connectIfNotConnected(): void $this->connect(); } - /** - * @phpstan-param FormattedRecord $record - */ - protected function generateDataStream(array $record): string + protected function generateDataStream(LogRecord $record): string { - return (string) $record['formatted']; + return (string) $record->formatted; } /** @@ -387,7 +368,7 @@ private function setSocketTimeout(): void private function setStreamChunkSize(): void { - if ($this->chunkSize && !$this->streamSetChunkSize()) { + if (null !== $this->chunkSize && false === $this->streamSetChunkSize()) { throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()"); } } @@ -408,7 +389,7 @@ private function writeToSocket(string $data): void } $sent += $chunk; $socketInfo = $this->streamGetMetadata(); - if (is_array($socketInfo) && $socketInfo['timed_out']) { + if (is_array($socketInfo) && (bool) $socketInfo['timed_out']) { throw new \RuntimeException("Write timed-out"); } @@ -437,7 +418,7 @@ private function writingIsTimedOut(int $sent): bool usleep(100); } - if ((microtime(true) - $this->lastWritingAt) >= $this->writingTimeout) { + if ((microtime(true) - (float) $this->lastWritingAt) >= $this->writingTimeout) { $this->closeSocket(); return true; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php index dcf282b..b4512a6 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php @@ -12,8 +12,9 @@ namespace Monolog\Handler; use Aws\Sqs\SqsClient; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Writes to any sqs queue. @@ -27,12 +28,10 @@ class SqsHandler extends AbstractProcessingHandler /** 100 KB in bytes - head message size for new error log */ protected const HEAD_MESSAGE_SIZE = 102400; - /** @var SqsClient */ - private $client; - /** @var string */ - private $queueUrl; + private SqsClient $client; + private string $queueUrl; - public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true) + public function __construct(SqsClient $sqsClient, string $queueUrl, int|string|Level $level = Level::Debug, bool $bubble = true) { parent::__construct($level, $bubble); @@ -41,15 +40,15 @@ public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Log } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - if (!isset($record['formatted']) || 'string' !== gettype($record['formatted'])) { + if (!isset($record->formatted) || 'string' !== gettype($record->formatted)) { throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string' . Utils::getRecordMessageForException($record)); } - $messageBody = $record['formatted']; + $messageBody = $record->formatted; if (strlen($messageBody) >= static::MAX_MESSAGE_SIZE) { $messageBody = Utils::substr($messageBody, 0, static::HEAD_MESSAGE_SIZE); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php index 6518351..027a721 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Stores to any stream resource @@ -20,29 +21,21 @@ * Can be used to store into php://stderr, remote and local files, etc. * * @author Jordi Boggiano - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class StreamHandler extends AbstractProcessingHandler { - /** @const int */ protected const MAX_CHUNK_SIZE = 2147483647; - /** @const int 10MB */ + /** 10MB */ protected const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024; - /** @var int */ - protected $streamChunkSize; + protected int $streamChunkSize; /** @var resource|null */ protected $stream; - /** @var ?string */ - protected $url = null; - /** @var ?string */ - private $errorMessage = null; - /** @var ?int */ - protected $filePermission; - /** @var bool */ - protected $useLocking; + protected string|null $url = null; + private string|null $errorMessage = null; + protected int|null $filePermission; + protected bool $useLocking; /** @var true|null */ - private $dirCreated = null; + private bool|null $dirCreated = null; /** * @param resource|string $stream If a missing path can't be created, an UnexpectedValueException will be thrown on first write @@ -51,7 +44,7 @@ class StreamHandler extends AbstractProcessingHandler * * @throws \InvalidArgumentException If stream is not a resource or string */ - public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + public function __construct($stream, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) { parent::__construct($level, $bubble); @@ -83,11 +76,11 @@ public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { - if ($this->url && is_resource($this->stream)) { + if (null !== $this->url && is_resource($this->stream)) { fclose($this->stream); } $this->stream = null; @@ -106,26 +99,21 @@ public function getStream() /** * Return the stream URL if it was configured with a URL and not an active resource - * - * @return string|null */ public function getUrl(): ?string { return $this->url; } - /** - * @return int - */ public function getStreamChunkSize(): int { return $this->streamChunkSize; } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!is_resource($this->stream)) { $url = $this->url; @@ -150,10 +138,6 @@ protected function write(array $record): void } $stream = $this->stream; - if (!is_resource($stream)) { - throw new \LogicException('No stream was opened yet' . Utils::getRecordMessageForException($record)); - } - if ($this->useLocking) { // ignoring errors here, there's not much we can do about them flock($stream, LOCK_EX); @@ -169,13 +153,10 @@ protected function write(array $record): void /** * Write to stream * @param resource $stream - * @param array $record - * - * @phpstan-param FormattedRecord $record */ - protected function streamWrite($stream, array $record): void + protected function streamWrite($stream, LogRecord $record): void { - fwrite($stream, (string) $record['formatted']); + fwrite($stream, (string) $record->formatted); } private function customErrorHandler(int $code, string $msg): bool @@ -202,7 +183,7 @@ private function getDirFromStream(string $stream): ?string private function createDir(string $url): void { // Do not try to create dir if it has already been tried. - if ($this->dirCreated) { + if (true === $this->dirCreated) { return; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php index 130e6f1..842b657 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php @@ -11,7 +11,10 @@ namespace Monolog\Handler; +use Closure; +use Monolog\Level; use Monolog\Logger; +use Monolog\LogRecord; use Monolog\Utils; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; @@ -23,23 +26,20 @@ * SymfonyMailerHandler uses Symfony's Mailer component to send the emails * * @author Jordi Boggiano - * - * @phpstan-import-type Record from \Monolog\Logger */ class SymfonyMailerHandler extends MailHandler { - /** @var MailerInterface|TransportInterface */ - protected $mailer; - /** @var Email|callable(string, Record[]): Email */ - private $emailTemplate; + protected MailerInterface|TransportInterface $mailer; + /** @var Email|Closure(string, LogRecord[]): Email */ + private Email|Closure $emailTemplate; /** - * @psalm-param Email|callable(string, Record[]): Email $email + * @phpstan-param Email|Closure(string, LogRecord[]): Email $email * * @param MailerInterface|TransportInterface $mailer The mailer to use - * @param callable|Email $email An email template, the subject/body will be replaced + * @param Closure|Email $email An email template, the subject/body will be replaced */ - public function __construct($mailer, $email, $level = Logger::ERROR, bool $bubble = true) + public function __construct($mailer, Email|Closure $email, int|string|Level $level = Level::Error, bool $bubble = true) { parent::__construct($level, $bubble); @@ -68,10 +68,8 @@ protected function getSubjectFormatter(?string $format): FormatterInterface /** * Creates instance of Email to be sent * - * @param string $content formatted email body to be sent - * @param array $records Log records that formed the content - * - * @phpstan-param Record[] $records + * @param string $content formatted email body to be sent + * @param LogRecord[] $records Log records that formed the content */ protected function buildMessage(string $content, array $records): Email { @@ -84,10 +82,10 @@ protected function buildMessage(string $content, array $records): Email if (!$message instanceof Email) { $record = reset($records); - throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it' . ($record ? Utils::getRecordMessageForException($record) : '')); + throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it' . ($record instanceof LogRecord ? Utils::getRecordMessageForException($record) : '')); } - if ($records) { + if (\count($records) > 0) { $subjectFormatter = $this->getSubjectFormatter($message->getSubject()); $message->subject($subjectFormatter->format($this->getHighestRecord($records))); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php index 1d543b7..0816a01 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php @@ -11,8 +11,9 @@ namespace Monolog\Handler; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Logs to syslog service. @@ -29,17 +30,14 @@ */ class SyslogHandler extends AbstractSyslogHandler { - /** @var string */ - protected $ident; - /** @var int */ - protected $logopts; + protected string $ident; + protected int $logopts; /** - * @param string $ident * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID */ - public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID) + public function __construct(string $ident, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, int $logopts = LOG_PID) { parent::__construct($facility, $level, $bubble); @@ -48,7 +46,7 @@ public function __construct(string $ident, $facility = LOG_USER, $level = Logger } /** - * {@inheritDoc} + * @inheritDoc */ public function close(): void { @@ -56,13 +54,13 @@ public function close(): void } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { if (!openlog($this->ident, $this->logopts, $this->facility)) { throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"' . Utils::getRecordMessageForException($record)); } - syslog($this->logLevels[$record['level']], (string) $record['formatted']); + syslog($this->toSyslogPriority($record->level), (string) $record->formatted); } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php index dbd8ef6..6a48334 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php @@ -18,12 +18,9 @@ class UdpSocket { protected const DATAGRAM_MAX_LENGTH = 65023; - /** @var string */ - protected $ip; - /** @var int */ - protected $port; - /** @var resource|Socket|null */ - protected $socket = null; + protected string $ip; + protected int $port; + protected ?Socket $socket = null; public function __construct(string $ip, int $port = 514) { @@ -31,28 +28,20 @@ public function __construct(string $ip, int $port = 514) $this->port = $port; } - /** - * @param string $line - * @param string $header - * @return void - */ - public function write($line, $header = "") + public function write(string $line, string $header = ""): void { $this->send($this->assembleMessage($line, $header)); } public function close(): void { - if (is_resource($this->socket) || $this->socket instanceof Socket) { + if ($this->socket instanceof Socket) { socket_close($this->socket); $this->socket = null; } } - /** - * @return resource|Socket - */ - protected function getSocket() + protected function getSocket(): Socket { if (null !== $this->socket) { return $this->socket; @@ -66,12 +55,12 @@ protected function getSocket() $protocol = IPPROTO_IP; } - $this->socket = socket_create($domain, SOCK_DGRAM, $protocol) ?: null; - if (null === $this->socket) { - throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create'); + $socket = socket_create($domain, SOCK_DGRAM, $protocol); + if ($socket instanceof Socket) { + return $this->socket = $socket; } - return $this->socket; + throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create'); } protected function send(string $chunk): void diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php index deaa19f..16a7286 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php @@ -12,8 +12,9 @@ namespace Monolog\Handler; use DateTimeInterface; -use Monolog\Logger; use Monolog\Handler\SyslogUdp\UdpSocket; +use Monolog\Level; +use Monolog\LogRecord; use Monolog\Utils; /** @@ -29,31 +30,29 @@ class SyslogUdpHandler extends AbstractSyslogHandler const RFC5424e = 2; /** @var array */ - private $dateFormats = array( + private array $dateFormats = [ self::RFC3164 => 'M d H:i:s', self::RFC5424 => \DateTime::RFC3339, self::RFC5424e => \DateTime::RFC3339_EXTENDED, - ); + ]; - /** @var UdpSocket */ - protected $socket; - /** @var string */ - protected $ident; + protected UdpSocket $socket; + protected string $ident; /** @var self::RFC* */ - protected $rfc; + protected int $rfc; /** - * @param string $host Either IP/hostname or a path to a unix socket (port must be 0 then) - * @param int $port Port number, or 0 if $host is a unix socket - * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant - * @param bool $bubble Whether the messages that are handled can bubble up the stack or not - * @param string $ident Program name or tag for each log message. - * @param int $rfc RFC to format the message for. - * @throws MissingExtensionException + * @param string $host Either IP/hostname or a path to a unix socket (port must be 0 then) + * @param int $port Port number, or 0 if $host is a unix socket + * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant + * @param bool $bubble Whether the messages that are handled can bubble up the stack or not + * @param string $ident Program name or tag for each log message. + * @param int $rfc RFC to format the message for. + * @throws MissingExtensionException when there is no socket extension * * @phpstan-param self::RFC* $rfc */ - public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) + public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) { if (!extension_loaded('sockets')) { throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler'); @@ -67,11 +66,11 @@ public function __construct(string $host, int $port = 514, $facility = LOG_USER, $this->socket = new UdpSocket($host, $port); } - protected function write(array $record): void + protected function write(LogRecord $record): void { - $lines = $this->splitMessageIntoLines($record['formatted']); + $lines = $this->splitMessageIntoLines($record->formatted); - $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']], $record['datetime']); + $header = $this->makeCommonSyslogHeader($this->toSyslogPriority($record->level), $record->datetime); foreach ($lines as $line) { $this->socket->write($line, $header); @@ -96,6 +95,7 @@ private function splitMessageIntoLines($message): array $lines = preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY); if (false === $lines) { $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode)); } @@ -109,11 +109,13 @@ protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $date { $priority = $severity + $this->facility; - if (!$pid = getmypid()) { + $pid = getmypid(); + if (false === $pid) { $pid = '-'; } - if (!$hostname = gethostname()) { + $hostname = gethostname(); + if (false === $hostname) { $hostname = '-'; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php index 8912eba..7b5b8a5 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php @@ -12,8 +12,9 @@ namespace Monolog\Handler; use RuntimeException; -use Monolog\Logger; +use Monolog\Level; use Monolog\Utils; +use Monolog\LogRecord; /** * Handler send logs to Telegram using Telegram Bot API. @@ -28,8 +29,6 @@ * @link https://core.telegram.org/bots/api * * @author Mazur Alexandr - * - * @phpstan-import-type Record from \Monolog\Logger */ class TelegramBotHandler extends AbstractProcessingHandler { @@ -52,69 +51,61 @@ class TelegramBotHandler extends AbstractProcessingHandler /** * Telegram bot access token provided by BotFather. * Create telegram bot with https://telegram.me/BotFather and use access token from it. - * @var string */ - private $apiKey; + private string $apiKey; /** * Telegram channel name. * Since to start with '@' symbol as prefix. - * @var string */ - private $channel; + private string $channel; /** * The kind of formatting that is used for the message. * See available options at https://core.telegram.org/bots/api#formatting-options * or in AVAILABLE_PARSE_MODES - * @var ?string */ - private $parseMode; + private string|null $parseMode; /** * Disables link previews for links in the message. - * @var ?bool */ - private $disableWebPagePreview; + private bool|null $disableWebPagePreview; /** * Sends the message silently. Users will receive a notification with no sound. - * @var ?bool */ - private $disableNotification; + private bool|null $disableNotification; /** * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages. * False - truncates a message that is too long. - * @var bool */ - private $splitLongMessages; + private bool $splitLongMessages; /** * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). - * @var bool */ - private $delayBetweenMessages; + private bool $delayBetweenMessages; /** - * @param string $apiKey Telegram bot access token provided by BotFather - * @param string $channel Telegram channel name - * @param bool $splitLongMessages Split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages - * @param bool $delayBetweenMessages Adds delay between sending a split message according to Telegram API - * @throws MissingExtensionException + * @param string $apiKey Telegram bot access token provided by BotFather + * @param string $channel Telegram channel name + * @param bool $splitLongMessages Split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages + * @param bool $delayBetweenMessages Adds delay between sending a split message according to Telegram API + * @throws MissingExtensionException If the curl extension is missing */ public function __construct( string $apiKey, string $channel, - $level = Logger::DEBUG, + $level = Level::Debug, bool $bubble = true, string $parseMode = null, bool $disableWebPagePreview = null, bool $disableNotification = null, bool $splitLongMessages = false, bool $delayBetweenMessages = false - ) - { + ) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler'); } @@ -132,7 +123,7 @@ public function __construct( public function setParseMode(string $parseMode = null): self { - if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES)) { + if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES, true)) { throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.'); } @@ -158,7 +149,6 @@ public function disableNotification(bool $disableNotification = null): self /** * True - split a message longer than MAX_MESSAGE_LENGTH into parts and send in multiple messages. * False - truncates a message that is too long. - * @param bool $splitLongMessages * @return $this */ public function splitLongMessages(bool $splitLongMessages = false): self @@ -170,7 +160,6 @@ public function splitLongMessages(bool $splitLongMessages = false): self /** * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). - * @param bool $delayBetweenMessages * @return $this */ public function delayBetweenMessages(bool $delayBetweenMessages = false): self @@ -181,11 +170,10 @@ public function delayBetweenMessages(bool $delayBetweenMessages = false): self } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { - /** @var Record[] $messages */ $messages = []; foreach ($records as $record) { @@ -193,30 +181,28 @@ public function handleBatch(array $records): void continue; } - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } $messages[] = $record; } - if (!empty($messages)) { - $this->send((string)$this->getFormatter()->formatBatch($messages)); + if (\count($messages) > 0) { + $this->send((string) $this->getFormatter()->formatBatch($messages)); } } /** * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->send($record['formatted']); + $this->send($record->formatted); } /** * Send request to @link https://api.telegram.org/bot on SendMessage action. - * @param string $message */ protected function send(string $message): void { @@ -259,7 +245,6 @@ protected function sendCurl(string $message): void /** * Handle a message that is too long: truncates or splits into several - * @param string $message * @return string[] */ private function handleMessageLength(string $message): array diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php index 0986da2..1884f83 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php @@ -11,8 +11,10 @@ namespace Monolog\Handler; +use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Used for testing purposes. @@ -65,85 +67,67 @@ * @method bool hasNoticeThatPasses($message) * @method bool hasInfoThatPasses($message) * @method bool hasDebugThatPasses($message) - * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class TestHandler extends AbstractProcessingHandler { - /** @var Record[] */ - protected $records = []; - /** @var array */ - protected $recordsByLevel = []; - /** @var bool */ - private $skipReset = false; + /** @var LogRecord[] */ + protected array $records = []; + /** @phpstan-var array, LogRecord[]> */ + protected array $recordsByLevel = []; + private bool $skipReset = false; /** - * @return array - * - * @phpstan-return Record[] + * @return array */ - public function getRecords() + public function getRecords(): array { return $this->records; } - /** - * @return void - */ - public function clear() + public function clear(): void { $this->records = []; $this->recordsByLevel = []; } - /** - * @return void - */ - public function reset() + public function reset(): void { if (!$this->skipReset) { $this->clear(); } } - /** - * @return void - */ - public function setSkipReset(bool $skipReset) + public function setSkipReset(bool $skipReset): void { $this->skipReset = $skipReset; } /** - * @param string|int $level Logging level value or name + * @param int|string|Level|LogLevel::* $level Logging level value or name * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function hasRecords($level): bool + public function hasRecords(int|string|Level $level): bool { - return isset($this->recordsByLevel[Logger::toMonologLevel($level)]); + return isset($this->recordsByLevel[Logger::toMonologLevel($level)->value]); } /** - * @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records - * @param string|int $level Logging level value or name + * @param string|array $recordAssertions Either a message string or an array containing message and optionally context keys that will be checked against all records * - * @phpstan-param array{message: string, context?: mixed[]}|string $record - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param array{message: string, context?: mixed[]}|string $recordAssertions */ - public function hasRecord($record, $level): bool + public function hasRecord(string|array $recordAssertions, Level $level): bool { - if (is_string($record)) { - $record = array('message' => $record); + if (is_string($recordAssertions)) { + $recordAssertions = ['message' => $recordAssertions]; } - return $this->hasRecordThatPasses(function ($rec) use ($record) { - if ($rec['message'] !== $record['message']) { + return $this->hasRecordThatPasses(function (LogRecord $rec) use ($recordAssertions) { + if ($rec->message !== $recordAssertions['message']) { return false; } - if (isset($record['context']) && $rec['context'] !== $record['context']) { + if (isset($recordAssertions['context']) && $rec->context !== $recordAssertions['context']) { return false; } @@ -151,47 +135,29 @@ public function hasRecord($record, $level): bool }, $level); } - /** - * @param string|int $level Logging level value or name - * - * @phpstan-param Level|LevelName|LogLevel::* $level - */ - public function hasRecordThatContains(string $message, $level): bool + public function hasRecordThatContains(string $message, Level $level): bool { - return $this->hasRecordThatPasses(function ($rec) use ($message) { - return strpos($rec['message'], $message) !== false; - }, $level); + return $this->hasRecordThatPasses(fn (LogRecord $rec) => str_contains($rec->message, $message), $level); } - /** - * @param string|int $level Logging level value or name - * - * @phpstan-param Level|LevelName|LogLevel::* $level - */ - public function hasRecordThatMatches(string $regex, $level): bool + public function hasRecordThatMatches(string $regex, Level $level): bool { - return $this->hasRecordThatPasses(function (array $rec) use ($regex): bool { - return preg_match($regex, $rec['message']) > 0; - }, $level); + return $this->hasRecordThatPasses(fn (LogRecord $rec) => preg_match($regex, $rec->message) > 0, $level); } /** - * @param string|int $level Logging level value or name - * @return bool - * - * @psalm-param callable(Record, int): mixed $predicate - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param callable(LogRecord, int): mixed $predicate */ - public function hasRecordThatPasses(callable $predicate, $level) + public function hasRecordThatPasses(callable $predicate, Level $level): bool { $level = Logger::toMonologLevel($level); - if (!isset($this->recordsByLevel[$level])) { + if (!isset($this->recordsByLevel[$level->value])) { return false; } - foreach ($this->recordsByLevel[$level] as $i => $rec) { - if ($predicate($rec, $i)) { + foreach ($this->recordsByLevel[$level->value] as $i => $rec) { + if ((bool) $predicate($rec, $i)) { return true; } } @@ -200,24 +166,22 @@ public function hasRecordThatPasses(callable $predicate, $level) } /** - * {@inheritDoc} + * @inheritDoc */ - protected function write(array $record): void + protected function write(LogRecord $record): void { - $this->recordsByLevel[$record['level']][] = $record; + $this->recordsByLevel[$record->level->value][] = $record; $this->records[] = $record; } /** - * @param string $method - * @param mixed[] $args - * @return bool + * @param mixed[] $args */ - public function __call($method, $args) + public function __call(string $method, array $args): bool { if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; - $level = constant('Monolog\Logger::' . strtoupper($matches[2])); + $level = constant(Level::class.'::' . $matches[2]); $callback = [$this, $genericMethod]; if (is_callable($callback)) { $args[] = $level; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php index c818352..9c12c3d 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php @@ -15,7 +15,6 @@ trait WebRequestRecognizerTrait { /** * Checks if PHP's serving a web request - * @return bool */ protected function isWebRequest(): bool { diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php index b6d3d3b..2d4e817 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php @@ -11,30 +11,30 @@ namespace Monolog\Handler; +use Monolog\LogRecord; +use Throwable; + /** * Forwards records to multiple handlers suppressing failures of each handler * and continuing through to give every handler a chance to succeed. * * @author Craig D'Amelio - * - * @phpstan-import-type Record from \Monolog\Logger */ class WhatFailureGroupHandler extends GroupHandler { /** - * {@inheritDoc} + * @inheritDoc */ - public function handle(array $record): bool + public function handle(LogRecord $record): bool { - if ($this->processors) { - /** @var Record $record */ + if (\count($this->processors) > 0) { $record = $this->processRecord($record); } foreach ($this->handlers as $handler) { try { $handler->handle($record); - } catch (\Throwable $e) { + } catch (Throwable) { // What failure? } } @@ -43,23 +43,22 @@ public function handle(array $record): bool } /** - * {@inheritDoc} + * @inheritDoc */ public function handleBatch(array $records): void { - if ($this->processors) { - $processed = array(); + if (\count($this->processors) > 0) { + $processed = []; foreach ($records as $record) { $processed[] = $this->processRecord($record); } - /** @var Record[] $records */ $records = $processed; } foreach ($this->handlers as $handler) { try { $handler->handleBatch($records); - } catch (\Throwable $e) { + } catch (Throwable) { // What failure? } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php index ddd46d8..1e71194 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php @@ -13,70 +13,67 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\NormalizerFormatter; -use Monolog\Logger; +use Monolog\Level; +use Monolog\LogRecord; /** * Handler sending logs to Zend Monitor * * @author Christian Bergau * @author Jason Davis - * - * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class ZendMonitorHandler extends AbstractProcessingHandler { - /** - * Monolog level / ZendMonitor Custom Event priority map - * - * @var array - */ - protected $levelMap = []; - /** * @throws MissingExtensionException */ - public function __construct($level = Logger::DEBUG, bool $bubble = true) + public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) { if (!function_exists('zend_monitor_custom_event')) { throw new MissingExtensionException( 'You must have Zend Server installed with Zend Monitor enabled in order to use this handler' ); } - //zend monitor constants are not defined if zend monitor is not enabled. - $this->levelMap = [ - Logger::DEBUG => \ZEND_MONITOR_EVENT_SEVERITY_INFO, - Logger::INFO => \ZEND_MONITOR_EVENT_SEVERITY_INFO, - Logger::NOTICE => \ZEND_MONITOR_EVENT_SEVERITY_INFO, - Logger::WARNING => \ZEND_MONITOR_EVENT_SEVERITY_WARNING, - Logger::ERROR => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - Logger::CRITICAL => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - Logger::ALERT => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - Logger::EMERGENCY => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, - ]; + parent::__construct($level, $bubble); } /** - * {@inheritDoc} + * Translates Monolog log levels to ZendMonitor levels. */ - protected function write(array $record): void + protected function toZendMonitorLevel(Level $level): int + { + return match ($level) { + Level::Debug => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Info => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Notice => \ZEND_MONITOR_EVENT_SEVERITY_INFO, + Level::Warning => \ZEND_MONITOR_EVENT_SEVERITY_WARNING, + Level::Error => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Critical => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Alert => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + Level::Emergency => \ZEND_MONITOR_EVENT_SEVERITY_ERROR, + }; + } + + /** + * @inheritDoc + */ + protected function write(LogRecord $record): void { $this->writeZendMonitorCustomEvent( - Logger::getLevelName($record['level']), - $record['message'], - $record['formatted'], - $this->levelMap[$record['level']] + $record->level->getName(), + $record->message, + $record->formatted, + $this->toZendMonitorLevel($record->level) ); } /** * Write to Zend Monitor Events - * @param string $type Text displayed in "Class Name (custom)" field - * @param string $message Text displayed in "Error String" - * @param array $formatted Displayed in Custom Variables tab - * @param int $severity Set the event severity level (-1,0,1) - * - * @phpstan-param FormattedRecord $formatted + * @param string $type Text displayed in "Class Name (custom)" field + * @param string $message Text displayed in "Error String" + * @param array $formatted Displayed in Custom Variables tab + * @param int $severity Set the event severity level (-1,0,1) */ protected function writeZendMonitorCustomEvent(string $type, string $message, array $formatted, int $severity): void { @@ -84,18 +81,10 @@ protected function writeZendMonitorCustomEvent(string $type, string $message, ar } /** - * {@inheritDoc} + * @inheritDoc */ public function getDefaultFormatter(): FormatterInterface { return new NormalizerFormatter(); } - - /** - * @return array - */ - public function getLevelMap(): array - { - return $this->levelMap; - } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/LogRecord.php b/upload/api/vendor/monolog/monolog/src/Monolog/LogRecord.php index 702807d..df758c5 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/LogRecord.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/LogRecord.php @@ -14,21 +14,111 @@ use ArrayAccess; /** - * Monolog log record interface for forward compatibility with Monolog 3.0 - * - * This is just present in Monolog 2.4+ to allow interoperable code to be written against - * both versions by type-hinting arguments as `array|\Monolog\LogRecord $record` - * - * Do not rely on this interface for other purposes, and do not implement it. + * Monolog log record * * @author Jordi Boggiano - * @template-extends \ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra'|'formatted', mixed> - * @phpstan-import-type Record from Logger + * @template-implements ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra', int|string|\DateTimeImmutable|array> */ -interface LogRecord extends \ArrayAccess +class LogRecord implements ArrayAccess { + private const MODIFIABLE_FIELDS = [ + 'extra' => true, + 'formatted' => true, + ]; + + public function __construct( + public readonly \DateTimeImmutable $datetime, + public readonly string $channel, + public readonly Level $level, + public readonly string $message, + /** @var array */ + public readonly array $context = [], + /** @var array */ + public array $extra = [], + public mixed $formatted = null, + ) { + } + + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === 'extra') { + if (!is_array($value)) { + throw new \InvalidArgumentException('extra must be an array'); + } + + $this->extra = $value; + + return; + } + + if ($offset === 'formatted') { + $this->formatted = $value; + + return; + } + + throw new \LogicException('Unsupported operation: setting '.$offset); + } + + public function offsetExists(mixed $offset): bool + { + if ($offset === 'level_name') { + return true; + } + + return isset($this->{$offset}); + } + + public function offsetUnset(mixed $offset): void + { + throw new \LogicException('Unsupported operation'); + } + + public function &offsetGet(mixed $offset): mixed + { + if ($offset === 'level_name' || $offset === 'level') { + // avoid returning readonly props by ref as this is illegal + if ($offset === 'level_name') { + $copy = $this->level->getName(); + } else { + $copy = $this->level->value; + } + + return $copy; + } + + if (isset(self::MODIFIABLE_FIELDS[$offset])) { + return $this->{$offset}; + } + + // avoid returning readonly props by ref as this is illegal + $copy = $this->{$offset}; + + return $copy; + } + /** - * @phpstan-return Record + * @phpstan-return array{message: string, context: mixed[], level: value-of, level_name: value-of, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} */ - public function toArray(): array; + public function toArray(): array + { + return [ + 'message' => $this->message, + 'context' => $this->context, + 'level' => $this->level->value, + 'level_name' => $this->level->getName(), + 'channel' => $this->channel, + 'datetime' => $this->datetime, + 'extra' => $this->extra, + ]; + } + + public function with(mixed ...$args): self + { + foreach (['message', 'context', 'level', 'channel', 'datetime', 'extra'] as $prop) { + $args[$prop] ??= $this->{$prop}; + } + + return new self(...$args); + } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Logger.php b/upload/api/vendor/monolog/monolog/src/Monolog/Logger.php index 84a2f55..db8bc21 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Logger.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Logger.php @@ -11,13 +11,17 @@ namespace Monolog; +use Closure; use DateTimeZone; +use Fiber; use Monolog\Handler\HandlerInterface; +use Monolog\Processor\ProcessorInterface; use Psr\Log\LoggerInterface; use Psr\Log\InvalidArgumentException; use Psr\Log\LogLevel; use Throwable; use Stringable; +use WeakMap; /** * Monolog log channel @@ -26,15 +30,14 @@ * and uses them to store records that are added to it. * * @author Jordi Boggiano - * - * @phpstan-type Level Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY - * @phpstan-type LevelName 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY' - * @phpstan-type Record array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} + * @final */ class Logger implements LoggerInterface, ResettableInterface { /** * Detailed debug information + * + * @deprecated Use \Monolog\Level::Debug */ public const DEBUG = 100; @@ -42,11 +45,15 @@ class Logger implements LoggerInterface, ResettableInterface * Interesting events * * Examples: User logs in, SQL logs. + * + * @deprecated Use \Monolog\Level::Info */ public const INFO = 200; /** * Uncommon events + * + * @deprecated Use \Monolog\Level::Notice */ public const NOTICE = 250; @@ -55,11 +62,15 @@ class Logger implements LoggerInterface, ResettableInterface * * Examples: Use of deprecated APIs, poor use of an API, * undesirable things that are not necessarily wrong. + * + * @deprecated Use \Monolog\Level::Warning */ public const WARNING = 300; /** * Runtime errors + * + * @deprecated Use \Monolog\Level::Error */ public const ERROR = 400; @@ -67,6 +78,8 @@ class Logger implements LoggerInterface, ResettableInterface * Critical conditions * * Example: Application component unavailable, unexpected exception. + * + * @deprecated Use \Monolog\Level::Critical */ public const CRITICAL = 500; @@ -75,11 +88,15 @@ class Logger implements LoggerInterface, ResettableInterface * * Example: Entire website down, database unavailable, etc. * This should trigger the SMS alerts and wake you up. + * + * @deprecated Use \Monolog\Level::Alert */ public const ALERT = 550; /** * Urgent alert. + * + * @deprecated Use \Monolog\Level::Emergency */ public const EMERGENCY = 600; @@ -88,28 +105,8 @@ class Logger implements LoggerInterface, ResettableInterface * * This is only bumped when API breaks are done and should * follow the major version of the library - * - * @var int - */ - public const API = 2; - - /** - * This is a static variable and not a constant to serve as an extension point for custom levels - * - * @var array $levels Logging levels with the levels as key - * - * @phpstan-var array $levels Logging levels with the levels as key */ - protected static $levels = [ - self::DEBUG => 'DEBUG', - self::INFO => 'INFO', - self::NOTICE => 'NOTICE', - self::WARNING => 'WARNING', - self::ERROR => 'ERROR', - self::CRITICAL => 'CRITICAL', - self::ALERT => 'ALERT', - self::EMERGENCY => 'EMERGENCY', - ]; + public const API = 3; /** * Mapping between levels numbers defined in RFC 5424 and Monolog ones @@ -117,90 +114,71 @@ class Logger implements LoggerInterface, ResettableInterface * @phpstan-var array $rfc_5424_levels */ private const RFC_5424_LEVELS = [ - 7 => self::DEBUG, - 6 => self::INFO, - 5 => self::NOTICE, - 4 => self::WARNING, - 3 => self::ERROR, - 2 => self::CRITICAL, - 1 => self::ALERT, - 0 => self::EMERGENCY, + 7 => Level::Debug, + 6 => Level::Info, + 5 => Level::Notice, + 4 => Level::Warning, + 3 => Level::Error, + 2 => Level::Critical, + 1 => Level::Alert, + 0 => Level::Emergency, ]; - /** - * @var string - */ - protected $name; + protected string $name; /** * The handler stack * - * @var HandlerInterface[] + * @var list */ - protected $handlers; + protected array $handlers; /** * Processors that will process all log records * * To process records of a single handler instead, add the processor on that specific handler * - * @var callable[] + * @var array<(callable(LogRecord): LogRecord)|ProcessorInterface> */ - protected $processors; + protected array $processors; - /** - * @var bool - */ - protected $microsecondTimestamps = true; + protected bool $microsecondTimestamps = true; - /** - * @var DateTimeZone - */ - protected $timezone; + protected DateTimeZone $timezone; - /** - * @var callable|null - */ - protected $exceptionHandler; + protected Closure|null $exceptionHandler = null; /** - * @var int Keeps track of depth to prevent infinite logging loops + * Keeps track of depth to prevent infinite logging loops */ - private $logDepth = 0; + private int $logDepth = 0; /** - * @var \WeakMap<\Fiber, int>|null Keeps track of depth inside fibers to prevent infinite logging loops + * @var WeakMap, int> Keeps track of depth inside fibers to prevent infinite logging loops */ - private $fiberLogDepth; + private WeakMap $fiberLogDepth; /** - * @var bool Whether to detect infinite logging loops - * + * Whether to detect infinite logging loops * This can be disabled via {@see useLoggingLoopDetection} if you have async handlers that do not play well with this */ - private $detectCycles = true; + private bool $detectCycles = true; /** - * @psalm-param array $processors - * * @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 callable[] $processors Optional array of processors * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used + * + * @phpstan-param array<(callable(LogRecord): LogRecord)|ProcessorInterface> $processors */ - public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null) + public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone|null $timezone = null) { $this->name = $name; $this->setHandlers($handlers); $this->processors = $processors; - $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC'); - - if (\PHP_VERSION_ID >= 80100) { - // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412 - /** @var \WeakMap<\Fiber, int> $fiberLogDepth */ - $fiberLogDepth = new \WeakMap(); - $this->fiberLogDepth = $fiberLogDepth; - } + $this->timezone = $timezone ?? new DateTimeZone(date_default_timezone_get()); + $this->fiberLogDepth = new \WeakMap(); } public function getName(): string @@ -236,7 +214,7 @@ public function pushHandler(HandlerInterface $handler): self */ public function popHandler(): HandlerInterface { - if (!$this->handlers) { + if (0 === \count($this->handlers)) { throw new \LogicException('You tried to pop from an empty handler stack.'); } @@ -248,7 +226,7 @@ public function popHandler(): HandlerInterface * * If a map is passed, keys will be ignored. * - * @param HandlerInterface[] $handlers + * @param list $handlers */ public function setHandlers(array $handlers): self { @@ -261,7 +239,7 @@ public function setHandlers(array $handlers): self } /** - * @return HandlerInterface[] + * @return list */ public function getHandlers(): array { @@ -270,8 +248,10 @@ public function getHandlers(): array /** * Adds a processor on to the stack. + * + * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback */ - public function pushProcessor(callable $callback): self + public function pushProcessor(ProcessorInterface|callable $callback): self { array_unshift($this->processors, $callback); @@ -281,12 +261,12 @@ public function pushProcessor(callable $callback): self /** * Removes the processor on top of the stack and returns it. * + * @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord) * @throws \LogicException If empty processor stack - * @return callable */ public function popProcessor(): callable { - if (!$this->processors) { + if (0 === \count($this->processors)) { throw new \LogicException('You tried to pop from an empty processor stack.'); } @@ -295,6 +275,7 @@ public function popProcessor(): callable /** * @return callable[] + * @phpstan-return array */ public function getProcessors(): array { @@ -335,18 +316,17 @@ public function useLoggingLoopDetection(bool $detectCycles): self * @param DateTimeImmutable $datetime Optional log date to log into the past or future * @return bool Whether the record has been processed * - * @phpstan-param Level $level + * @phpstan-param value-of|Level $level */ - public function addRecord(int $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool + public function addRecord(int|Level $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool { - if (isset(self::RFC_5424_LEVELS[$level])) { + if (is_int($level) && isset(self::RFC_5424_LEVELS[$level])) { $level = self::RFC_5424_LEVELS[$level]; } if ($this->detectCycles) { - if (\PHP_VERSION_ID >= 80100 && $fiber = \Fiber::getCurrent()) { - $this->fiberLogDepth[$fiber] = $this->fiberLogDepth[$fiber] ?? 0; - $logDepth = ++$this->fiberLogDepth[$fiber]; + if (null !== ($fiber = Fiber::getCurrent())) { + $logDepth = $this->fiberLogDepth[$fiber] = ($this->fiberLogDepth[$fiber] ?? 0) + 1; } else { $logDepth = ++$this->logDepth; } @@ -362,31 +342,30 @@ public function addRecord(int $level, string $message, array $context = [], Date } try { - $record = null; + $recordInitialized = count($this->processors) === 0; + + $record = new LogRecord( + message: $message, + context: $context, + level: self::toMonologLevel($level), + channel: $this->name, + datetime: $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), + extra: [], + ); + $handled = false; foreach ($this->handlers as $handler) { - if (null === $record) { - // skip creating the record as long as no handler is going to handle it - if (!$handler->isHandling(['level' => $level])) { + if (false === $recordInitialized) { + // skip initializing the record as long as no handler is going to handle it + if (!$handler->isHandling($record)) { continue; } - $levelName = static::getLevelName($level); - - $record = [ - 'message' => $message, - 'context' => $context, - 'level' => $level, - 'level_name' => $levelName, - 'channel' => $this->name, - 'datetime' => $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), - 'extra' => [], - ]; - try { foreach ($this->processors as $processor) { $record = $processor($record); } + $recordInitialized = true; } catch (Throwable $e) { $this->handleException($e, $record); @@ -394,8 +373,9 @@ public function addRecord(int $level, string $message, array $context = [], Date } } - // once the record exists, send it to all handlers as long as the bubbling chain is not interrupted + // once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted try { + $handled = true; if (true === $handler->handle($record)) { break; } @@ -405,6 +385,8 @@ public function addRecord(int $level, string $message, array $context = [], Date return true; } } + + return $handled; } finally { if ($this->detectCycles) { if (isset($fiber)) { @@ -414,8 +396,6 @@ public function addRecord(int $level, string $message, array $context = [], Date } } } - - return null !== $record; } /** @@ -461,77 +441,77 @@ public function reset(): void } /** - * Gets all supported logging levels. + * Gets the name of the logging level as a string. * - * @return array Assoc array with human-readable level names => level codes. - * @phpstan-return array - */ - public static function getLevels(): array - { - return array_flip(static::$levels); - } - - /** - * Gets the name of the logging level. + * This still returns a string instead of a Level for BC, but new code should not rely on this method. * * @throws \Psr\Log\InvalidArgumentException If level is not defined * - * @phpstan-param Level $level - * @phpstan-return LevelName + * @phpstan-param value-of|Level $level + * @phpstan-return value-of + * + * @deprecated Since 3.0, use {@see toMonologLevel} or {@see \Monolog\Level->getName()} instead */ - public static function getLevelName(int $level): string + public static function getLevelName(int|Level $level): string { - if (!isset(static::$levels[$level])) { - throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels))); - } - - return static::$levels[$level]; + return self::toMonologLevel($level)->getName(); } /** * Converts PSR-3 levels to Monolog ones if necessary * - * @param string|int $level Level number (monolog) or name (PSR-3) - * @throws \Psr\Log\InvalidArgumentException If level is not defined + * @param int|string|Level|LogLevel::* $level Level number (monolog) or name (PSR-3) + * @throws \Psr\Log\InvalidArgumentException If level is not defined * - * @phpstan-param Level|LevelName|LogLevel::* $level - * @phpstan-return Level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public static function toMonologLevel($level): int + public static function toMonologLevel(string|int|Level $level): Level { - if (is_string($level)) { - if (is_numeric($level)) { - /** @phpstan-ignore-next-line */ - return intval($level); + if ($level instanceof Level) { + return $level; + } + + if (\is_string($level)) { + if (\is_numeric($level)) { + $levelEnum = Level::tryFrom((int) $level); + if ($levelEnum === null) { + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); + } + + return $levelEnum; } - // Contains chars of all log levels and avoids using strtoupper() which may have + // Contains first char of all log levels and avoids using strtoupper() which may have // strange results depending on locale (for example, "i" will become "İ" in Turkish locale) - $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY'); - if (defined(__CLASS__.'::'.$upper)) { - return constant(__CLASS__ . '::' . $upper); + $upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1)); + if (defined(Level::class.'::'.$upper)) { + return constant(Level::class . '::' . $upper); } - throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); } - if (!is_int($level)) { - throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels)); + $levelEnum = Level::tryFrom($level); + if ($levelEnum === null) { + throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); } - return $level; + return $levelEnum; } /** * Checks whether the Logger has a handler that listens on the given level * - * @phpstan-param Level $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function isHandling(int $level): bool + public function isHandling(int|string|Level $level): bool { - $record = [ - 'level' => $level, - ]; + $record = new LogRecord( + datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), + channel: $this->name, + message: '', + level: self::toMonologLevel($level), + ); foreach ($this->handlers as $handler) { if ($handler->isHandling($record)) { @@ -545,16 +525,16 @@ public function isHandling(int $level): bool /** * Set a custom exception handler that will be called if adding a new record fails * - * The callable will receive an exception object and the record that failed to be logged + * The Closure will receive an exception object and the record that failed to be logged */ - public function setExceptionHandler(?callable $callback): self + public function setExceptionHandler(Closure|null $callback): self { $this->exceptionHandler = $callback; return $this; } - public function getExceptionHandler(): ?callable + public function getExceptionHandler(): Closure|null { return $this->exceptionHandler; } @@ -568,19 +548,21 @@ public function getExceptionHandler(): ?callable * @param string|Stringable $message The log message * @param mixed[] $context The log context * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param Level|LogLevel::* $level */ - public function log($level, $message, array $context = []): void + public function log($level, string|\Stringable $message, array $context = []): void { - if (!is_int($level) && !is_string($level)) { - throw new \InvalidArgumentException('$level is expected to be a string or int'); - } + if (!$level instanceof Level) { + if (!is_string($level) && !is_int($level)) { + throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance'); + } - if (isset(self::RFC_5424_LEVELS[$level])) { - $level = self::RFC_5424_LEVELS[$level]; - } + if (isset(self::RFC_5424_LEVELS[$level])) { + $level = self::RFC_5424_LEVELS[$level]; + } - $level = static::toMonologLevel($level); + $level = static::toMonologLevel($level); + } $this->addRecord($level, (string) $message, $context); } @@ -593,9 +575,9 @@ public function log($level, $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function debug($message, array $context = []): void + public function debug(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::DEBUG, (string) $message, $context); + $this->addRecord(Level::Debug, (string) $message, $context); } /** @@ -606,9 +588,9 @@ public function debug($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function info($message, array $context = []): void + public function info(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::INFO, (string) $message, $context); + $this->addRecord(Level::Info, (string) $message, $context); } /** @@ -619,9 +601,9 @@ public function info($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function notice($message, array $context = []): void + public function notice(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::NOTICE, (string) $message, $context); + $this->addRecord(Level::Notice, (string) $message, $context); } /** @@ -632,9 +614,9 @@ public function notice($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function warning($message, array $context = []): void + public function warning(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::WARNING, (string) $message, $context); + $this->addRecord(Level::Warning, (string) $message, $context); } /** @@ -645,9 +627,9 @@ public function warning($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function error($message, array $context = []): void + public function error(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::ERROR, (string) $message, $context); + $this->addRecord(Level::Error, (string) $message, $context); } /** @@ -658,9 +640,9 @@ public function error($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function critical($message, array $context = []): void + public function critical(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::CRITICAL, (string) $message, $context); + $this->addRecord(Level::Critical, (string) $message, $context); } /** @@ -671,9 +653,9 @@ public function critical($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function alert($message, array $context = []): void + public function alert(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::ALERT, (string) $message, $context); + $this->addRecord(Level::Alert, (string) $message, $context); } /** @@ -684,9 +666,9 @@ public function alert($message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function emergency($message, array $context = []): void + public function emergency(string|\Stringable $message, array $context = []): void { - $this->addRecord(static::EMERGENCY, (string) $message, $context); + $this->addRecord(Level::Emergency, (string) $message, $context); } /** @@ -710,13 +692,10 @@ public function getTimezone(): DateTimeZone /** * Delegates exception management to the custom exception handler, * or throws the exception if no custom handler is set. - * - * @param array $record - * @phpstan-param Record $record */ - protected function handleException(Throwable $e, array $record): void + protected function handleException(Throwable $e, LogRecord $record): void { - if (!$this->exceptionHandler) { + if (null === $this->exceptionHandler) { throw $e; } @@ -751,11 +730,6 @@ public function __unserialize(array $data): void } } - if (\PHP_VERSION_ID >= 80100) { - // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412 - /** @var \WeakMap<\Fiber, int> $fiberLogDepth */ - $fiberLogDepth = new \WeakMap(); - $this->fiberLogDepth = $fiberLogDepth; - } + $this->fiberLogDepth = new \WeakMap(); } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php index 8166bdc..5a70ac2 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php @@ -11,46 +11,44 @@ namespace Monolog\Processor; +use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Injects Git branch and Git commit SHA in all records * * @author Nick Otter * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class GitProcessor implements ProcessorInterface { - /** @var int */ - private $level; + private Level $level; /** @var array{branch: string, commit: string}|array|null */ private static $cache = null; /** - * @param string|int $level The minimum logging level at which this Processor will be triggered + * @param int|string|Level|LogLevel::* $level The minimum logging level at which this Processor will be triggered * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG) + public function __construct(int|string|Level $level = Level::Debug) { $this->level = Logger::toMonologLevel($level); } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { // return if the level is not high enough - if ($record['level'] < $this->level) { + if ($record->level->isLowerThan($this->level)) { return $record; } - $record['extra']['git'] = self::getGitInfo(); + $record->extra['git'] = self::getGitInfo(); return $record; } @@ -60,12 +58,12 @@ public function __invoke(array $record): array */ private static function getGitInfo(): array { - if (self::$cache) { + if (self::$cache !== null) { return self::$cache; } - $branches = `git branch -v --no-abbrev`; - if ($branches && preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { + $branches = shell_exec('git branch -v --no-abbrev'); + if (is_string($branches) && 1 === preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { return self::$cache = [ 'branch' => $matches[1], 'commit' => $matches[2], diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php index 91fda7d..cba6e09 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php @@ -11,13 +11,14 @@ namespace Monolog\Processor; +use Monolog\LogRecord; + /** * Injects value of gethostname in all records */ class HostnameProcessor implements ProcessorInterface { - /** @var string */ - private static $host; + private static string $host; public function __construct() { @@ -25,11 +26,11 @@ public function __construct() } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { - $record['extra']['hostname'] = self::$host; + $record->extra['hostname'] = self::$host; return $record; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php index a32e76b..3a6fbfb 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php @@ -11,8 +11,10 @@ namespace Monolog\Processor; +use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Injects line/file:class/function where the log message came from @@ -24,31 +26,28 @@ * triggered the FingersCrossedHandler. * * @author Jordi Boggiano - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class IntrospectionProcessor implements ProcessorInterface { - /** @var int */ - private $level; - /** @var string[] */ - private $skipClassesPartials; - /** @var int */ - private $skipStackFramesCount; + private Level $level; + /** @var string[] */ - private $skipFunctions = [ + private array $skipClassesPartials; + + private int $skipStackFramesCount; + + private const SKIP_FUNCTIONS = [ 'call_user_func', 'call_user_func_array', ]; /** - * @param string|int $level The minimum logging level at which this Processor will be triggered - * @param string[] $skipClassesPartials + * @param string|int|Level $level The minimum logging level at which this Processor will be triggered + * @param string[] $skipClassesPartials * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], int $skipStackFramesCount = 0) + public function __construct(int|string|Level $level = Level::Debug, array $skipClassesPartials = [], int $skipStackFramesCount = 0) { $this->level = Logger::toMonologLevel($level); $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials); @@ -56,12 +55,12 @@ public function __construct($level = Logger::DEBUG, array $skipClassesPartials = } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { // return if the level is not high enough - if ($record['level'] < $this->level) { + if ($record->level->isLowerThan($this->level)) { return $record; } @@ -83,7 +82,7 @@ public function __invoke(array $record): array continue 2; } } - } elseif (in_array($trace[$i]['function'], $this->skipFunctions)) { + } elseif (in_array($trace[$i]['function'], self::SKIP_FUNCTIONS, true)) { $i++; continue; @@ -95,14 +94,14 @@ public function __invoke(array $record): array $i += $this->skipStackFramesCount; // we should have the call source now - $record['extra'] = array_merge( - $record['extra'], + $record->extra = array_merge( + $record->extra, [ - 'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null, - 'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null, - 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null, - 'callType' => isset($trace[$i]['type']) ? $trace[$i]['type'] : null, - 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null, + 'file' => $trace[$i - 1]['file'] ?? null, + 'line' => $trace[$i - 1]['line'] ?? null, + 'class' => $trace[$i]['class'] ?? null, + 'callType' => $trace[$i]['type'] ?? null, + 'function' => $trace[$i]['function'] ?? null, ] ); @@ -110,7 +109,7 @@ public function __invoke(array $record): array } /** - * @param array[] $trace + * @param array $trace */ private function isTraceClassOrSkippedFunction(array $trace, int $index): bool { @@ -118,6 +117,6 @@ private function isTraceClassOrSkippedFunction(array $trace, int $index): bool return false; } - return isset($trace[$index]['class']) || in_array($trace[$index]['function'], $this->skipFunctions); + return isset($trace[$index]['class']) || in_array($trace[$index]['function'], self::SKIP_FUNCTIONS, true); } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php index 37c756f..adc32c6 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\LogRecord; + /** * Injects memory_get_peak_usage in all records * @@ -20,9 +22,9 @@ class MemoryPeakUsageProcessor extends MemoryProcessor { /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { $usage = memory_get_peak_usage($this->realUsage); @@ -30,7 +32,7 @@ public function __invoke(array $record): array $usage = $this->formatBytes($usage); } - $record['extra']['memory_peak_usage'] = $usage; + $record->extra['memory_peak_usage'] = $usage; return $record; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php index 227deb7..f808e51 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php @@ -21,12 +21,12 @@ abstract class MemoryProcessor implements ProcessorInterface /** * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported. */ - protected $realUsage; + protected bool $realUsage; /** * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size) */ - protected $useFormatting; + protected bool $useFormatting; /** * @param bool $realUsage Set this to true to get the real size of memory allocated from system. @@ -41,7 +41,6 @@ public function __construct(bool $realUsage = true, bool $useFormatting = true) /** * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is * - * @param int $bytes * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int */ protected function formatBytes(int $bytes) diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php index e141921..a814b1d 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\LogRecord; + /** * Injects memory_get_usage in all records * @@ -20,9 +22,9 @@ class MemoryUsageProcessor extends MemoryProcessor { /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { $usage = memory_get_usage($this->realUsage); @@ -30,7 +32,7 @@ public function __invoke(array $record): array $usage = $this->formatBytes($usage); } - $record['extra']['memory_usage'] = $usage; + $record->extra['memory_usage'] = $usage; return $record; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php index d4a628f..47b1e64 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php @@ -11,45 +11,43 @@ namespace Monolog\Processor; +use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; +use Monolog\LogRecord; /** * Injects Hg branch and Hg revision number in all records * * @author Jonathan A. Schweder - * - * @phpstan-import-type LevelName from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger */ class MercurialProcessor implements ProcessorInterface { - /** @var Level */ - private $level; + private Level $level; /** @var array{branch: string, revision: string}|array|null */ private static $cache = null; /** - * @param int|string $level The minimum logging level at which this Processor will be triggered + * @param int|string|Level $level The minimum logging level at which this Processor will be triggered * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function __construct($level = Logger::DEBUG) + public function __construct(int|string|Level $level = Level::Debug) { $this->level = Logger::toMonologLevel($level); } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { // return if the level is not high enough - if ($record['level'] < $this->level) { + if ($record->level->isLowerThan($this->level)) { return $record; } - $record['extra']['hg'] = self::getMercurialInfo(); + $record->extra['hg'] = self::getMercurialInfo(); return $record; } @@ -59,11 +57,11 @@ public function __invoke(array $record): array */ private static function getMercurialInfo(): array { - if (self::$cache) { + if (self::$cache !== null) { return self::$cache; } - $result = explode(' ', trim(`hg id -nb`)); + $result = explode(' ', trim((string) shell_exec('hg id -nb'))); if (count($result) >= 3) { return self::$cache = [ diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php index 3b939a9..bb9a522 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\LogRecord; + /** * Adds value of getmypid into records * @@ -19,11 +21,11 @@ class ProcessIdProcessor implements ProcessorInterface { /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { - $record['extra']['process_id'] = getmypid(); + $record->extra['process_id'] = getmypid(); return $record; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php index 5defb7e..ebe41fc 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php @@ -11,20 +11,17 @@ namespace Monolog\Processor; +use Monolog\LogRecord; + /** * An optional interface to allow labelling Monolog processors. * * @author Nicolas Grekas - * - * @phpstan-import-type Record from \Monolog\Logger */ interface ProcessorInterface { /** - * @return array The processed record - * - * @phpstan-param Record $record - * @phpstan-return Record + * @return LogRecord The processed record */ - public function __invoke(array $record); + public function __invoke(LogRecord $record); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php index e7c1217..aad2aad 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php @@ -12,6 +12,7 @@ namespace Monolog\Processor; use Monolog\Utils; +use Monolog\LogRecord; /** * Processes a record's message according to PSR-3 rules @@ -24,11 +25,9 @@ class PsrLogMessageProcessor implements ProcessorInterface { public const SIMPLE_DATE = "Y-m-d\TH:i:s.uP"; - /** @var string|null */ - private $dateFormat; + private ?string $dateFormat; - /** @var bool */ - private $removeUsedContextFields; + private bool $removeUsedContextFields; /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format @@ -41,30 +40,32 @@ public function __construct(?string $dateFormat = null, bool $removeUsedContextF } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { - if (false === strpos($record['message'], '{')) { + if (false === strpos($record->message, '{')) { return $record; } $replacements = []; - foreach ($record['context'] as $key => $val) { + $context = $record->context; + + foreach ($context as $key => $val) { $placeholder = '{' . $key . '}'; - if (strpos($record['message'], $placeholder) === false) { + if (strpos($record->message, $placeholder) === false) { continue; } - if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { + if (null === $val || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { $replacements[$placeholder] = $val; } elseif ($val instanceof \DateTimeInterface) { - if (!$this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) { + if (null === $this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) { // handle monolog dates using __toString if no specific dateFormat was asked for // so that it follows the useMicroseconds flag $replacements[$placeholder] = (string) $val; } else { - $replacements[$placeholder] = $val->format($this->dateFormat ?: static::SIMPLE_DATE); + $replacements[$placeholder] = $val->format($this->dateFormat ?? static::SIMPLE_DATE); } } elseif ($val instanceof \UnitEnum) { $replacements[$placeholder] = $val instanceof \BackedEnum ? $val->value : $val->name; @@ -77,12 +78,10 @@ public function __invoke(array $record): array } if ($this->removeUsedContextFields) { - unset($record['context'][$key]); + unset($context[$key]); } } - $record['message'] = strtr($record['message'], $replacements); - - return $record; + return $record->with(message: strtr($record->message, $replacements), context: $context); } } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php index 80f1874..4543ccf 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php @@ -11,6 +11,8 @@ namespace Monolog\Processor; +use Monolog\LogRecord; + /** * Adds a tags array into record * @@ -19,7 +21,7 @@ class TagProcessor implements ProcessorInterface { /** @var string[] */ - private $tags; + private array $tags; /** * @param string[] $tags @@ -50,11 +52,11 @@ public function setTags(array $tags = []): self } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { - $record['extra']['tags'] = $this->tags; + $record->extra['tags'] = $this->tags; return $record; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php index a27b74d..3a0c128 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php @@ -12,6 +12,7 @@ namespace Monolog\Processor; use Monolog\ResettableInterface; +use Monolog\LogRecord; /** * Adds a unique identifier into records @@ -20,9 +21,12 @@ */ class UidProcessor implements ProcessorInterface, ResettableInterface { - /** @var string */ - private $uid; + /** @var non-empty-string */ + private string $uid; + /** + * @param int<1, 32> $length + */ public function __construct(int $length = 7) { if ($length > 32 || $length < 1) { @@ -33,11 +37,11 @@ public function __construct(int $length = 7) } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { - $record['extra']['uid'] = $this->uid; + $record->extra['uid'] = $this->uid; return $record; } @@ -47,11 +51,15 @@ public function getUid(): string return $this->uid; } - public function reset() + public function reset(): void { $this->uid = $this->generateUid(strlen($this->uid)); } + /** + * @param positive-int $length + * @return non-empty-string + */ private function generateUid(int $length): string { return substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length); diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php index 51850e1..2088b18 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php @@ -11,6 +11,9 @@ namespace Monolog\Processor; +use ArrayAccess; +use Monolog\LogRecord; + /** * Injects url/method and remote IP of the current web request in all records * @@ -19,9 +22,9 @@ class WebProcessor implements ProcessorInterface { /** - * @var array|\ArrayAccess + * @var array|ArrayAccess */ - protected $serverData; + protected array|ArrayAccess $serverData; /** * Default fields @@ -30,7 +33,7 @@ class WebProcessor implements ProcessorInterface * * @var array */ - protected $extraFields = [ + protected array $extraFields = [ 'url' => 'REQUEST_URI', 'ip' => 'REMOTE_ADDR', 'http_method' => 'REQUEST_METHOD', @@ -40,17 +43,15 @@ class WebProcessor implements ProcessorInterface ]; /** - * @param array|\ArrayAccess|null $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data - * @param array|array|null $extraFields Field names and the related key inside $serverData to be added (or just a list of field names to use the default configured $serverData mapping). If not provided it defaults to: [url, ip, http_method, server, referrer] + unique_id if present in server data + * @param array|ArrayAccess|null $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data + * @param array|array|null $extraFields Field names and the related key inside $serverData to be added (or just a list of field names to use the default configured $serverData mapping). If not provided it defaults to: [url, ip, http_method, server, referrer] + unique_id if present in server data */ - public function __construct($serverData = null, array $extraFields = null) + public function __construct(array|ArrayAccess|null $serverData = null, array|null $extraFields = null) { if (null === $serverData) { $this->serverData = &$_SERVER; - } elseif (is_array($serverData) || $serverData instanceof \ArrayAccess) { - $this->serverData = $serverData; } else { - throw new \UnexpectedValueException('$serverData must be an array or object implementing ArrayAccess.'); + $this->serverData = $serverData; } $defaultEnabled = ['url', 'ip', 'http_method', 'server', 'referrer']; @@ -64,7 +65,7 @@ public function __construct($serverData = null, array $extraFields = null) } if (isset($extraFields[0])) { foreach (array_keys($this->extraFields) as $fieldName) { - if (!in_array($fieldName, $extraFields)) { + if (!in_array($fieldName, $extraFields, true)) { unset($this->extraFields[$fieldName]); } } @@ -74,9 +75,9 @@ public function __construct($serverData = null, array $extraFields = null) } /** - * {@inheritDoc} + * @inheritDoc */ - public function __invoke(array $record): array + public function __invoke(LogRecord $record): LogRecord { // skip processing if for some reason request data // is not present (CLI or wonky SAPIs) @@ -84,7 +85,7 @@ public function __invoke(array $record): array return $record; } - $record['extra'] = $this->appendExtraFields($record['extra']); + $record->extra = $this->appendExtraFields($record->extra); return $record; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Registry.php b/upload/api/vendor/monolog/monolog/src/Monolog/Registry.php index ae94ae6..2ef2edc 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Registry.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Registry.php @@ -42,7 +42,7 @@ class Registry * * @var Logger[] */ - private static $loggers = []; + private static array $loggers = []; /** * Adds new logging channel to the registry @@ -51,11 +51,10 @@ class Registry * @param string|null $name Name of the logging channel ($logger->getName() by default) * @param bool $overwrite Overwrite instance in the registry if the given name already exists? * @throws \InvalidArgumentException If $overwrite set to false and named Logger instance already exists - * @return void */ - public static function addLogger(Logger $logger, ?string $name = null, bool $overwrite = false) + public static function addLogger(Logger $logger, ?string $name = null, bool $overwrite = false): void { - $name = $name ?: $logger->getName(); + $name = $name ?? $logger->getName(); if (isset(self::$loggers[$name]) && !$overwrite) { throw new InvalidArgumentException('Logger with the given name already exists'); @@ -110,7 +109,7 @@ public static function clear(): void * @param string $name Name of the requested Logger instance * @throws \InvalidArgumentException If named Logger instance is not in the registry */ - public static function getInstance($name): Logger + public static function getInstance(string $name): Logger { if (!isset(self::$loggers[$name])) { throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name)); @@ -127,7 +126,7 @@ public static function getInstance($name): Logger * @throws \InvalidArgumentException If named Logger instance is not in the registry * @return Logger Requested instance of Logger */ - public static function __callStatic($name, $arguments) + public static function __callStatic(string $name, array $arguments): Logger { return self::getInstance($name); } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/ResettableInterface.php b/upload/api/vendor/monolog/monolog/src/Monolog/ResettableInterface.php index 2c5fd78..4983a6b 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/ResettableInterface.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/ResettableInterface.php @@ -27,8 +27,5 @@ */ interface ResettableInterface { - /** - * @return void - */ - public function reset(); + public function reset(): void; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/SignalHandler.php b/upload/api/vendor/monolog/monolog/src/Monolog/SignalHandler.php index d730eea..b930ca4 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/SignalHandler.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/SignalHandler.php @@ -19,21 +19,17 @@ * Monolog POSIX signal handler * * @author Robert Gust-Bardon - * - * @phpstan-import-type Level from \Monolog\Logger - * @phpstan-import-type LevelName from \Monolog\Logger */ class SignalHandler { - /** @var LoggerInterface */ - private $logger; + private LoggerInterface $logger; /** @var array SIG_DFL, SIG_IGN or previous callable */ - private $previousSignalHandler = []; - /** @var array */ - private $signalLevelMap = []; + private array $previousSignalHandler = []; + /** @var array */ + private array $signalLevelMap = []; /** @var array */ - private $signalRestartSyscalls = []; + private array $signalRestartSyscalls = []; public function __construct(LoggerInterface $logger) { @@ -41,21 +37,18 @@ public function __construct(LoggerInterface $logger) } /** - * @param int|string $level Level or level name - * @param bool $callPrevious - * @param bool $restartSyscalls - * @param bool|null $async + * @param int|string|Level $level Level or level name * @return $this * - * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - public function registerSignalHandler(int $signo, $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self + public function registerSignalHandler(int $signo, int|string|Level $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self { if (!extension_loaded('pcntl') || !function_exists('pcntl_signal')) { return $this; } - $level = Logger::toMonologLevel($level); + $level = Logger::toMonologLevel($level)->toPsrLogLevel(); if ($callPrevious) { $handler = pcntl_signal_get_handler($signo); @@ -80,12 +73,12 @@ public function registerSignalHandler(int $signo, $level = LogLevel::CRITICAL, b */ public function handleSignal(int $signo, $siginfo = null): void { + /** @var array $signals */ static $signals = []; - if (!$signals && extension_loaded('pcntl')) { + if (\count($signals) === 0 && extension_loaded('pcntl')) { $pcntl = new ReflectionExtension('pcntl'); - // HHVM 3.24.2 returns an empty array. - foreach ($pcntl->getConstants() ?: get_defined_constants(true)['Core'] as $name => $value) { + foreach ($pcntl->getConstants() as $name => $value) { if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && is_int($value)) { $signals[$value] = $name; } diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Test/TestCase.php b/upload/api/vendor/monolog/monolog/src/Monolog/Test/TestCase.php index bc0b425..98204a9 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Test/TestCase.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Test/TestCase.php @@ -11,18 +11,18 @@ namespace Monolog\Test; +use Monolog\Level; use Monolog\Logger; +use Monolog\LogRecord; use Monolog\DateTimeImmutable; use Monolog\Formatter\FormatterInterface; +use Psr\Log\LogLevel; /** * Lets you easily generate log records and a dummy formatter for testing purposes * * @author Jordi Boggiano * - * @phpstan-import-type Record from \Monolog\Logger - * @phpstan-import-type Level from \Monolog\Logger - * * @internal feel free to reuse this to test your own handlers, this is marked internal to avoid issues with PHPStorm https://github.com/Seldaek/monolog/issues/1677 */ class TestCase extends \PHPUnit\Framework\TestCase @@ -37,47 +37,44 @@ public function tearDown(): void } /** - * @param mixed[] $context - * - * @return array Record + * @param array $context + * @param array $extra * - * @phpstan-param Level $level - * @phpstan-return Record + * @phpstan-param value-of|value-of|Level|LogLevel::* $level */ - protected function getRecord(int $level = Logger::WARNING, string $message = 'test', array $context = []): array + protected function getRecord(int|string|Level $level = Level::Warning, string|\Stringable $message = 'test', array $context = [], string $channel = 'test', \DateTimeImmutable $datetime = new DateTimeImmutable(true), array $extra = []): LogRecord { - return [ - 'message' => (string) $message, - 'context' => $context, - 'level' => $level, - 'level_name' => Logger::getLevelName($level), - 'channel' => 'test', - 'datetime' => new DateTimeImmutable(true), - 'extra' => [], - ]; + return new LogRecord( + message: (string) $message, + context: $context, + level: Logger::toMonologLevel($level), + channel: $channel, + datetime: $datetime, + extra: $extra, + ); } /** - * @phpstan-return Record[] + * @phpstan-return list */ protected function getMultipleRecords(): array { return [ - $this->getRecord(Logger::DEBUG, 'debug message 1'), - $this->getRecord(Logger::DEBUG, 'debug message 2'), - $this->getRecord(Logger::INFO, 'information'), - $this->getRecord(Logger::WARNING, 'warning'), - $this->getRecord(Logger::ERROR, 'error'), + $this->getRecord(Level::Debug, 'debug message 1'), + $this->getRecord(Level::Debug, 'debug message 2'), + $this->getRecord(Level::Info, 'information'), + $this->getRecord(Level::Warning, 'warning'), + $this->getRecord(Level::Error, 'error'), ]; } protected function getIdentityFormatter(): FormatterInterface { $formatter = $this->createMock(FormatterInterface::class); - $formatter->expects($this->any()) + $formatter->expects(self::any()) ->method('format') - ->will($this->returnCallback(function ($record) { - return $record['message']; + ->will(self::returnCallback(function ($record) { + return $record->message; })); return $formatter; diff --git a/upload/api/vendor/monolog/monolog/src/Monolog/Utils.php b/upload/api/vendor/monolog/monolog/src/Monolog/Utils.php index 360c421..9dae253 100644 --- a/upload/api/vendor/monolog/monolog/src/Monolog/Utils.php +++ b/upload/api/vendor/monolog/monolog/src/Monolog/Utils.php @@ -122,7 +122,7 @@ public static function handleJsonError(int $code, $data, ?int $encodeFlags = nul if (is_string($data)) { self::detectAndCleanUtf8($data); } elseif (is_array($data)) { - array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8')); + array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']); } else { self::throwEncodeError($code, $data); } @@ -165,27 +165,16 @@ public static function pcreLastErrorMessage(int $code): string * @param int $code return code of json_last_error function * @param mixed $data data that was meant to be encoded * @throws \RuntimeException - * - * @return never */ - private static function throwEncodeError(int $code, $data): void + private static function throwEncodeError(int $code, $data): never { - switch ($code) { - case JSON_ERROR_DEPTH: - $msg = 'Maximum stack depth exceeded'; - break; - case JSON_ERROR_STATE_MISMATCH: - $msg = 'Underflow or the modes mismatch'; - break; - case JSON_ERROR_CTRL_CHAR: - $msg = 'Unexpected control character found'; - break; - case JSON_ERROR_UTF8: - $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; - break; - default: - $msg = 'Unknown error'; - } + $msg = match ($code) { + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', + default => 'Unknown error', + }; throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true)); } @@ -207,7 +196,7 @@ private static function throwEncodeError(int $code, $data): void */ private static function detectAndCleanUtf8(&$data): void { - if (is_string($data) && !preg_match('//u', $data)) { + if (is_string($data) && preg_match('//u', $data) !== 1) { $data = preg_replace_callback( '/[\x80-\xFF]+/', function ($m) { @@ -217,6 +206,7 @@ function ($m) { ); if (!is_string($data)) { $pcreErrorCode = preg_last_error(); + throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode)); } $data = str_replace( @@ -230,8 +220,8 @@ function ($m) { /** * Converts a string with a valid 'memory_limit' format, to bytes. * - * @param string|false $val - * @return int|false Returns an integer representing bytes. Returns FALSE in case of error. + * @param string|false $val + * @return int|false Returns an integer representing bytes. Returns FALSE in case of error. */ public static function expandIniShorthandBytes($val) { @@ -244,7 +234,7 @@ public static function expandIniShorthandBytes($val) return (int) $val; } - if (!preg_match('/^\s*(?\d+)(?:\.\d+)?\s*(?[gmk]?)\s*$/i', $val, $match)) { + if (preg_match('/^\s*(?\d+)(?:\.\d+)?\s*(?[gmk]?)\s*$/i', $val, $match) !== 1) { return false; } @@ -252,8 +242,10 @@ public static function expandIniShorthandBytes($val) switch (strtolower($match['unit'] ?? '')) { case 'g': $val *= 1024; + // no break case 'm': $val *= 1024; + // no break case 'k': $val *= 1024; } @@ -261,24 +253,22 @@ public static function expandIniShorthandBytes($val) return $val; } - /** - * @param array $record - */ - public static function getRecordMessageForException(array $record): string + public static function getRecordMessageForException(LogRecord $record): string { $context = ''; $extra = ''; + try { - if ($record['context']) { - $context = "\nContext: " . json_encode($record['context']); + if (\count($record->context) > 0) { + $context = "\nContext: " . json_encode($record->context, JSON_THROW_ON_ERROR); } - if ($record['extra']) { - $extra = "\nExtra: " . json_encode($record['extra']); + if (\count($record->extra) > 0) { + $extra = "\nExtra: " . json_encode($record->extra, JSON_THROW_ON_ERROR); } } catch (\Throwable $e) { // noop } - return "\nThe exception occurred while attempting to log: " . $record['message'] . $context . $extra; + return "\nThe exception occurred while attempting to log: " . $record->message . $context . $extra; } } diff --git a/upload/api/vendor/psr/log/composer.json b/upload/api/vendor/psr/log/composer.json index ca05695..879fc6f 100644 --- a/upload/api/vendor/psr/log/composer.json +++ b/upload/api/vendor/psr/log/composer.json @@ -11,16 +11,16 @@ } ], "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, "autoload": { "psr-4": { - "Psr\\Log\\": "Psr/Log/" + "Psr\\Log\\": "src" } }, "extra": { "branch-alias": { - "dev-master": "1.1.x-dev" + "dev-master": "3.x-dev" } } } diff --git a/upload/engine/inc/dleapi.php b/upload/engine/inc/dleapi.php index b2c81fd..47e9b32 100644 --- a/upload/engine/inc/dleapi.php +++ b/upload/engine/inc/dleapi.php @@ -22,8 +22,13 @@ $version = [ 'name' => 'DLE-API', 'descr' => 'Неофициальное API', - 'version' => '0.2.2', + 'version' => '0.3.0', 'changelog' => [ + '0.3.0' => [ + 'Оптимизация кода под PHP 8.2', + 'Минимально поддерживаемая версия DLE - 16.0', + 'Изменён список алгоритмов на hash_hmac_algos' + ], '0.2.2' => [ '[FIX] Поправлены файлы рутинга, которые забыл заменить', '[FIX] Поправлена функция сохранения кеша, из-за чего выдавало ответ null', @@ -84,7 +89,17 @@ else if ($_GET['action'] === 'changelog') $subtitle = ['?mod=dleapi' => $version['descr'], '' => 'Изменения в всериях']; echoheader("{$version['name']} (v{$version['version']})", $subtitle); -function showRow($title = "", $description = "", $field = "", $class = "") { + +/** + * Функция создания заголовка + * + * @param string|null $title + * @param string|null $description + * @param string|null $field + * @param string|null $class + * @return void + */ +function showRow(?string $title, ?string $description, ?string $field, ?string $class) : void { echo "
{$title}
{$description} @@ -93,13 +108,15 @@ function showRow($title = "", $description = "", $field = "", $class = "") { } /** - * @param $options - * @param $name - * @param $selected + * Функция выпадающего меню + * + * @param array $options + * @param string $name + * @param string|null $selected * * @return string */ -function makeDropDown($options, $name, $selected) { +function makeDropDown(array $options, string $name, ?string $selected) : string { $output = "'); + ''); showRow('Длина ключа', - 'Задаём длину ключа, по которой будет генерироваться автоматический API ключ. Разделитель не учитывается. Если будет не хватка символов, то будут генерироваться случайные символы, пока не заполнят длину ключа. Или же набор символов будет урезан.
Важно: Деление общей длины и длины блока должно быть без остатка. Скрипт будет сам подставлять нужное значение.', - ''); + 'Задаём длину ключа, по которой будет генерироваться автоматический API ключ. Разделитель не учитывается. Если будет не хватка символов, то будут генерироваться случайные символы, пока не заполнят длину ключа. Или же набор символов будет урезан.
Важно: Деление общей длины и длины блока должно быть без остатка. Скрипт будет сам подставлять нужное значение.', + ''); showRow('Разделитель блока', 'Задаём разделитель блока, который будет делить блоки. Пример: -', - ''); + ''); showRow('Секретный ключ', 'Секретный ключ для генерации ключа. Пример: ' . - $config['http_home_url'] . '', - ''); + $config['http_home_url'] . '', + ''); echo << HTML; showRow('Ключ', - 'Уникальный ключ доступа. Генерация ключа происходит при помощи алгоритма, ID пользователя и секретного ключа.', - '
', - 'white-line'); + 'Уникальный ключ доступа. Генерация ключа происходит при помощи алгоритма, ID пользователя и секретного ключа.', + '
', + 'white-line'); showRow('Пользователь', 'Выбор пользователя для ключа', makeDropDown(getUsers(), 'save_con[user]', '')); showRow('Полный доступ', - 'Данная опция будет игнорировать прочие полномочия и даст полный доступ ко всем таблицам', - makeCheckBox('save_con[is_admin]', '')); + 'Данная опция будет игнорировать прочие полномочия и даст полный доступ ко всем таблицам', + makeCheckBox('save_con[is_admin]', '')); showRow('Только своё?', 'Данная опция будет выводить только те данные, что связаны с API пользователя.', - makeCheckBox('save_con[own_only]', '')); + makeCheckBox('save_con[own_only]', '')); showRow('Активен?', 'Данная опция включает этот ключ', makeCheckBox('save_con[active]', '1')); echo << @@ -747,7 +767,7 @@ function pbkdf2($algorithm = 2, $user_id, $salt, $key_length, $separator, $block case 'edit': - $this_id = (int)$_GET['id']; + $this_id = (int) $_GET['id']; $api_key = $db->super_query('SELECT * FROM ' . PREFIX . "_api_keys WHERE id = {$this_id}"); @@ -769,19 +789,19 @@ function pbkdf2($algorithm = 2, $user_id, $salt, $key_length, $separator, $block HTML; showRow('Ключ', - 'Уникальный ключ доступа. Генерация ключа происходит при помощи алгоритма, ID пользователя и секретного ключа.', - '
', - 'white-line'); + 'Уникальный ключ доступа. Генерация ключа происходит при помощи алгоритма, ID пользователя и секретного ключа.', + '
', + 'white-line'); showRow('Пользователь', 'Выбор пользователя для ключа', - makeDropDown(getUsers(), 'save_con[user]', $api_key['user_id'])); + makeDropDown(getUsers(), 'save_con[user]', $api_key['user_id'])); showRow('Полный доступ', - 'Данная опция будет игнорировать прочие полномочия и даст полный доступ ко всем таблицам', - makeCheckBox('save_con[is_admin]', $api_key['is_admin'])); + 'Данная опция будет игнорировать прочие полномочия и даст полный доступ ко всем таблицам', + makeCheckBox('save_con[is_admin]', $api_key['is_admin'])); showRow('Только своё?', 'Данная опция будет выводить только те данные, что связаны с API пользователя.', - makeCheckBox('save_con[own_only]', $api_key['own_only'])); + makeCheckBox('save_con[own_only]', $api_key['own_only'])); showRow('Активен?', 'Данная опция включает этот ключ', makeCheckBox('save_con[active]', - $api_key['active'])); + $api_key['active'])); echo << @@ -979,7 +999,7 @@ function pbkdf2($algorithm = 2, $user_id, $salt, $key_length, $separator, $block default: - $start_from = (int)$_REQUEST['start_from']; + $start_from = (int) $_REQUEST['start_from']; $api_per_page = 50; if ($start_from < 0) $start_from = 0; diff --git a/upload/install.xml b/upload/install.xml index 9affda9..5ccfabe 100644 --- a/upload/install.xml +++ b/upload/install.xml @@ -3,8 +3,8 @@ DLE-API Неофициальное API для CMS DLE - 0.2.2 - 13.0 + 0.3.0 + 16.0 greater 1 diff --git "a/\320\237\321\200\320\276\321\207\321\202\320\270 \320\274\320\265\320\275\321\217.txt" "b/\320\237\321\200\320\276\321\207\321\202\320\270 \320\274\320\265\320\275\321\217.txt" deleted file mode 100644 index 3e899c5..0000000 --- "a/\320\237\321\200\320\276\321\207\321\202\320\270 \320\274\320\265\320\275\321\217.txt" +++ /dev/null @@ -1,124 +0,0 @@ -DLE API -Модификация для админпанели и глобальные функции для моих разработок Совместимость проверенна на DLE-версиях 13.х. Для корректной работы требуется минимальная версия MySQL 5.5.6 или MariaDB 10.0, поскольку используются Foreign Key, которые требуют наличие InnoDB. -Для установки достаточно скачать релиз (https://github.com/Gokujo/dle_api/releases/latest). -Документация к API находится на сервере POSTMAN (https://documenter.getpostman.com/view/7856564/SW7T9BsW). -На данный момент она не полная и пополняется медлено, но верно. Релизы выше только для версий DLE 13 и выше. -Для пожеланий можно использовать feathub (https://feathub.com/Gokujo/dle_api)). - -DLE >= 13.x -Скачайте релиз. У вас три варианта для установки: - -1. При помощи bat-Скрипта. Для пользователей Windows Для этого устанавливаем 7Zip (https://www.7-zip.org/download.html). После установки запускаем скрипт install_archive.bat. После завершения установки - загружаем install.zip в менеджер плагинов. -2. Упаковать самому Любым архиватором запаковать всё содержимое в папке upload, причём так, чтобы в корне архива был файл install.xml и папка engine. Затем устанавливаем архив через менеджер плагинов. -3. Просто залить Залейте папку engine в корень сайта и установите плагин через менеджер плагинов. - -DLE < 13 -В теории, и на движках младше всё должно работать, поскольку в процессе не затрагиваются файлы движка. Но, это не точно, я не пробовал, не эксперементировал. На свой страх и риск. - -Установка -Залить папки api и engine из папки upload в корень сайта. Затем выполнить запрос в базу данных: - -create or replace procedure addFieldIfNotExists(IN table_name_IN varchar(100), IN field_name_IN varchar(100), - IN field_definition_IN varchar(100)) -BEGIN - - SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN); - IF (@isFieldThere = 0) THEN - - SET @ddl = CONCAT('ALTER TABLE ', table_name_IN); - SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN'); - SET @ddl = CONCAT(@ddl, ' ', field_name_IN); - SET @ddl = CONCAT(@ddl, ' ', field_definition_IN); - - PREPARE stmt FROM @ddl; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - END IF; - -END; - -create or replace function isFieldExisting(table_name_IN varchar(100), field_name_IN varchar(100)) returns int - RETURN ( - SELECT COUNT(COLUMN_NAME) - FROM INFORMATION_SCHEMA.columns - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = table_name_IN - AND COLUMN_NAME = field_name_IN - ); - -CREATE TABLE {prefix}_api_keys ( - id int auto_increment - primary key, - api varchar(255) not null, - is_admin tinyint(1) default 0 not null, - creator int default 0 null, - created datetime default CURRENT_TIMESTAMP not null, - active tinyint(1) default 0 not null, - user_id int default 0 not null, - own_only tinyint(1) default 1 not null, - constraint {prefix}_api_keys_key_uindex - unique (api) -); - -create table {prefix}_api_scope ( - scope_id int auto_increment - primary key, - `table` varchar(255) null, - `read` tinyint(1) default 0 not null, - `write` tinyint(1) default 0 not null, - `delete` tinyint(1) default 0 not null, - key_id int default 0 not null, - constraint {prefix}_api_scope_{prefix}_api_keys_id_fk - foreign key (key_id) references {prefix}_api_keys (id) - on update cascade on delete cascade -); - -INSERT INTO {prefix}_admin_sections (name, title, descr, icon, allow_groups) VALUES ('dleapi', 'DLE-API', 'Неофициальное API для DLE. Раздел по созданию и управлению над ключами доступа к API.', '/engine/skins/images/icons/dleapi.png', 1); - -Обновление -Заменить все файлы из папки upload, кроме install.xml. - -Выполнить SQL запрос -create or replace procedure addFieldIfNotExists(IN table_name_IN varchar(100), IN field_name_IN varchar(100), - IN field_definition_IN varchar(100)) -BEGIN - - SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN); - IF (@isFieldThere = 0) THEN - - SET @ddl = CONCAT('ALTER TABLE ', table_name_IN); - SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN'); - SET @ddl = CONCAT(@ddl, ' ', field_name_IN); - SET @ddl = CONCAT(@ddl, ' ', field_definition_IN); - - PREPARE stmt FROM @ddl; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - - END IF; - -END; - -create or replace function isFieldExisting(table_name_IN varchar(100), field_name_IN varchar(100)) returns int - RETURN ( - SELECT COUNT(COLUMN_NAME) - FROM INFORMATION_SCHEMA.columns - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = table_name_IN - AND COLUMN_NAME = field_name_IN - ); - -CALL addFieldIfNotExists ('{prefix}_api_keys', 'own_only', 'boolean default false not null'); - - -Удаление -Удаляем из корня сайта папку api, a так-же из папки engine/inc файл dleapi.php и из engine/skins/images файл dleapi.png. - -Выполняем запрос в базу данных: -DELETE FROM {prefix}_admin_sections WHERE `name` = 'dleapi'; -DROP TABLE {prefix}_api_keys cascade, {prefix}_api_scope cascade; -DROP PROCEDURE IF EXISTS addFieldIfNotExists; -DROP FUNCTION IF EXISTS isFieldExisting; - -{prefix} заменяем на свой префикс базы данных.