diff --git a/vendor/autoload.php b/vendor/autoload.php index 69df693f0..0dfc978f8 100644 --- a/vendor/autoload.php +++ b/vendor/autoload.php @@ -22,4 +22,4 @@ require_once __DIR__ . '/composer/autoload_real.php'; -return ComposerAutoloaderInit01edbf89a2a31910527aa0e7dc75324b::getLoader(); +return ComposerAutoloaderInit8cc69a57001ff18655c419e4501e58cd::getLoader(); diff --git a/vendor/brick/math/CHANGELOG.md b/vendor/brick/math/CHANGELOG.md index 17cea8d9f..03c3d824d 100644 --- a/vendor/brick/math/CHANGELOG.md +++ b/vendor/brick/math/CHANGELOG.md @@ -2,41 +2,11 @@ All notable changes to this project will be documented in this file. -## [0.11.0](https://github.com/brick/math/releases/tag/0.11.0) - 2023-01-16 - -💥 **Breaking changes** - -- Minimum PHP version is now 8.0 -- Methods accepting a union of types are now strongly typed* -- `MathException` now extends `Exception` instead of `RuntimeException` - -* You may now run into type errors if you were passing `Stringable` objects to `of()` or any of the methods -internally calling `of()`, with `strict_types` enabled. You can fix this by casting `Stringable` objects to `string` -first. - -## [0.10.2](https://github.com/brick/math/releases/tag/0.10.2) - 2022-08-11 - -👌 **Improvements** - -- `BigRational::toFloat()` now simplifies the fraction before performing division (#73) thanks to @olsavmic - -## [0.10.1](https://github.com/brick/math/releases/tag/0.10.1) - 2022-08-02 - -✨ **New features** - -- `BigInteger::gcdMultiple()` returns the GCD of multiple `BigInteger` numbers - -## [0.10.0](https://github.com/brick/math/releases/tag/0.10.0) - 2022-06-18 - -💥 **Breaking changes** - -- Minimum PHP version is now 7.4 - ## [0.9.3](https://github.com/brick/math/releases/tag/0.9.3) - 2021-08-15 🚀 **Compatibility with PHP 8.1** -- Support for custom object serialization; this removes a warning on PHP 8.1 due to the `Serializable` interface being deprecated (#60) thanks @TRowbotham +- Support for custom object serialization; this removes a warning on PHP 8.1 due to the `Serializable` interface being deprecated (thanks @TRowbotham) ## [0.9.2](https://github.com/brick/math/releases/tag/0.9.2) - 2021-01-20 @@ -46,7 +16,7 @@ first. ## [0.9.1](https://github.com/brick/math/releases/tag/0.9.1) - 2020-08-19 -✨ **New features** +✨ New features - `BigInteger::not()` returns the bitwise `NOT` value @@ -355,8 +325,8 @@ This release also comes with many performance improvements. - `getFraction()` is renamed to `fraction()` - `divideAndRemainder()` is renamed to `quotientAndRemainder()` - `dividedBy()` now takes a **mandatory** `$scale` parameter **before** the rounding mode - - `toBigInteger()` does not accept a `$roundingMode` parameter anymore - - `toBigRational()` does not simplify the fraction anymore; explicitly add `->simplified()` to get the previous behaviour + - `toBigInteger()` does not accept a `$roundingMode` parameter any more + - `toBigRational()` does not simplify the fraction any more; explicitly add `->simplified()` to get the previous behaviour - `BigRational`: - `getSign()` is renamed to `sign()` - `getNumerator()` is renamed to `numerator()` @@ -430,7 +400,7 @@ Added `BigDecimal::divideAndRemainder()` ## [0.2.0](https://github.com/brick/math/releases/tag/0.2.0) - 2015-05-22 -- `min()` and `max()` do not accept an `array` anymore, but a variable number of parameters +- `min()` and `max()` do not accept an `array` any more, but a variable number of parameters - **minimum PHP version is now 5.6** - continuous integration with PHP 7 diff --git a/vendor/brick/math/composer.json b/vendor/brick/math/composer.json index ed817bdd0..ec196632f 100644 --- a/vendor/brick/math/composer.json +++ b/vendor/brick/math/composer.json @@ -14,12 +14,13 @@ ], "license": "MIT", "require": { - "php": "^8.0" + "php": "^7.1 || ^8.0", + "ext-json": "*" }, "require-dev": { - "phpunit/phpunit": "^9.0", + "phpunit/phpunit": "^7.5.15 || ^8.5 || ^9.0", "php-coveralls/php-coveralls": "^2.2", - "vimeo/psalm": "5.0.0" + "vimeo/psalm": "4.9.2" }, "autoload": { "psr-4": { diff --git a/vendor/brick/math/src/BigDecimal.php b/vendor/brick/math/src/BigDecimal.php index 02fc65612..78246500c 100644 --- a/vendor/brick/math/src/BigDecimal.php +++ b/vendor/brick/math/src/BigDecimal.php @@ -22,15 +22,19 @@ final class BigDecimal extends BigNumber * This is a string of digits with an optional leading minus sign. * No leading zero must be present. * No leading minus sign must be present if the value is 0. + * + * @var string */ - private string $value; + private $value; /** * The scale (number of digits after the decimal point) of this decimal number. * * This must be zero or more. + * + * @var int */ - private int $scale; + private $scale; /** * Protected constructor. Use a factory method to obtain an instance. @@ -47,11 +51,15 @@ protected function __construct(string $value, int $scale = 0) /** * Creates a BigDecimal of the given value. * + * @param BigNumber|int|float|string $value + * + * @return BigDecimal + * * @throws MathException If the value cannot be converted to a BigDecimal. * * @psalm-pure */ - public static function of(BigNumber|int|float|string $value) : BigDecimal + public static function of($value) : BigNumber { return parent::of($value)->toBigDecimal(); } @@ -64,11 +72,13 @@ public static function of(BigNumber|int|float|string $value) : BigDecimal * @param BigNumber|int|float|string $value The unscaled value. Must be convertible to a BigInteger. * @param int $scale The scale of the number, positive or zero. * + * @return BigDecimal + * * @throws \InvalidArgumentException If the scale is negative. * * @psalm-pure */ - public static function ofUnscaledValue(BigNumber|int|float|string $value, int $scale = 0) : BigDecimal + public static function ofUnscaledValue($value, int $scale = 0) : BigDecimal { if ($scale < 0) { throw new \InvalidArgumentException('The scale cannot be negative.'); @@ -80,6 +90,8 @@ public static function ofUnscaledValue(BigNumber|int|float|string $value, int $s /** * Returns a BigDecimal representing zero, with a scale of zero. * + * @return BigDecimal + * * @psalm-pure */ public static function zero() : BigDecimal @@ -100,6 +112,8 @@ public static function zero() : BigDecimal /** * Returns a BigDecimal representing one, with a scale of zero. * + * @return BigDecimal + * * @psalm-pure */ public static function one() : BigDecimal @@ -120,6 +134,8 @@ public static function one() : BigDecimal /** * Returns a BigDecimal representing ten, with a scale of zero. * + * @return BigDecimal + * * @psalm-pure */ public static function ten() : BigDecimal @@ -144,9 +160,11 @@ public static function ten() : BigDecimal * * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigDecimal. * + * @return BigDecimal The result. + * * @throws MathException If the number is not valid, or is not convertible to a BigDecimal. */ - public function plus(BigNumber|int|float|string $that) : BigDecimal + public function plus($that) : BigDecimal { $that = BigDecimal::of($that); @@ -173,9 +191,11 @@ public function plus(BigNumber|int|float|string $that) : BigDecimal * * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigDecimal. * + * @return BigDecimal The result. + * * @throws MathException If the number is not valid, or is not convertible to a BigDecimal. */ - public function minus(BigNumber|int|float|string $that) : BigDecimal + public function minus($that) : BigDecimal { $that = BigDecimal::of($that); @@ -198,9 +218,11 @@ public function minus(BigNumber|int|float|string $that) : BigDecimal * * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigDecimal. * + * @return BigDecimal The result. + * * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigDecimal. */ - public function multipliedBy(BigNumber|int|float|string $that) : BigDecimal + public function multipliedBy($that) : BigDecimal { $that = BigDecimal::of($that); @@ -225,10 +247,12 @@ public function multipliedBy(BigNumber|int|float|string $that) : BigDecimal * @param int|null $scale The desired scale, or null to use the scale of this number. * @param int $roundingMode An optional rounding mode. * + * @return BigDecimal + * * @throws \InvalidArgumentException If the scale or rounding mode is invalid. * @throws MathException If the number is invalid, is zero, or rounding was necessary. */ - public function dividedBy(BigNumber|int|float|string $that, ?int $scale = null, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal + public function dividedBy($that, ?int $scale = null, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal { $that = BigDecimal::of($that); @@ -261,10 +285,12 @@ public function dividedBy(BigNumber|int|float|string $that, ?int $scale = null, * * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. * + * @return BigDecimal The result. + * * @throws MathException If the divisor is not a valid number, is not convertible to a BigDecimal, is zero, * or the result yields an infinite number of digits. */ - public function exactlyDividedBy(BigNumber|int|float|string $that) : BigDecimal + public function exactlyDividedBy($that) : BigDecimal { $that = BigDecimal::of($that); @@ -300,6 +326,10 @@ public function exactlyDividedBy(BigNumber|int|float|string $that) : BigDecimal * * The result has a scale of `$this->scale * $exponent`. * + * @param int $exponent The exponent. + * + * @return BigDecimal The result. + * * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. */ public function power(int $exponent) : BigDecimal @@ -330,9 +360,11 @@ public function power(int $exponent) : BigDecimal * * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. * + * @return BigDecimal The quotient. + * * @throws MathException If the divisor is not a valid decimal number, or is zero. */ - public function quotient(BigNumber|int|float|string $that) : BigDecimal + public function quotient($that) : BigDecimal { $that = BigDecimal::of($that); @@ -355,9 +387,11 @@ public function quotient(BigNumber|int|float|string $that) : BigDecimal * * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal. * + * @return BigDecimal The remainder. + * * @throws MathException If the divisor is not a valid decimal number, or is zero. */ - public function remainder(BigNumber|int|float|string $that) : BigDecimal + public function remainder($that) : BigDecimal { $that = BigDecimal::of($that); @@ -386,7 +420,7 @@ public function remainder(BigNumber|int|float|string $that) : BigDecimal * * @throws MathException If the divisor is not a valid decimal number, or is zero. */ - public function quotientAndRemainder(BigNumber|int|float|string $that) : array + public function quotientAndRemainder($that) : array { $that = BigDecimal::of($that); @@ -410,6 +444,10 @@ public function quotientAndRemainder(BigNumber|int|float|string $that) : array /** * Returns the square root of this number, rounded down to the given number of decimals. * + * @param int $scale + * + * @return BigDecimal + * * @throws \InvalidArgumentException If the scale is negative. * @throws NegativeNumberException If this number is negative. */ @@ -450,6 +488,10 @@ public function sqrt(int $scale) : BigDecimal /** * Returns a copy of this BigDecimal with the decimal point moved $n places to the left. + * + * @param int $n + * + * @return BigDecimal */ public function withPointMovedLeft(int $n) : BigDecimal { @@ -466,6 +508,10 @@ public function withPointMovedLeft(int $n) : BigDecimal /** * Returns a copy of this BigDecimal with the decimal point moved $n places to the right. + * + * @param int $n + * + * @return BigDecimal */ public function withPointMovedRight(int $n) : BigDecimal { @@ -492,6 +538,8 @@ public function withPointMovedRight(int $n) : BigDecimal /** * Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part. + * + * @return BigDecimal */ public function stripTrailingZeros() : BigDecimal { @@ -523,6 +571,8 @@ public function stripTrailingZeros() : BigDecimal /** * Returns the absolute value of this number. + * + * @return BigDecimal */ public function abs() : BigDecimal { @@ -531,13 +581,18 @@ public function abs() : BigDecimal /** * Returns the negated value of this number. + * + * @return BigDecimal */ public function negated() : BigDecimal { return new BigDecimal(Calculator::get()->neg($this->value), $this->scale); } - public function compareTo(BigNumber|int|float|string $that) : int + /** + * {@inheritdoc} + */ + public function compareTo($that) : int { $that = BigNumber::of($that); @@ -554,16 +609,25 @@ public function compareTo(BigNumber|int|float|string $that) : int return - $that->compareTo($this); } + /** + * {@inheritdoc} + */ public function getSign() : int { return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1); } + /** + * @return BigInteger + */ public function getUnscaledValue() : BigInteger { - return self::newBigInteger($this->value); + return BigInteger::create($this->value); } + /** + * @return int + */ public function getScale() : int { return $this->scale; @@ -573,6 +637,8 @@ public function getScale() : int * Returns a string representing the integral part of this decimal number. * * Example: `-123.456` => `-123`. + * + * @return string */ public function getIntegralPart() : string { @@ -591,6 +657,8 @@ public function getIntegralPart() : string * If the scale is zero, an empty string is returned. * * Examples: `-123.456` => '456', `123` => ''. + * + * @return string */ public function getFractionalPart() : string { @@ -605,32 +673,46 @@ public function getFractionalPart() : string /** * Returns whether this decimal number has a non-zero fractional part. + * + * @return bool */ public function hasNonZeroFractionalPart() : bool { return $this->getFractionalPart() !== \str_repeat('0', $this->scale); } + /** + * {@inheritdoc} + */ public function toBigInteger() : BigInteger { $zeroScaleDecimal = $this->scale === 0 ? $this : $this->dividedBy(1, 0); - return self::newBigInteger($zeroScaleDecimal->value); + return BigInteger::create($zeroScaleDecimal->value); } + /** + * {@inheritdoc} + */ public function toBigDecimal() : BigDecimal { return $this; } + /** + * {@inheritdoc} + */ public function toBigRational() : BigRational { - $numerator = self::newBigInteger($this->value); - $denominator = self::newBigInteger('1' . \str_repeat('0', $this->scale)); + $numerator = BigInteger::create($this->value); + $denominator = BigInteger::create('1' . \str_repeat('0', $this->scale)); - return self::newBigRational($numerator, $denominator, false); + return BigRational::create($numerator, $denominator, false); } + /** + * {@inheritdoc} + */ public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal { if ($scale === $this->scale) { @@ -640,16 +722,25 @@ public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSAR return $this->dividedBy(BigDecimal::one(), $scale, $roundingMode); } + /** + * {@inheritdoc} + */ public function toInt() : int { return $this->toBigInteger()->toInt(); } + /** + * {@inheritdoc} + */ public function toFloat() : float { return (float) (string) $this; } + /** + * {@inheritdoc} + */ public function __toString() : string { if ($this->scale === 0) { @@ -681,6 +772,8 @@ public function __serialize(): array * * @param array{value: string, scale: int} $data * + * @return void + * * @throws \LogicException */ public function __unserialize(array $data): void @@ -697,6 +790,8 @@ public function __unserialize(array $data): void * This method is required by interface Serializable and SHOULD NOT be accessed directly. * * @internal + * + * @return string */ public function serialize() : string { @@ -709,6 +804,10 @@ public function serialize() : string * @internal * @psalm-suppress RedundantPropertyInitializationCheck * + * @param string $value + * + * @return void + * * @throws \LogicException */ public function unserialize($value) : void @@ -726,6 +825,9 @@ public function unserialize($value) : void /** * Puts the internal values of the given decimal numbers on the same scale. * + * @param BigDecimal $x The first decimal number. + * @param BigDecimal $y The second decimal number. + * * @return array{string, string} The scaled integer values of $x and $y. */ private function scaleValues(BigDecimal $x, BigDecimal $y) : array @@ -742,6 +844,11 @@ private function scaleValues(BigDecimal $x, BigDecimal $y) : array return [$a, $b]; } + /** + * @param int $scale + * + * @return string + */ private function valueWithMinScale(int $scale) : string { $value = $this->value; @@ -755,6 +862,8 @@ private function valueWithMinScale(int $scale) : string /** * Adds leading zeros if necessary to the unscaled value to represent the full decimal number. + * + * @return string */ private function getUnscaledValueWithLeadingZeros() : string { diff --git a/vendor/brick/math/src/BigInteger.php b/vendor/brick/math/src/BigInteger.php index 435679331..f213fbedb 100644 --- a/vendor/brick/math/src/BigInteger.php +++ b/vendor/brick/math/src/BigInteger.php @@ -26,8 +26,10 @@ final class BigInteger extends BigNumber * * No leading zeros must be present. * No leading minus sign must be present if the number is zero. + * + * @var string */ - private string $value; + private $value; /** * Protected constructor. Use a factory method to obtain an instance. @@ -42,11 +44,15 @@ protected function __construct(string $value) /** * Creates a BigInteger of the given value. * + * @param BigNumber|int|float|string $value + * + * @return BigInteger + * * @throws MathException If the value cannot be converted to a BigInteger. * * @psalm-pure */ - public static function of(BigNumber|int|float|string $value) : BigInteger + public static function of($value) : BigNumber { return parent::of($value)->toBigInteger(); } @@ -65,6 +71,8 @@ public static function of(BigNumber|int|float|string $value) : BigInteger * @param string $number The number to convert, in the given base. * @param int $base The base of the number, between 2 and 36. * + * @return BigInteger + * * @throws NumberFormatException If the number is empty, or contains invalid chars for the given base. * @throws \InvalidArgumentException If the base is out of range. * @@ -130,6 +138,8 @@ public static function fromBase(string $number, int $base) : BigInteger * @param string $number The number to parse. * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8. * + * @return BigInteger + * * @throws NumberFormatException If the given number is empty or contains invalid chars for the given alphabet. * @throws \InvalidArgumentException If the alphabet does not contain at least 2 chars. * @@ -173,6 +183,8 @@ public static function fromArbitraryBase(string $number, string $alphabet) : Big * @param bool $signed Whether to interpret as a signed number in two's-complement representation with a leading * sign bit. * + * @return BigInteger + * * @throws NumberFormatException If the string is empty. */ public static function fromBytes(string $value, bool $signed = true) : BigInteger @@ -205,13 +217,15 @@ public static function fromBytes(string $value, bool $signed = true) : BigIntege * * Using the default random bytes generator, this method is suitable for cryptographic use. * - * @psalm-param (callable(int): string)|null $randomBytesGenerator + * @psalm-param callable(int): string $randomBytesGenerator * * @param int $numBits The number of bits. * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, and returns a * string of random bytes of the given length. Defaults to the * `random_bytes()` function. * + * @return BigInteger + * * @throws \InvalidArgumentException If $numBits is negative. */ public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null) : BigInteger @@ -252,14 +266,13 @@ public static function randomBits(int $numBits, ?callable $randomBytesGenerator * and returns a string of random bytes of the given length. * Defaults to the `random_bytes()` function. * + * @return BigInteger + * * @throws MathException If one of the parameters cannot be converted to a BigInteger, * or `$min` is greater than `$max`. */ - public static function randomRange( - BigNumber|int|float|string $min, - BigNumber|int|float|string $max, - ?callable $randomBytesGenerator = null - ) : BigInteger { + public static function randomRange($min, $max, ?callable $randomBytesGenerator = null) : BigInteger + { $min = BigInteger::of($min); $max = BigInteger::of($max); @@ -285,6 +298,8 @@ public static function randomRange( /** * Returns a BigInteger representing zero. * + * @return BigInteger + * * @psalm-pure */ public static function zero() : BigInteger @@ -305,6 +320,8 @@ public static function zero() : BigInteger /** * Returns a BigInteger representing one. * + * @return BigInteger + * * @psalm-pure */ public static function one() : BigInteger @@ -325,6 +342,8 @@ public static function one() : BigInteger /** * Returns a BigInteger representing ten. * + * @return BigInteger + * * @psalm-pure */ public static function ten() : BigInteger @@ -342,29 +361,16 @@ public static function ten() : BigInteger return $ten; } - public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger - { - $result = $a; - - foreach ($n as $next) { - $result = $result->gcd($next); - - if ($result->isEqualTo(1)) { - return $result; - } - } - - return $result; - } - /** * Returns the sum of this number and the given one. * * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger. * + * @return BigInteger The result. + * * @throws MathException If the number is not valid, or is not convertible to a BigInteger. */ - public function plus(BigNumber|int|float|string $that) : BigInteger + public function plus($that) : BigInteger { $that = BigInteger::of($that); @@ -386,9 +392,11 @@ public function plus(BigNumber|int|float|string $that) : BigInteger * * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigInteger. * + * @return BigInteger The result. + * * @throws MathException If the number is not valid, or is not convertible to a BigInteger. */ - public function minus(BigNumber|int|float|string $that) : BigInteger + public function minus($that) : BigInteger { $that = BigInteger::of($that); @@ -406,9 +414,11 @@ public function minus(BigNumber|int|float|string $that) : BigInteger * * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger. * + * @return BigInteger The result. + * * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger. */ - public function multipliedBy(BigNumber|int|float|string $that) : BigInteger + public function multipliedBy($that) : BigInteger { $that = BigInteger::of($that); @@ -431,10 +441,12 @@ public function multipliedBy(BigNumber|int|float|string $that) : BigInteger * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. * @param int $roundingMode An optional rounding mode. * + * @return BigInteger The result. + * * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero, * or RoundingMode::UNNECESSARY is used and the remainder is not zero. */ - public function dividedBy(BigNumber|int|float|string $that, int $roundingMode = RoundingMode::UNNECESSARY) : BigInteger + public function dividedBy($that, int $roundingMode = RoundingMode::UNNECESSARY) : BigInteger { $that = BigInteger::of($that); @@ -454,6 +466,10 @@ public function dividedBy(BigNumber|int|float|string $that, int $roundingMode = /** * Returns this number exponentiated to the given value. * + * @param int $exponent The exponent. + * + * @return BigInteger The result. + * * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. */ public function power(int $exponent) : BigInteger @@ -482,9 +498,11 @@ public function power(int $exponent) : BigInteger * * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. * + * @return BigInteger + * * @throws DivisionByZeroException If the divisor is zero. */ - public function quotient(BigNumber|int|float|string $that) : BigInteger + public function quotient($that) : BigInteger { $that = BigInteger::of($that); @@ -508,9 +526,11 @@ public function quotient(BigNumber|int|float|string $that) : BigInteger * * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. * + * @return BigInteger + * * @throws DivisionByZeroException If the divisor is zero. */ - public function remainder(BigNumber|int|float|string $that) : BigInteger + public function remainder($that) : BigInteger { $that = BigInteger::of($that); @@ -536,7 +556,7 @@ public function remainder(BigNumber|int|float|string $that) : BigInteger * * @throws DivisionByZeroException If the divisor is zero. */ - public function quotientAndRemainder(BigNumber|int|float|string $that) : array + public function quotientAndRemainder($that) : array { $that = BigInteger::of($that); @@ -562,9 +582,11 @@ public function quotientAndRemainder(BigNumber|int|float|string $that) : array * * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger. * + * @return BigInteger + * * @throws DivisionByZeroException If the divisor is zero. */ - public function mod(BigNumber|int|float|string $that) : BigInteger + public function mod($that) : BigInteger { $that = BigInteger::of($that); @@ -580,6 +602,10 @@ public function mod(BigNumber|int|float|string $that) : BigInteger /** * Returns the modular multiplicative inverse of this BigInteger modulo $m. * + * @param BigInteger $m + * + * @return BigInteger + * * @throws DivisionByZeroException If $m is zero. * @throws NegativeNumberException If $m is negative. * @throws MathException If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger @@ -616,10 +642,12 @@ public function modInverse(BigInteger $m) : BigInteger * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero. * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive. * + * @return BigInteger + * * @throws NegativeNumberException If any of the operands is negative. * @throws DivisionByZeroException If the modulus is zero. */ - public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod) : BigInteger + public function modPow($exp, $mod) : BigInteger { $exp = BigInteger::of($exp); $mod = BigInteger::of($mod); @@ -643,8 +671,10 @@ public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|stri * The GCD is always positive, unless both operands are zero, in which case it is zero. * * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + * + * @return BigInteger */ - public function gcd(BigNumber|int|float|string $that) : BigInteger + public function gcd($that) : BigInteger { $that = BigInteger::of($that); @@ -666,6 +696,8 @@ public function gcd(BigNumber|int|float|string $that) : BigInteger * * The result is the largest x such that x² ≤ n. * + * @return BigInteger + * * @throws NegativeNumberException If this number is negative. */ public function sqrt() : BigInteger @@ -681,6 +713,8 @@ public function sqrt() : BigInteger /** * Returns the absolute value of this number. + * + * @return BigInteger */ public function abs() : BigInteger { @@ -689,6 +723,8 @@ public function abs() : BigInteger /** * Returns the inverse of this number. + * + * @return BigInteger */ public function negated() : BigInteger { @@ -701,8 +737,10 @@ public function negated() : BigInteger * This method returns a negative BigInteger if and only if both operands are negative. * * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + * + * @return BigInteger */ - public function and(BigNumber|int|float|string $that) : BigInteger + public function and($that) : BigInteger { $that = BigInteger::of($that); @@ -715,8 +753,10 @@ public function and(BigNumber|int|float|string $that) : BigInteger * This method returns a negative BigInteger if and only if either of the operands is negative. * * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + * + * @return BigInteger */ - public function or(BigNumber|int|float|string $that) : BigInteger + public function or($that) : BigInteger { $that = BigInteger::of($that); @@ -729,8 +769,10 @@ public function or(BigNumber|int|float|string $that) : BigInteger * This method returns a negative BigInteger if and only if exactly one of the operands is negative. * * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number. + * + * @return BigInteger */ - public function xor(BigNumber|int|float|string $that) : BigInteger + public function xor($that) : BigInteger { $that = BigInteger::of($that); @@ -739,6 +781,8 @@ public function xor(BigNumber|int|float|string $that) : BigInteger /** * Returns the bitwise-not of this BigInteger. + * + * @return BigInteger */ public function not() : BigInteger { @@ -747,6 +791,10 @@ public function not() : BigInteger /** * Returns the integer left shifted by a given number of bits. + * + * @param int $distance The distance to shift. + * + * @return BigInteger */ public function shiftedLeft(int $distance) : BigInteger { @@ -763,6 +811,10 @@ public function shiftedLeft(int $distance) : BigInteger /** * Returns the integer right shifted by a given number of bits. + * + * @param int $distance The distance to shift. + * + * @return BigInteger */ public function shiftedRight(int $distance) : BigInteger { @@ -788,6 +840,8 @@ public function shiftedRight(int $distance) : BigInteger * * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. * Computes (ceil(log2(this < 0 ? -this : this+1))). + * + * @return int */ public function getBitLength() : int { @@ -806,6 +860,8 @@ public function getBitLength() : int * Returns the index of the rightmost (lowest-order) one bit in this BigInteger. * * Returns -1 if this BigInteger contains no one bits. + * + * @return int */ public function getLowestSetBit() : int { @@ -825,6 +881,8 @@ public function getLowestSetBit() : int /** * Returns whether this number is even. + * + * @return bool */ public function isEven() : bool { @@ -833,6 +891,8 @@ public function isEven() : bool /** * Returns whether this number is odd. + * + * @return bool */ public function isOdd() : bool { @@ -846,6 +906,8 @@ public function isOdd() : bool * * @param int $n The bit to test, 0-based. * + * @return bool + * * @throws \InvalidArgumentException If the bit to test is negative. */ public function testBit(int $n) : bool @@ -857,7 +919,10 @@ public function testBit(int $n) : bool return $this->shiftedRight($n)->isOdd(); } - public function compareTo(BigNumber|int|float|string $that) : int + /** + * {@inheritdoc} + */ + public function compareTo($that) : int { $that = BigNumber::of($that); @@ -868,31 +933,49 @@ public function compareTo(BigNumber|int|float|string $that) : int return - $that->compareTo($this); } + /** + * {@inheritdoc} + */ public function getSign() : int { return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1); } + /** + * {@inheritdoc} + */ public function toBigInteger() : BigInteger { return $this; } + /** + * {@inheritdoc} + */ public function toBigDecimal() : BigDecimal { - return self::newBigDecimal($this->value); + return BigDecimal::create($this->value); } + /** + * {@inheritdoc} + */ public function toBigRational() : BigRational { - return self::newBigRational($this, BigInteger::one(), false); + return BigRational::create($this, BigInteger::one(), false); } + /** + * {@inheritdoc} + */ public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal { return $this->toBigDecimal()->toScale($scale, $roundingMode); } + /** + * {@inheritdoc} + */ public function toInt() : int { $intValue = (int) $this->value; @@ -904,6 +987,9 @@ public function toInt() : int return $intValue; } + /** + * {@inheritdoc} + */ public function toFloat() : float { return (float) $this->value; @@ -914,6 +1000,10 @@ public function toFloat() : float * * The output will always be lowercase for bases greater than 10. * + * @param int $base + * + * @return string + * * @throws \InvalidArgumentException If the base is out of range. */ public function toBase(int $base) : string @@ -937,6 +1027,8 @@ public function toBase(int $base) : string * * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8. * + * @return string + * * @throws NegativeNumberException If this number is negative. * @throws \InvalidArgumentException If the given alphabet does not contain at least 2 chars. */ @@ -971,6 +1063,8 @@ public function toArbitraryBase(string $alphabet) : string * * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit. * + * @return string + * * @throws NegativeNumberException If $signed is false, and the number is negative. */ public function toBytes(bool $signed = true) : string @@ -1014,6 +1108,9 @@ public function toBytes(bool $signed = true) : string return \hex2bin($hex); } + /** + * {@inheritdoc} + */ public function __toString() : string { return $this->value; @@ -1039,6 +1136,8 @@ public function __serialize(): array * * @param array{value: string} $data * + * @return void + * * @throws \LogicException */ public function __unserialize(array $data): void @@ -1054,6 +1153,8 @@ public function __unserialize(array $data): void * This method is required by interface Serializable and SHOULD NOT be accessed directly. * * @internal + * + * @return string */ public function serialize() : string { @@ -1066,6 +1167,10 @@ public function serialize() : string * @internal * @psalm-suppress RedundantPropertyInitializationCheck * + * @param string $value + * + * @return void + * * @throws \LogicException */ public function unserialize($value) : void diff --git a/vendor/brick/math/src/BigNumber.php b/vendor/brick/math/src/BigNumber.php index 80146d207..38c8c554e 100644 --- a/vendor/brick/math/src/BigNumber.php +++ b/vendor/brick/math/src/BigNumber.php @@ -48,12 +48,16 @@ abstract class BigNumber implements \Serializable, \JsonSerializable * - strings containing a `.` character or using an exponential notation are returned as BigDecimal * - strings containing only digits with an optional leading `+` or `-` sign are returned as BigInteger * + * @param BigNumber|int|float|string $value + * + * @return BigNumber + * * @throws NumberFormatException If the format of the number is not valid. * @throws DivisionByZeroException If the value represents a rational number with a denominator of zero. * * @psalm-pure */ - public static function of(BigNumber|int|float|string $value) : BigNumber + public static function of($value) : BigNumber { if ($value instanceof BigNumber) { return $value; @@ -63,7 +67,8 @@ public static function of(BigNumber|int|float|string $value) : BigNumber return new BigInteger((string) $value); } - $value = \is_float($value) ? self::floatToString($value) : $value; + /** @psalm-suppress RedundantCastGivenDocblockType We cannot trust the untyped $value here! */ + $value = \is_float($value) ? self::floatToString($value) : (string) $value; $throw = static function() use ($value) : void { throw new NumberFormatException(\sprintf( @@ -76,7 +81,9 @@ public static function of(BigNumber|int|float|string $value) : BigNumber $throw(); } - $getMatch = static fn(string $value): ?string => (($matches[$value] ?? '') !== '') ? $matches[$value] : null; + $getMatch = static function(string $value) use ($matches) : ?string { + return isset($matches[$value]) && $matches[$value] !== '' ? $matches[$value] : null; + }; $sign = $getMatch('sign'); $numerator = $getMatch('numerator'); @@ -148,6 +155,10 @@ public static function of(BigNumber|int|float|string $value) : BigNumber * * @see https://github.com/brick/math/pull/20 * + * @param float $float + * + * @return string + * * @psalm-pure * @psalm-suppress ImpureFunctionCall */ @@ -164,36 +175,21 @@ private static function floatToString(float $float) : string } /** - * Proxy method to access BigInteger's protected constructor from sibling classes. + * Proxy method to access protected constructors from sibling classes. * * @internal - * @psalm-pure - */ - protected function newBigInteger(string $value) : BigInteger - { - return new BigInteger($value); - } - - /** - * Proxy method to access BigDecimal's protected constructor from sibling classes. * - * @internal - * @psalm-pure - */ - protected function newBigDecimal(string $value, int $scale = 0) : BigDecimal - { - return new BigDecimal($value, $scale); - } - - /** - * Proxy method to access BigRational's protected constructor from sibling classes. + * @param mixed ...$args The arguments to the constructor. + * + * @return static * - * @internal * @psalm-pure + * @psalm-suppress TooManyArguments + * @psalm-suppress UnsafeInstantiation */ - protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator) : BigRational + protected static function create(... $args) : BigNumber { - return new BigRational($numerator, $denominator, $checkDenominator); + return new static(... $args); } /** @@ -202,6 +198,8 @@ protected function newBigRational(BigInteger $numerator, BigInteger $denominator * @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers need to be convertible * to an instance of the class this method is called on. * + * @return static The minimum value. + * * @throws \InvalidArgumentException If no values are given. * @throws MathException If an argument is not valid. * @@ -209,7 +207,7 @@ protected function newBigRational(BigInteger $numerator, BigInteger $denominator * @psalm-suppress MoreSpecificReturnType * @psalm-pure */ - public static function min(BigNumber|int|float|string ...$values) : static + public static function min(...$values) : BigNumber { $min = null; @@ -234,6 +232,8 @@ public static function min(BigNumber|int|float|string ...$values) : static * @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers need to be convertible * to an instance of the class this method is called on. * + * @return static The maximum value. + * * @throws \InvalidArgumentException If no values are given. * @throws MathException If an argument is not valid. * @@ -241,7 +241,7 @@ public static function min(BigNumber|int|float|string ...$values) : static * @psalm-suppress MoreSpecificReturnType * @psalm-pure */ - public static function max(BigNumber|int|float|string ...$values) : static + public static function max(...$values) : BigNumber { $max = null; @@ -266,14 +266,18 @@ public static function max(BigNumber|int|float|string ...$values) : static * @param BigNumber|int|float|string ...$values The numbers to add. All the numbers need to be convertible * to an instance of the class this method is called on. * + * @return static The sum. + * * @throws \InvalidArgumentException If no values are given. * @throws MathException If an argument is not valid. * + * @psalm-suppress LessSpecificReturnStatement + * @psalm-suppress MoreSpecificReturnType * @psalm-pure */ - public static function sum(BigNumber|int|float|string ...$values) : static + public static function sum(...$values) : BigNumber { - /** @var static|null $sum */ + /** @var BigNumber|null $sum */ $sum = null; foreach ($values as $value) { @@ -297,6 +301,11 @@ public static function sum(BigNumber|int|float|string ...$values) : static * depending on their ability to perform the operation. This will also require a version bump because we're * potentially breaking custom BigNumber implementations (if any...) * + * @param BigNumber $a + * @param BigNumber $b + * + * @return BigNumber + * * @psalm-pure */ private static function add(BigNumber $a, BigNumber $b) : BigNumber @@ -327,6 +336,8 @@ private static function add(BigNumber $a, BigNumber $b) : BigNumber * * @param string $number The number, validated as a non-empty string of digits with optional leading sign. * + * @return string + * * @psalm-pure */ private static function cleanUp(string $number) : string @@ -352,46 +363,68 @@ private static function cleanUp(string $number) : string /** * Checks if this number is equal to the given one. + * + * @param BigNumber|int|float|string $that + * + * @return bool */ - public function isEqualTo(BigNumber|int|float|string $that) : bool + public function isEqualTo($that) : bool { return $this->compareTo($that) === 0; } /** * Checks if this number is strictly lower than the given one. + * + * @param BigNumber|int|float|string $that + * + * @return bool */ - public function isLessThan(BigNumber|int|float|string $that) : bool + public function isLessThan($that) : bool { return $this->compareTo($that) < 0; } /** * Checks if this number is lower than or equal to the given one. + * + * @param BigNumber|int|float|string $that + * + * @return bool */ - public function isLessThanOrEqualTo(BigNumber|int|float|string $that) : bool + public function isLessThanOrEqualTo($that) : bool { return $this->compareTo($that) <= 0; } /** * Checks if this number is strictly greater than the given one. + * + * @param BigNumber|int|float|string $that + * + * @return bool */ - public function isGreaterThan(BigNumber|int|float|string $that) : bool + public function isGreaterThan($that) : bool { return $this->compareTo($that) > 0; } /** * Checks if this number is greater than or equal to the given one. + * + * @param BigNumber|int|float|string $that + * + * @return bool */ - public function isGreaterThanOrEqualTo(BigNumber|int|float|string $that) : bool + public function isGreaterThanOrEqualTo($that) : bool { return $this->compareTo($that) >= 0; } /** * Checks if this number equals zero. + * + * @return bool */ public function isZero() : bool { @@ -400,6 +433,8 @@ public function isZero() : bool /** * Checks if this number is strictly negative. + * + * @return bool */ public function isNegative() : bool { @@ -408,6 +443,8 @@ public function isNegative() : bool /** * Checks if this number is negative or zero. + * + * @return bool */ public function isNegativeOrZero() : bool { @@ -416,6 +453,8 @@ public function isNegativeOrZero() : bool /** * Checks if this number is strictly positive. + * + * @return bool */ public function isPositive() : bool { @@ -424,6 +463,8 @@ public function isPositive() : bool /** * Checks if this number is positive or zero. + * + * @return bool */ public function isPositiveOrZero() : bool { @@ -440,15 +481,19 @@ abstract public function getSign() : int; /** * Compares this number to the given one. * + * @param BigNumber|int|float|string $that + * * @return int [-1,0,1] If `$this` is lower than, equal to, or greater than `$that`. * * @throws MathException If the number is not valid. */ - abstract public function compareTo(BigNumber|int|float|string $that) : int; + abstract public function compareTo($that) : int; /** * Converts this number to a BigInteger. * + * @return BigInteger The converted number. + * * @throws RoundingNecessaryException If this number cannot be converted to a BigInteger without rounding. */ abstract public function toBigInteger() : BigInteger; @@ -456,12 +501,16 @@ abstract public function toBigInteger() : BigInteger; /** * Converts this number to a BigDecimal. * + * @return BigDecimal The converted number. + * * @throws RoundingNecessaryException If this number cannot be converted to a BigDecimal without rounding. */ abstract public function toBigDecimal() : BigDecimal; /** * Converts this number to a BigRational. + * + * @return BigRational The converted number. */ abstract public function toBigRational() : BigRational; @@ -471,6 +520,8 @@ abstract public function toBigRational() : BigRational; * @param int $scale The scale of the resulting `BigDecimal`. * @param int $roundingMode A `RoundingMode` constant. * + * @return BigDecimal + * * @throws RoundingNecessaryException If this number cannot be converted to the given scale without rounding. * This only applies when RoundingMode::UNNECESSARY is used. */ @@ -482,6 +533,8 @@ abstract public function toScale(int $scale, int $roundingMode = RoundingMode::U * If this number cannot be converted to a native integer without losing precision, an exception is thrown. * Note that the acceptable range for an integer depends on the platform and differs for 32-bit and 64-bit. * + * @return int The converted value. + * * @throws MathException If this number cannot be exactly converted to a native integer. */ abstract public function toInt() : int; @@ -494,6 +547,8 @@ abstract public function toInt() : int; * * If the number is greater than the largest representable floating point number, positive infinity is returned. * If the number is less than the smallest representable floating point number, negative infinity is returned. + * + * @return float The converted value. */ abstract public function toFloat() : float; @@ -502,9 +557,14 @@ abstract public function toFloat() : float; * * The output of this method can be parsed by the `of()` factory method; * this will yield an object equal to this one, without any information loss. + * + * @return string */ abstract public function __toString() : string; + /** + * {@inheritdoc} + */ public function jsonSerialize() : string { return $this->__toString(); diff --git a/vendor/brick/math/src/BigRational.php b/vendor/brick/math/src/BigRational.php index 31f2904fa..bee094f73 100644 --- a/vendor/brick/math/src/BigRational.php +++ b/vendor/brick/math/src/BigRational.php @@ -20,13 +20,17 @@ final class BigRational extends BigNumber { /** * The numerator. + * + * @var BigInteger */ - private BigInteger $numerator; + private $numerator; /** * The denominator. Always strictly positive. + * + * @var BigInteger */ - private BigInteger $denominator; + private $denominator; /** * Protected constructor. Use a factory method to obtain an instance. @@ -57,11 +61,15 @@ protected function __construct(BigInteger $numerator, BigInteger $denominator, b /** * Creates a BigRational of the given value. * + * @param BigNumber|int|float|string $value + * + * @return BigRational + * * @throws MathException If the value cannot be converted to a BigRational. * * @psalm-pure */ - public static function of(BigNumber|int|float|string $value) : BigRational + public static function of($value) : BigNumber { return parent::of($value)->toBigRational(); } @@ -75,16 +83,16 @@ public static function of(BigNumber|int|float|string $value) : BigRational * @param BigNumber|int|float|string $numerator The numerator. Must be convertible to a BigInteger. * @param BigNumber|int|float|string $denominator The denominator. Must be convertible to a BigInteger. * + * @return BigRational + * * @throws NumberFormatException If an argument does not represent a valid number. * @throws RoundingNecessaryException If an argument represents a non-integer number. * @throws DivisionByZeroException If the denominator is zero. * * @psalm-pure */ - public static function nd( - BigNumber|int|float|string $numerator, - BigNumber|int|float|string $denominator, - ) : BigRational { + public static function nd($numerator, $denominator) : BigRational + { $numerator = BigInteger::of($numerator); $denominator = BigInteger::of($denominator); @@ -94,6 +102,8 @@ public static function nd( /** * Returns a BigRational representing zero. * + * @return BigRational + * * @psalm-pure */ public static function zero() : BigRational @@ -114,6 +124,8 @@ public static function zero() : BigRational /** * Returns a BigRational representing one. * + * @return BigRational + * * @psalm-pure */ public static function one() : BigRational @@ -134,6 +146,8 @@ public static function one() : BigRational /** * Returns a BigRational representing ten. * + * @return BigRational + * * @psalm-pure */ public static function ten() : BigRational @@ -151,11 +165,17 @@ public static function ten() : BigRational return $ten; } + /** + * @return BigInteger + */ public function getNumerator() : BigInteger { return $this->numerator; } + /** + * @return BigInteger + */ public function getDenominator() : BigInteger { return $this->denominator; @@ -163,6 +183,8 @@ public function getDenominator() : BigInteger /** * Returns the quotient of the division of the numerator by the denominator. + * + * @return BigInteger */ public function quotient() : BigInteger { @@ -171,6 +193,8 @@ public function quotient() : BigInteger /** * Returns the remainder of the division of the numerator by the denominator. + * + * @return BigInteger */ public function remainder() : BigInteger { @@ -192,9 +216,11 @@ public function quotientAndRemainder() : array * * @param BigNumber|int|float|string $that The number to add. * + * @return BigRational The result. + * * @throws MathException If the number is not valid. */ - public function plus(BigNumber|int|float|string $that) : BigRational + public function plus($that) : BigRational { $that = BigRational::of($that); @@ -210,9 +236,11 @@ public function plus(BigNumber|int|float|string $that) : BigRational * * @param BigNumber|int|float|string $that The number to subtract. * + * @return BigRational The result. + * * @throws MathException If the number is not valid. */ - public function minus(BigNumber|int|float|string $that) : BigRational + public function minus($that) : BigRational { $that = BigRational::of($that); @@ -228,9 +256,11 @@ public function minus(BigNumber|int|float|string $that) : BigRational * * @param BigNumber|int|float|string $that The multiplier. * + * @return BigRational The result. + * * @throws MathException If the multiplier is not a valid number. */ - public function multipliedBy(BigNumber|int|float|string $that) : BigRational + public function multipliedBy($that) : BigRational { $that = BigRational::of($that); @@ -245,9 +275,11 @@ public function multipliedBy(BigNumber|int|float|string $that) : BigRational * * @param BigNumber|int|float|string $that The divisor. * + * @return BigRational The result. + * * @throws MathException If the divisor is not a valid number, or is zero. */ - public function dividedBy(BigNumber|int|float|string $that) : BigRational + public function dividedBy($that) : BigRational { $that = BigRational::of($that); @@ -260,6 +292,10 @@ public function dividedBy(BigNumber|int|float|string $that) : BigRational /** * Returns this number exponentiated to the given value. * + * @param int $exponent The exponent. + * + * @return BigRational The result. + * * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000. */ public function power(int $exponent) : BigRational @@ -286,6 +322,8 @@ public function power(int $exponent) : BigRational * * The reciprocal has the numerator and denominator swapped. * + * @return BigRational + * * @throws DivisionByZeroException If the numerator is zero. */ public function reciprocal() : BigRational @@ -295,6 +333,8 @@ public function reciprocal() : BigRational /** * Returns the absolute value of this BigRational. + * + * @return BigRational */ public function abs() : BigRational { @@ -303,6 +343,8 @@ public function abs() : BigRational /** * Returns the negated value of this BigRational. + * + * @return BigRational */ public function negated() : BigRational { @@ -311,6 +353,8 @@ public function negated() : BigRational /** * Returns the simplified value of this BigRational. + * + * @return BigRational */ public function simplified() : BigRational { @@ -322,16 +366,25 @@ public function simplified() : BigRational return new BigRational($numerator, $denominator, false); } - public function compareTo(BigNumber|int|float|string $that) : int + /** + * {@inheritdoc} + */ + public function compareTo($that) : int { return $this->minus($that)->getSign(); } + /** + * {@inheritdoc} + */ public function getSign() : int { return $this->numerator->getSign(); } + /** + * {@inheritdoc} + */ public function toBigInteger() : BigInteger { $simplified = $this->simplified(); @@ -343,32 +396,49 @@ public function toBigInteger() : BigInteger return $simplified->numerator; } + /** + * {@inheritdoc} + */ public function toBigDecimal() : BigDecimal { return $this->numerator->toBigDecimal()->exactlyDividedBy($this->denominator); } + /** + * {@inheritdoc} + */ public function toBigRational() : BigRational { return $this; } + /** + * {@inheritdoc} + */ public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal { return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode); } + /** + * {@inheritdoc} + */ public function toInt() : int { return $this->toBigInteger()->toInt(); } + /** + * {@inheritdoc} + */ public function toFloat() : float { - $simplified = $this->simplified(); - return $simplified->numerator->toFloat() / $simplified->denominator->toFloat(); + return $this->numerator->toFloat() / $this->denominator->toFloat(); } + /** + * {@inheritdoc} + */ public function __toString() : string { $numerator = (string) $this->numerator; @@ -401,6 +471,8 @@ public function __serialize(): array * * @param array{numerator: BigInteger, denominator: BigInteger} $data * + * @return void + * * @throws \LogicException */ public function __unserialize(array $data): void @@ -417,6 +489,8 @@ public function __unserialize(array $data): void * This method is required by interface Serializable and SHOULD NOT be accessed directly. * * @internal + * + * @return string */ public function serialize() : string { @@ -429,6 +503,10 @@ public function serialize() : string * @internal * @psalm-suppress RedundantPropertyInitializationCheck * + * @param string $value + * + * @return void + * * @throws \LogicException */ public function unserialize($value) : void diff --git a/vendor/brick/math/src/Exception/DivisionByZeroException.php b/vendor/brick/math/src/Exception/DivisionByZeroException.php index ce7769ac2..a4e443176 100644 --- a/vendor/brick/math/src/Exception/DivisionByZeroException.php +++ b/vendor/brick/math/src/Exception/DivisionByZeroException.php @@ -10,6 +10,8 @@ class DivisionByZeroException extends MathException { /** + * @return DivisionByZeroException + * * @psalm-pure */ public static function divisionByZero() : DivisionByZeroException @@ -18,6 +20,8 @@ public static function divisionByZero() : DivisionByZeroException } /** + * @return DivisionByZeroException + * * @psalm-pure */ public static function modulusMustNotBeZero() : DivisionByZeroException @@ -26,6 +30,8 @@ public static function modulusMustNotBeZero() : DivisionByZeroException } /** + * @return DivisionByZeroException + * * @psalm-pure */ public static function denominatorMustNotBeZero() : DivisionByZeroException diff --git a/vendor/brick/math/src/Exception/IntegerOverflowException.php b/vendor/brick/math/src/Exception/IntegerOverflowException.php index c73b49097..e0b07d3c7 100644 --- a/vendor/brick/math/src/Exception/IntegerOverflowException.php +++ b/vendor/brick/math/src/Exception/IntegerOverflowException.php @@ -12,6 +12,10 @@ class IntegerOverflowException extends MathException { /** + * @param BigInteger $value + * + * @return IntegerOverflowException + * * @psalm-pure */ public static function toIntOverflow(BigInteger $value) : IntegerOverflowException diff --git a/vendor/brick/math/src/Exception/MathException.php b/vendor/brick/math/src/Exception/MathException.php index 46e9c3fe4..21fda90e1 100644 --- a/vendor/brick/math/src/Exception/MathException.php +++ b/vendor/brick/math/src/Exception/MathException.php @@ -6,7 +6,9 @@ /** * Base class for all math exceptions. + * + * This class is abstract to ensure that only fine-grained exceptions are thrown throughout the code. */ -class MathException extends \Exception +class MathException extends \RuntimeException { } diff --git a/vendor/brick/math/src/Exception/NumberFormatException.php b/vendor/brick/math/src/Exception/NumberFormatException.php index d9cf6ff5f..2fd0be73a 100644 --- a/vendor/brick/math/src/Exception/NumberFormatException.php +++ b/vendor/brick/math/src/Exception/NumberFormatException.php @@ -12,6 +12,8 @@ class NumberFormatException extends MathException /** * @param string $char The failing character. * + * @return NumberFormatException + * * @psalm-pure */ public static function charNotInAlphabet(string $char) : self diff --git a/vendor/brick/math/src/Exception/RoundingNecessaryException.php b/vendor/brick/math/src/Exception/RoundingNecessaryException.php index 57bfcd844..1c6100563 100644 --- a/vendor/brick/math/src/Exception/RoundingNecessaryException.php +++ b/vendor/brick/math/src/Exception/RoundingNecessaryException.php @@ -10,6 +10,8 @@ class RoundingNecessaryException extends MathException { /** + * @return RoundingNecessaryException + * * @psalm-pure */ public static function roundingNecessary() : RoundingNecessaryException diff --git a/vendor/brick/math/src/Internal/Calculator.php b/vendor/brick/math/src/Internal/Calculator.php index b8cecda96..a6eac799f 100644 --- a/vendor/brick/math/src/Internal/Calculator.php +++ b/vendor/brick/math/src/Internal/Calculator.php @@ -34,8 +34,10 @@ abstract class Calculator /** * The Calculator instance in use. + * + * @var Calculator|null */ - private static ?Calculator $instance = null; + private static $instance; /** * Sets the Calculator instance to use. @@ -43,6 +45,8 @@ abstract class Calculator * An instance is typically set only in unit tests: the autodetect is usually the best option. * * @param Calculator|null $calculator The calculator instance, or NULL to revert to autodetect. + * + * @return void */ final public static function set(?Calculator $calculator) : void { @@ -54,6 +58,8 @@ final public static function set(?Calculator $calculator) : void * * If none has been explicitly set, the fastest available implementation will be returned. * + * @return Calculator + * * @psalm-pure * @psalm-suppress ImpureStaticProperty */ @@ -71,6 +77,8 @@ final public static function get() : Calculator * Returns the fastest available Calculator implementation. * * @codeCoverageIgnore + * + * @return Calculator */ private static function detect() : Calculator { @@ -88,6 +96,9 @@ private static function detect() : Calculator /** * Extracts the sign & digits of the operands. * + * @param string $a The first operand. + * @param string $b The second operand. + * * @return array{bool, bool, string, string} Whether $a and $b are negative, followed by their digits. */ final protected function init(string $a, string $b) : array @@ -103,6 +114,10 @@ final protected function init(string $a, string $b) : array /** * Returns the absolute value of a number. + * + * @param string $n The number. + * + * @return string The absolute value. */ final public function abs(string $n) : string { @@ -111,6 +126,10 @@ final public function abs(string $n) : string /** * Negates a number. + * + * @param string $n The number. + * + * @return string The negated value. */ final public function neg(string $n) : string { @@ -128,6 +147,9 @@ final public function neg(string $n) : string /** * Compares two numbers. * + * @param string $a The first number. + * @param string $b The second number. + * * @return int [-1, 0, 1] If the first number is less than, equal to, or greater than the second number. */ final public function cmp(string $a, string $b) : int @@ -158,16 +180,31 @@ final public function cmp(string $a, string $b) : int /** * Adds two numbers. + * + * @param string $a The augend. + * @param string $b The addend. + * + * @return string The sum. */ abstract public function add(string $a, string $b) : string; /** * Subtracts two numbers. + * + * @param string $a The minuend. + * @param string $b The subtrahend. + * + * @return string The difference. */ abstract public function sub(string $a, string $b) : string; /** * Multiplies two numbers. + * + * @param string $a The multiplicand. + * @param string $b The multiplier. + * + * @return string The product. */ abstract public function mul(string $a, string $b) : string; @@ -197,7 +234,7 @@ abstract public function divR(string $a, string $b) : string; * @param string $a The dividend. * @param string $b The divisor, must not be zero. * - * @return array{string, string} An array containing the quotient and remainder. + * @return string[] An array containing the quotient and remainder. */ abstract public function divQR(string $a, string $b) : array; @@ -212,7 +249,10 @@ abstract public function divQR(string $a, string $b) : array; abstract public function pow(string $a, int $e) : string; /** + * @param string $a * @param string $b The modulus; must not be zero. + * + * @return string */ public function mod(string $a, string $b) : string { @@ -226,7 +266,10 @@ public function mod(string $a, string $b) : string * * This method can be overridden by the concrete implementation if the underlying library has built-in support. * + * @param string $x * @param string $m The modulus; must not be negative or zero. + * + * @return string|null */ public function modInverse(string $x, string $m) : ?string { @@ -240,7 +283,9 @@ public function modInverse(string $x, string $m) : ?string $modVal = $this->mod($x, $m); } - [$g, $x] = $this->gcdExtended($modVal, $m); + $x = '0'; + $y = '0'; + $g = $this->gcdExtended($modVal, $m, $x, $y); if ($g !== '1') { return null; @@ -255,6 +300,8 @@ public function modInverse(string $x, string $m) : ?string * @param string $base The base number; must be positive or zero. * @param string $exp The exponent; must be positive or zero. * @param string $mod The modulus; must be strictly positive. + * + * @return string The power. */ abstract public function modPow(string $base, string $exp, string $mod) : string; @@ -264,6 +311,9 @@ abstract public function modPow(string $base, string $exp, string $mod) : string * This method can be overridden by the concrete implementation if the underlying library * has built-in support for GCD calculations. * + * @param string $a The first number. + * @param string $b The second number. + * * @return string The GCD, always positive, or zero if both arguments are zero. */ public function gcd(string $a, string $b) : string @@ -279,21 +329,24 @@ public function gcd(string $a, string $b) : string return $this->gcd($b, $this->divR($a, $b)); } - /** - * @return array{string, string, string} GCD, X, Y - */ - private function gcdExtended(string $a, string $b) : array + private function gcdExtended(string $a, string $b, string &$x, string &$y) : string { if ($a === '0') { - return [$b, '0', '1']; + $x = '0'; + $y = '1'; + + return $b; } - [$gcd, $x1, $y1] = $this->gcdExtended($this->mod($b, $a), $a); + $x1 = '0'; + $y1 = '0'; + + $gcd = $this->gcdExtended($this->mod($b, $a), $a, $x1, $y1); $x = $this->sub($y1, $this->mul($this->divQ($b, $a), $x1)); $y = $x1; - return [$gcd, $x, $y]; + return $gcd; } /** @@ -301,6 +354,10 @@ private function gcdExtended(string $a, string $b) : array * * The result is the largest x such that x² ≤ n. * The input MUST NOT be negative. + * + * @param string $n The number. + * + * @return string The square root. */ abstract public function sqrt(string $n) : string; @@ -432,10 +489,10 @@ final public function toArbitraryBase(string $number, string $alphabet, int $bas * @param string $b The divisor, must not be zero. * @param int $roundingMode The rounding mode. * + * @return string + * * @throws \InvalidArgumentException If the rounding mode is invalid. * @throws RoundingNecessaryException If RoundingMode::UNNECESSARY is provided but rounding is necessary. - * - * @psalm-suppress ImpureFunctionCall */ final public function divRound(string $a, string $b, int $roundingMode) : string { @@ -513,6 +570,11 @@ final public function divRound(string $a, string $b, int $roundingMode) : string * * This method can be overridden by the concrete implementation if the underlying library * has built-in support for bitwise operations. + * + * @param string $a + * @param string $b + * + * @return string */ public function and(string $a, string $b) : string { @@ -524,6 +586,11 @@ public function and(string $a, string $b) : string * * This method can be overridden by the concrete implementation if the underlying library * has built-in support for bitwise operations. + * + * @param string $a + * @param string $b + * + * @return string */ public function or(string $a, string $b) : string { @@ -535,6 +602,11 @@ public function or(string $a, string $b) : string * * This method can be overridden by the concrete implementation if the underlying library * has built-in support for bitwise operations. + * + * @param string $a + * @param string $b + * + * @return string */ public function xor(string $a, string $b) : string { @@ -544,9 +616,11 @@ public function xor(string $a, string $b) : string /** * Performs a bitwise operation on a decimal number. * - * @param 'and'|'or'|'xor' $operator The operator to use. - * @param string $a The left operand. - * @param string $b The right operand. + * @param string $operator The operator to use, must be "and", "or" or "xor". + * @param string $a The left operand. + * @param string $b The right operand. + * + * @return string */ private function bitwise(string $operator, string $a, string $b) : string { @@ -604,6 +678,8 @@ private function bitwise(string $operator, string $a, string $b) : string /** * @param string $number A positive, binary number. + * + * @return string */ private function twosComplement(string $number) : string { @@ -633,6 +709,8 @@ private function twosComplement(string $number) : string * Converts a decimal number to a binary string. * * @param string $number The number to convert, positive or zero, only digits. + * + * @return string */ private function toBinary(string $number) : string { @@ -650,6 +728,8 @@ private function toBinary(string $number) : string * Returns the positive decimal representation of a binary number. * * @param string $bytes The bytes representing the number. + * + * @return string */ private function toDecimal(string $bytes) : string { diff --git a/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php b/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php index 5457a3c98..6632b378a 100644 --- a/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php +++ b/vendor/brick/math/src/Internal/Calculator/BcMathCalculator.php @@ -15,58 +15,99 @@ */ class BcMathCalculator extends Calculator { + /** + * {@inheritdoc} + */ public function add(string $a, string $b) : string { return \bcadd($a, $b, 0); } + /** + * {@inheritdoc} + */ public function sub(string $a, string $b) : string { return \bcsub($a, $b, 0); } + /** + * {@inheritdoc} + */ public function mul(string $a, string $b) : string { return \bcmul($a, $b, 0); } + /** + * {@inheritdoc} + * + * @psalm-suppress InvalidNullableReturnType + * @psalm-suppress NullableReturnStatement + */ public function divQ(string $a, string $b) : string { return \bcdiv($a, $b, 0); } /** + * {@inheritdoc} + * * @psalm-suppress InvalidNullableReturnType * @psalm-suppress NullableReturnStatement */ public function divR(string $a, string $b) : string { - return \bcmod($a, $b, 0); + if (version_compare(PHP_VERSION, '7.2') >= 0) { + return \bcmod($a, $b, 0); + } + + return \bcmod($a, $b); } + /** + * {@inheritdoc} + */ public function divQR(string $a, string $b) : array { $q = \bcdiv($a, $b, 0); - $r = \bcmod($a, $b, 0); + if (version_compare(PHP_VERSION, '7.2') >= 0) { + $r = \bcmod($a, $b, 0); + } else { + $r = \bcmod($a, $b); + } + + assert($q !== null); assert($r !== null); return [$q, $r]; } + /** + * {@inheritdoc} + */ public function pow(string $a, int $e) : string { return \bcpow($a, (string) $e, 0); } + /** + * {@inheritdoc} + * + * @psalm-suppress InvalidNullableReturnType + * @psalm-suppress NullableReturnStatement + */ public function modPow(string $base, string $exp, string $mod) : string { return \bcpowmod($base, $exp, $mod, 0); } /** - * @psalm-suppress InvalidNullableReturnType + * {@inheritDoc} + * * @psalm-suppress NullableReturnStatement + * @psalm-suppress InvalidNullableReturnType */ public function sqrt(string $n) : string { diff --git a/vendor/brick/math/src/Internal/Calculator/GmpCalculator.php b/vendor/brick/math/src/Internal/Calculator/GmpCalculator.php index 42d4c6927..52d18800a 100644 --- a/vendor/brick/math/src/Internal/Calculator/GmpCalculator.php +++ b/vendor/brick/math/src/Internal/Calculator/GmpCalculator.php @@ -15,31 +15,49 @@ */ class GmpCalculator extends Calculator { + /** + * {@inheritdoc} + */ public function add(string $a, string $b) : string { return \gmp_strval(\gmp_add($a, $b)); } + /** + * {@inheritdoc} + */ public function sub(string $a, string $b) : string { return \gmp_strval(\gmp_sub($a, $b)); } + /** + * {@inheritdoc} + */ public function mul(string $a, string $b) : string { return \gmp_strval(\gmp_mul($a, $b)); } + /** + * {@inheritdoc} + */ public function divQ(string $a, string $b) : string { return \gmp_strval(\gmp_div_q($a, $b)); } + /** + * {@inheritdoc} + */ public function divR(string $a, string $b) : string { return \gmp_strval(\gmp_div_r($a, $b)); } + /** + * {@inheritdoc} + */ public function divQR(string $a, string $b) : array { [$q, $r] = \gmp_div_qr($a, $b); @@ -50,11 +68,17 @@ public function divQR(string $a, string $b) : array ]; } + /** + * {@inheritdoc} + */ public function pow(string $a, int $e) : string { return \gmp_strval(\gmp_pow($a, $e)); } + /** + * {@inheritdoc} + */ public function modInverse(string $x, string $m) : ?string { $result = \gmp_invert($x, $m); @@ -66,41 +90,65 @@ public function modInverse(string $x, string $m) : ?string return \gmp_strval($result); } + /** + * {@inheritdoc} + */ public function modPow(string $base, string $exp, string $mod) : string { return \gmp_strval(\gmp_powm($base, $exp, $mod)); } + /** + * {@inheritdoc} + */ public function gcd(string $a, string $b) : string { return \gmp_strval(\gmp_gcd($a, $b)); } + /** + * {@inheritdoc} + */ public function fromBase(string $number, int $base) : string { return \gmp_strval(\gmp_init($number, $base)); } + /** + * {@inheritdoc} + */ public function toBase(string $number, int $base) : string { return \gmp_strval($number, $base); } + /** + * {@inheritdoc} + */ public function and(string $a, string $b) : string { return \gmp_strval(\gmp_and($a, $b)); } + /** + * {@inheritdoc} + */ public function or(string $a, string $b) : string { return \gmp_strval(\gmp_or($a, $b)); } + /** + * {@inheritdoc} + */ public function xor(string $a, string $b) : string { return \gmp_strval(\gmp_xor($a, $b)); } + /** + * {@inheritDoc} + */ public function sqrt(string $n) : string { return \gmp_strval(\gmp_sqrt($n)); diff --git a/vendor/brick/math/src/Internal/Calculator/NativeCalculator.php b/vendor/brick/math/src/Internal/Calculator/NativeCalculator.php index 7c679d24d..020a6338b 100644 --- a/vendor/brick/math/src/Internal/Calculator/NativeCalculator.php +++ b/vendor/brick/math/src/Internal/Calculator/NativeCalculator.php @@ -19,13 +19,17 @@ class NativeCalculator extends Calculator * The max number of digits the platform can natively add, subtract, multiply or divide without overflow. * For multiplication, this represents the max sum of the lengths of both operands. * - * In addition, it is assumed that an extra digit can hold a carry (1) without overflowing. + * For addition, it is assumed that an extra digit can hold a carry (1) without overflowing. * Example: 32-bit: max number 1,999,999,999 (9 digits + carry) * 64-bit: max number 1,999,999,999,999,999,999 (18 digits + carry) + * + * @var int */ - private int $maxDigits; + private $maxDigits; /** + * Class constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -44,6 +48,9 @@ public function __construct() } } + /** + * {@inheritdoc} + */ public function add(string $a, string $b) : string { /** @@ -75,11 +82,17 @@ public function add(string $a, string $b) : string return $result; } + /** + * {@inheritdoc} + */ public function sub(string $a, string $b) : string { return $this->add($a, $this->neg($b)); } + /** + * {@inheritdoc} + */ public function mul(string $a, string $b) : string { /** @@ -123,16 +136,25 @@ public function mul(string $a, string $b) : string return $result; } + /** + * {@inheritdoc} + */ public function divQ(string $a, string $b) : string { return $this->divQR($a, $b)[0]; } + /** + * {@inheritdoc} + */ public function divR(string $a, string $b): string { return $this->divQR($a, $b)[1]; } + /** + * {@inheritdoc} + */ public function divQR(string $a, string $b) : array { if ($a === '0') { @@ -188,6 +210,9 @@ public function divQR(string $a, string $b) : array return [$q, $r]; } + /** + * {@inheritdoc} + */ public function pow(string $a, int $e) : string { if ($e === 0) { @@ -215,6 +240,8 @@ public function pow(string $a, int $e) : string /** * Algorithm from: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/ + * + * {@inheritdoc} */ public function modPow(string $base, string $exp, string $mod) : string { @@ -249,6 +276,8 @@ public function modPow(string $base, string $exp, string $mod) : string /** * Adapted from https://cp-algorithms.com/num_methods/roots_newton.html + * + * {@inheritDoc} */ public function sqrt(string $n) : string { @@ -277,6 +306,11 @@ public function sqrt(string $n) : string /** * Performs the addition of two non-signed large integers. + * + * @param string $a The first operand. + * @param string $b The second operand. + * + * @return string */ private function doAdd(string $a, string $b) : string { @@ -329,6 +363,11 @@ private function doAdd(string $a, string $b) : string /** * Performs the subtraction of two non-signed large integers. + * + * @param string $a The first operand. + * @param string $b The second operand. + * + * @return string */ private function doSub(string $a, string $b) : string { @@ -406,6 +445,11 @@ private function doSub(string $a, string $b) : string /** * Performs the multiplication of two non-signed large integers. + * + * @param string $a The first operand. + * @param string $b The second operand. + * + * @return string */ private function doMul(string $a, string $b) : string { @@ -478,6 +522,9 @@ private function doMul(string $a, string $b) : string /** * Performs the division of two non-signed large integers. * + * @param string $a The first operand. + * @param string $b The second operand. + * * @return string[] The quotient and remainder. */ private function doDiv(string $a, string $b) : array @@ -536,6 +583,9 @@ private function doDiv(string $a, string $b) : array /** * Compares two non-signed large numbers. * + * @param string $a The first operand. + * @param string $b The second operand. + * * @return int [-1, 0, 1] */ private function doCmp(string $a, string $b) : int @@ -557,6 +607,9 @@ private function doCmp(string $a, string $b) : int * * The numbers must only consist of digits, without leading minus sign. * + * @param string $a The first operand. + * @param string $b The second operand. + * * @return array{string, string, int} */ private function pad(string $a, string $b) : array diff --git a/vendor/buckaroo/sdk/src/Transaction/Client.php b/vendor/buckaroo/sdk/src/Transaction/Client.php index 65c761e2c..355b28e4e 100644 --- a/vendor/buckaroo/sdk/src/Transaction/Client.php +++ b/vendor/buckaroo/sdk/src/Transaction/Client.php @@ -32,7 +32,6 @@ use Buckaroo\Services\TransactionHeaders\HmacHeader; use Buckaroo\Services\TransactionHeaders\SoftwareHeader; use Buckaroo\Transaction\Request\HttpClient\HttpClientFactory; -use Buckaroo\Transaction\Request\HttpClient\HttpClientGuzzle; use Buckaroo\Transaction\Request\HttpClient\HttpClientInterface; use Buckaroo\Transaction\Request\Request; use Buckaroo\Transaction\Response\Response; @@ -44,7 +43,7 @@ class Client private const METHOD_POST = 'POST'; /** - * @var HttpClientInterface|HttpClientGuzzle + * @var HttpClientInterface */ protected HttpClientInterface $httpClient; /** diff --git a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV5.php b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV5.php index e56f022f4..acb11dc5e 100644 --- a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV5.php +++ b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV5.php @@ -5,8 +5,9 @@ use Buckaroo\Exceptions\BuckarooException; use Buckaroo\Exceptions\TransferException; use Buckaroo\Handlers\Logging\Subject; -use GuzzleHttp\Client as GuzzleClientV5; +use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\RequestException; class GuzzleHttpClientV5 extends HttpClientAbstract @@ -22,7 +23,7 @@ public function __construct(Subject $logger) parent::__construct($logger); $this->logger = $logger; - $this->httpClient = new GuzzleClientV5([ + $this->httpClient = new Client([ 'timeout' => self::TIMEOUT, 'connect_timeout' => self::CONNECT_TIMEOUT, ]); @@ -35,8 +36,7 @@ public function __construct(Subject $logger) * @param string|null $data * @return array|mixed * @throws TransferException - * @throws BuckarooException - * @throws BuckarooException + * @throws BuckarooException|GuzzleException */ public function call(string $url, array $headers, string $method, string $data = null) diff --git a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV7.php b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV7.php index c1ca02754..015b4e09a 100644 --- a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV7.php +++ b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/GuzzleHttpClientV7.php @@ -2,6 +2,7 @@ namespace Buckaroo\Transaction\Request\HttpClient; +use Buckaroo\Exceptions\BuckarooException; use Buckaroo\Exceptions\TransferException; use Buckaroo\Handlers\Logging\Subject; use GuzzleHttp\Client; @@ -41,7 +42,7 @@ public function __construct(Subject $logger) * @param string|null $data * @return array|mixed * @throws TransferException - * @throws \Buckaroo\Exceptions\BuckarooException + * @throws BuckarooException */ public function call(string $url, array $headers, string $method, string $data = null) { @@ -57,8 +58,7 @@ public function call(string $url, array $headers, string $method, string $data = $this->logger->info('RESPONSE HEADERS: ' . json_encode($response->getHeaders())); $this->logger->info('RESPONSE BODY: ' . $response->getBody()); - } catch (GuzzleException $e) - { + } catch (GuzzleException $e) { throw new TransferException($this->logger, "Transfer failed", 0, $e); } diff --git a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientFactory.php b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientFactory.php index 88cd7fc68..1c7a12208 100644 --- a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientFactory.php +++ b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientFactory.php @@ -14,6 +14,7 @@ public static function createClient(Subject $logger) // Extract the major version number $majorVersion = (int) explode('.', $versionString)[0]; + // Instantiate the appropriate client based on the major version if ($majorVersion === 5) { return new GuzzleHttpClientV5($logger); } diff --git a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientGuzzle.php b/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientGuzzle.php deleted file mode 100644 index d15a2fd74..000000000 --- a/vendor/buckaroo/sdk/src/Transaction/Request/HttpClient/HttpClientGuzzle.php +++ /dev/null @@ -1,92 +0,0 @@ -logger = $logger; - - $this->httpClient = new Client([ - RequestOptions::TIMEOUT => self::TIMEOUT, - RequestOptions::CONNECT_TIMEOUT => self::CONNECT_TIMEOUT, - ]); - } - - /** - * @param string $url - * @param array $headers - * @param string $method - * @param string|null $data - * @return array|mixed - * @throws TransferException - * @throws \Buckaroo\Exceptions\BuckarooException - */ - public function call(string $url, array $headers, string $method, string $data = null) - { - $headers = $this->convertHeadersFormat($headers); - - $request = new Request($method, $url, $headers, $data); - - try - { - $response = $this->httpClient->send($request, ['http_errors' => false]); - - $result = (string) $response->getBody(); - - $this->logger->info('RESPONSE HEADERS: ' . json_encode($response->getHeaders())); - $this->logger->info('RESPONSE BODY: ' . $response->getBody()); - } catch (GuzzleException $e) - { - throw new TransferException($this->logger, "Transfer failed", 0, $e); - } - - $result = $this->getDecodedResult($response, $result); - - return [ - $response, - $result, - ]; - } -} diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php index fd56bd7d8..a72151c77 100644 --- a/vendor/composer/ClassLoader.php +++ b/vendor/composer/ClassLoader.php @@ -429,7 +429,8 @@ public function unregister() public function loadClass($class) { if ($file = $this->findFile($class)) { - (self::$includeFile)($file); + $includeFile = self::$includeFile; + $includeFile($file); return true; } @@ -560,7 +561,10 @@ private function findFileWithExtension($class, $ext) return false; } - private static function initializeIncludeClosure(): void + /** + * @return void + */ + private static function initializeIncludeClosure() { if (self::$includeFile !== null) { return; @@ -574,8 +578,8 @@ private static function initializeIncludeClosure(): void * @param string $file * @return void */ - self::$includeFile = static function($file) { + self::$includeFile = \Closure::bind(static function($file) { include $file; - }; + }, null, null); } } diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php index c6b54af7b..51e734a77 100644 --- a/vendor/composer/InstalledVersions.php +++ b/vendor/composer/InstalledVersions.php @@ -98,7 +98,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true) { foreach (self::getInstalled() as $installed) { if (isset($installed['versions'][$packageName])) { - return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; } } @@ -119,7 +119,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true) */ public static function satisfies(VersionParser $parser, $packageName, $constraint) { - $constraint = $parser->parseConstraints($constraint); + $constraint = $parser->parseConstraints((string) $constraint); $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); return $provided->matches($constraint); @@ -328,7 +328,9 @@ private static function getInstalled() if (isset(self::$installedByVendor[$vendorDir])) { $installed[] = self::$installedByVendor[$vendorDir]; } elseif (is_file($vendorDir.'/composer/installed.php')) { - $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + $installed[] = self::$installedByVendor[$vendorDir] = $required; if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { self::$installed = $installed[count($installed) - 1]; } @@ -340,12 +342,17 @@ private static function getInstalled() // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { - self::$installed = require __DIR__ . '/installed.php'; + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; } else { self::$installed = array(); } } - $installed[] = self::$installed; + + if (self::$installed !== array()) { + $installed[] = self::$installed; + } return $installed; } diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index 0fb0a2c19..3885b22a6 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -6,5 +6,12 @@ $baseDir = dirname($vendorDir); return array( + 'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'CURLStringFile' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReturnTypeWillChange' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', ); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php index e0dff4efe..19477328a 100644 --- a/vendor/composer/autoload_files.php +++ b/vendor/composer/autoload_files.php @@ -7,7 +7,10 @@ return array( '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + '23c18046f52bef3eea034657bafda50f' => $vendorDir . '/symfony/polyfill-php81/bootstrap.php', '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', 'e39a8b23c42d4e1452234d762b03835a' => $vendorDir . '/ramsey/uuid/src/functions.php', ); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index a3d2df7e1..566f54e1b 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -6,10 +6,13 @@ $baseDir = dirname($vendorDir); return array( + 'Symfony\\Polyfill\\Php81\\' => array($vendorDir . '/symfony/polyfill-php81'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), 'Ramsey\\Uuid\\' => array($vendorDir . '/ramsey/uuid/src'), 'Ramsey\\Collection\\' => array($vendorDir . '/ramsey/collection/src'), - 'Psr\\Log\\' => array($vendorDir . '/psr/log/src'), - 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'), + 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'), 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), 'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'), 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 00553979a..7fe925e3e 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -2,7 +2,7 @@ // autoload_real.php @generated by Composer -class ComposerAutoloaderInit01edbf89a2a31910527aa0e7dc75324b +class ComposerAutoloaderInit8cc69a57001ff18655c419e4501e58cd { private static $loader; @@ -24,25 +24,25 @@ public static function getLoader() require __DIR__ . '/platform_check.php'; - spl_autoload_register(array('ComposerAutoloaderInit01edbf89a2a31910527aa0e7dc75324b', 'loadClassLoader'), true, false); + spl_autoload_register(array('ComposerAutoloaderInit8cc69a57001ff18655c419e4501e58cd', 'loadClassLoader'), true, false); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); - spl_autoload_unregister(array('ComposerAutoloaderInit01edbf89a2a31910527aa0e7dc75324b', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInit8cc69a57001ff18655c419e4501e58cd', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; - call_user_func(\Composer\Autoload\ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b::getInitializer($loader)); + call_user_func(\Composer\Autoload\ComposerStaticInit8cc69a57001ff18655c419e4501e58cd::getInitializer($loader)); $loader->register(false); - $filesToLoad = \Composer\Autoload\ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b::$files; - $requireFile = static function ($fileIdentifier, $file) { + $filesToLoad = \Composer\Autoload\ComposerStaticInit8cc69a57001ff18655c419e4501e58cd::$files; + $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } - }; + }, null, null); foreach ($filesToLoad as $fileIdentifier => $file) { - ($requireFile)($fileIdentifier, $file); + $requireFile($fileIdentifier, $file); } return $loader; diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 5c9caf619..776b8bd03 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -4,16 +4,25 @@ namespace Composer\Autoload; -class ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b +class ComposerStaticInit8cc69a57001ff18655c419e4501e58cd { public static $files = array ( '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + '23c18046f52bef3eea034657bafda50f' => __DIR__ . '/..' . '/symfony/polyfill-php81/bootstrap.php', '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', 'e39a8b23c42d4e1452234d762b03835a' => __DIR__ . '/..' . '/ramsey/uuid/src/functions.php', ); public static $prefixLengthsPsr4 = array ( + 'S' => + array ( + 'Symfony\\Polyfill\\Php81\\' => 23, + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Ctype\\' => 23, + ), 'R' => array ( 'Ramsey\\Uuid\\' => 12, @@ -51,6 +60,18 @@ class ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b ); public static $prefixDirsPsr4 = array ( + 'Symfony\\Polyfill\\Php81\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php81', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), 'Ramsey\\Uuid\\' => array ( 0 => __DIR__ . '/..' . '/ramsey/uuid/src', @@ -61,12 +82,12 @@ class ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b ), 'Psr\\Log\\' => array ( - 0 => __DIR__ . '/..' . '/psr/log/src', + 0 => __DIR__ . '/..' . '/psr/log/Psr/Log', ), 'Psr\\Http\\Message\\' => array ( - 0 => __DIR__ . '/..' . '/psr/http-factory/src', - 1 => __DIR__ . '/..' . '/psr/http-message/src', + 0 => __DIR__ . '/..' . '/psr/http-message/src', + 1 => __DIR__ . '/..' . '/psr/http-factory/src', ), 'Psr\\Http\\Client\\' => array ( @@ -119,15 +140,22 @@ class ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b ); public static $classMap = array ( + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'CURLStringFile' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/CURLStringFile.php', 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReturnTypeWillChange' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { - $loader->prefixLengthsPsr4 = ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b::$prefixLengthsPsr4; - $loader->prefixDirsPsr4 = ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b::$prefixDirsPsr4; - $loader->classMap = ComposerStaticInit01edbf89a2a31910527aa0e7dc75324b::$classMap; + $loader->prefixLengthsPsr4 = ComposerStaticInit8cc69a57001ff18655c419e4501e58cd::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit8cc69a57001ff18655c419e4501e58cd::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit8cc69a57001ff18655c419e4501e58cd::$classMap; }, null, ClassLoader::class); } diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index bef90f368..63ecaae3c 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -2,28 +2,29 @@ "packages": [ { "name": "brick/math", - "version": "0.11.0", - "version_normalized": "0.11.0.0", + "version": "0.9.3", + "version_normalized": "0.9.3.0", "source": { "type": "git", "url": "https://github.com/brick/math.git", - "reference": "0ad82ce168c82ba30d1c01ec86116ab52f589478" + "reference": "ca57d18f028f84f777b2168cd1911b0dee2343ae" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/brick/math/zipball/0ad82ce168c82ba30d1c01ec86116ab52f589478", - "reference": "0ad82ce168c82ba30d1c01ec86116ab52f589478", + "url": "https://api.github.com/repos/brick/math/zipball/ca57d18f028f84f777b2168cd1911b0dee2343ae", + "reference": "ca57d18f028f84f777b2168cd1911b0dee2343ae", "shasum": "" }, "require": { - "php": "^8.0" + "ext-json": "*", + "php": "^7.1 || ^8.0" }, "require-dev": { "php-coveralls/php-coveralls": "^2.2", - "phpunit/phpunit": "^9.0", - "vimeo/psalm": "5.0.0" + "phpunit/phpunit": "^7.5.15 || ^8.5 || ^9.0", + "vimeo/psalm": "4.9.2" }, - "time": "2023-01-15T23:15:59+00:00", + "time": "2021-08-15T20:50:18+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -48,12 +49,16 @@ ], "support": { "issues": "https://github.com/brick/math/issues", - "source": "https://github.com/brick/math/tree/0.11.0" + "source": "https://github.com/brick/math/tree/0.9.3" }, "funding": [ { "url": "https://github.com/BenMorel", "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/brick/math", + "type": "tidelift" } ], "install-path": "../brick/math" @@ -532,42 +537,43 @@ }, { "name": "monolog/monolog", - "version": "3.5.0", - "version_normalized": "3.5.0.0", + "version": "2.9.2", + "version_normalized": "2.9.2.0", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "c915e2634718dbc8a4a15c61b0e62e7a44e14448" + "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/c915e2634718dbc8a4a15c61b0e62e7a44e14448", - "reference": "c915e2634718dbc8a4a15c61b0e62e7a44e14448", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", + "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f", "shasum": "" }, "require": { - "php": ">=8.1", - "psr/log": "^2.0 || ^3.0" + "php": ">=7.2", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" }, "provide": { - "psr/log-implementation": "3.0.0" + "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" }, "require-dev": { - "aws/aws-sdk-php": "^3.0", + "aws/aws-sdk-php": "^2.4.9 || ^3.0", "doctrine/couchdb": "~1.0@dev", "elasticsearch/elasticsearch": "^7 || ^8", "ext-json": "*", - "graylog2/gelf-php": "^1.4.2 || ^2.0", - "guzzlehttp/guzzle": "^7.4.5", + "graylog2/gelf-php": "^1.4.2 || ^2@dev", + "guzzlehttp/guzzle": "^7.4", "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpstan/phpstan": "^1.9", - "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-strict-rules": "^1.4", - "phpunit/phpunit": "^10.1", - "predis/predis": "^1.1 || ^2", + "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", "ruflin/elastica": "^7", + "swiftmailer/swiftmailer": "^5.3|^6.0", "symfony/mailer": "^5.4 || ^6", "symfony/mime": "^5.4 || ^6" }, @@ -587,11 +593,11 @@ "rollbar/rollbar": "Allow sending log messages to Rollbar", "ruflin/elastica": "Allow sending log messages to an Elastic Search server" }, - "time": "2023-10-27T15:32:31+00:00", + "time": "2023-10-27T15:25:26+00:00", "type": "library", "extra": { "branch-alias": { - "dev-main": "3.x-dev" + "dev-main": "2.x-dev" } }, "installation-source": "dist", @@ -620,7 +626,7 @@ ], "support": { "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/3.5.0" + "source": "https://github.com/Seldaek/monolog/tree/2.9.2" }, "funding": [ { @@ -805,33 +811,33 @@ }, { "name": "psr/log", - "version": "3.0.0", - "version_normalized": "3.0.0.0", + "version": "1.1.4", + "version_normalized": "1.1.4.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" + "reference": "d49695b909c3b7628b6289db5479a1c204601f11" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/fe5ea303b0887d5caefd3d431c3e61ad47037001", - "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", + "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", + "reference": "d49695b909c3b7628b6289db5479a1c204601f11", "shasum": "" }, "require": { - "php": ">=8.0.0" + "php": ">=5.3.0" }, - "time": "2021-07-14T16:46:02+00:00", + "time": "2021-05-03T11:20:27+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "3.x-dev" + "dev-master": "1.1.x-dev" } }, "installation-source": "dist", "autoload": { "psr-4": { - "Psr\\Log\\": "src" + "Psr\\Log\\": "Psr/Log/" } }, "notification-url": "https://packagist.org/downloads/", @@ -852,7 +858,7 @@ "psr-3" ], "support": { - "source": "https://github.com/php-fig/log/tree/3.0.0" + "source": "https://github.com/php-fig/log/tree/1.1.4" }, "install-path": "../psr/log" }, @@ -905,21 +911,22 @@ }, { "name": "ramsey/collection", - "version": "2.0.0", - "version_normalized": "2.0.0.0", + "version": "1.3.0", + "version_normalized": "1.3.0.0", "source": { "type": "git", "url": "https://github.com/ramsey/collection.git", - "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5" + "reference": "ad7475d1c9e70b190ecffc58f2d989416af339b4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ramsey/collection/zipball/a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", - "reference": "a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5", + "url": "https://api.github.com/repos/ramsey/collection/zipball/ad7475d1c9e70b190ecffc58f2d989416af339b4", + "reference": "ad7475d1c9e70b190ecffc58f2d989416af339b4", "shasum": "" }, "require": { - "php": "^8.1" + "php": "^7.4 || ^8.0", + "symfony/polyfill-php81": "^1.23" }, "require-dev": { "captainhook/plugin-composer": "^5.3", @@ -943,7 +950,7 @@ "ramsey/conventional-commits": "^1.3", "vimeo/psalm": "^5.4" }, - "time": "2022-12-31T21:50:55+00:00", + "time": "2022-12-27T19:12:24+00:00", "type": "library", "extra": { "captainhook": { @@ -981,7 +988,7 @@ ], "support": { "issues": "https://github.com/ramsey/collection/issues", - "source": "https://github.com/ramsey/collection/tree/2.0.0" + "source": "https://github.com/ramsey/collection/tree/1.3.0" }, "funding": [ { @@ -997,24 +1004,26 @@ }, { "name": "ramsey/uuid", - "version": "4.7.5", - "version_normalized": "4.7.5.0", + "version": "4.2.3", + "version_normalized": "4.2.3.0", "source": { "type": "git", "url": "https://github.com/ramsey/uuid.git", - "reference": "5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e" + "reference": "fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ramsey/uuid/zipball/5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e", - "reference": "5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df", + "reference": "fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df", "shasum": "" }, "require": { - "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11", + "brick/math": "^0.8 || ^0.9", "ext-json": "*", - "php": "^8.0", - "ramsey/collection": "^1.2 || ^2.0" + "php": "^7.2 || ^8.0", + "ramsey/collection": "^1.0", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-php80": "^1.14" }, "replace": { "rhumsaa/uuid": "self.version" @@ -1026,31 +1035,35 @@ "doctrine/annotations": "^1.8", "ergebnis/composer-normalize": "^2.15", "mockery/mockery": "^1.3", + "moontoast/math": "^1.1", "paragonie/random-lib": "^2", "php-mock/php-mock": "^2.2", "php-mock/php-mock-mockery": "^1.3", "php-parallel-lint/php-parallel-lint": "^1.1", "phpbench/phpbench": "^1.0", - "phpstan/extension-installer": "^1.1", - "phpstan/phpstan": "^1.8", - "phpstan/phpstan-mockery": "^1.1", - "phpstan/phpstan-phpunit": "^1.1", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-mockery": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", "phpunit/phpunit": "^8.5 || ^9", - "ramsey/composer-repl": "^1.4", - "slevomat/coding-standard": "^8.4", + "slevomat/coding-standard": "^7.0", "squizlabs/php_codesniffer": "^3.5", "vimeo/psalm": "^4.9" }, "suggest": { "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-ctype": "Enables faster processing of character classification using ctype functions.", "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." }, - "time": "2023-11-08T05:53:05+00:00", + "time": "2021-09-25T23:10:38+00:00", "type": "library", "extra": { + "branch-alias": { + "dev-main": "4.x-dev" + }, "captainhook": { "force-install": true } @@ -1076,7 +1089,7 @@ ], "support": { "issues": "https://github.com/ramsey/uuid/issues", - "source": "https://github.com/ramsey/uuid/tree/4.7.5" + "source": "https://github.com/ramsey/uuid/tree/4.2.3" }, "funding": [ { @@ -1092,27 +1105,27 @@ }, { "name": "symfony/deprecation-contracts", - "version": "v3.4.0", - "version_normalized": "3.4.0.0", + "version": "v2.5.2", + "version_normalized": "2.5.2.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/7c3aff79d10325257a001fcf92d991f24fc967cf", - "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66", "shasum": "" }, "require": { - "php": ">=8.1" + "php": ">=7.1" }, - "time": "2023-05-23T14:45:45+00:00", + "time": "2022-01-02T09:53:40+00:00", "type": "library", "extra": { "branch-alias": { - "dev-main": "3.4-dev" + "dev-main": "2.5-dev" }, "thanks": { "name": "symfony/contracts", @@ -1142,7 +1155,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.4.0" + "source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.2" }, "funding": [ { @@ -1159,6 +1172,259 @@ } ], "install-path": "../symfony/deprecation-contracts" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb", + "reference": "ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-ctype": "*" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "support": { + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-ctype" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php80" + }, + { + "name": "symfony/polyfill-php81", + "version": "v1.28.0", + "version_normalized": "1.28.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/7581cd600fa9fd681b797d00b02f068e2f13263b", + "reference": "7581cd600fa9fd681b797d00b02f068e2f13263b", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2023-01-26T09:26:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/polyfill-php81" } ], "dev": true, diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php index 19a50ae64..299e928f5 100644 --- a/vendor/composer/installed.php +++ b/vendor/composer/installed.php @@ -3,7 +3,7 @@ 'name' => 'buckaroo/prestashop', 'pretty_version' => 'dev-develop', 'version' => 'dev-develop', - 'reference' => 'd318ebcc9144ea608efb4d3a3a8650006a092f3e', + 'reference' => 'f9b12c447c8a8415386938ab9c3884931489eb70', 'type' => 'prestashop-module', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), @@ -11,9 +11,9 @@ ), 'versions' => array( 'brick/math' => array( - 'pretty_version' => '0.11.0', - 'version' => '0.11.0.0', - 'reference' => '0ad82ce168c82ba30d1c01ec86116ab52f589478', + 'pretty_version' => '0.9.3', + 'version' => '0.9.3.0', + 'reference' => 'ca57d18f028f84f777b2168cd1911b0dee2343ae', 'type' => 'library', 'install_path' => __DIR__ . '/../brick/math', 'aliases' => array(), @@ -22,7 +22,7 @@ 'buckaroo/prestashop' => array( 'pretty_version' => 'dev-develop', 'version' => 'dev-develop', - 'reference' => 'd318ebcc9144ea608efb4d3a3a8650006a092f3e', + 'reference' => 'f9b12c447c8a8415386938ab9c3884931489eb70', 'type' => 'prestashop-module', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), @@ -74,9 +74,9 @@ 'dev_requirement' => false, ), 'monolog/monolog' => array( - 'pretty_version' => '3.5.0', - 'version' => '3.5.0.0', - 'reference' => 'c915e2634718dbc8a4a15c61b0e62e7a44e14448', + 'pretty_version' => '2.9.2', + 'version' => '2.9.2.0', + 'reference' => '437cb3628f4cf6042cc10ae97fc2b8472e48ca1f', 'type' => 'library', 'install_path' => __DIR__ . '/../monolog/monolog', 'aliases' => array(), @@ -128,9 +128,9 @@ ), ), 'psr/log' => array( - 'pretty_version' => '3.0.0', - 'version' => '3.0.0.0', - 'reference' => 'fe5ea303b0887d5caefd3d431c3e61ad47037001', + 'pretty_version' => '1.1.4', + 'version' => '1.1.4.0', + 'reference' => 'd49695b909c3b7628b6289db5479a1c204601f11', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/log', 'aliases' => array(), @@ -139,7 +139,7 @@ 'psr/log-implementation' => array( 'dev_requirement' => false, 'provided' => array( - 0 => '3.0.0', + 0 => '1.0.0 || 2.0.0 || 3.0.0', ), ), 'ralouphie/getallheaders' => array( @@ -152,18 +152,18 @@ 'dev_requirement' => false, ), 'ramsey/collection' => array( - 'pretty_version' => '2.0.0', - 'version' => '2.0.0.0', - 'reference' => 'a4b48764bfbb8f3a6a4d1aeb1a35bb5e9ecac4a5', + 'pretty_version' => '1.3.0', + 'version' => '1.3.0.0', + 'reference' => 'ad7475d1c9e70b190ecffc58f2d989416af339b4', 'type' => 'library', 'install_path' => __DIR__ . '/../ramsey/collection', 'aliases' => array(), 'dev_requirement' => false, ), 'ramsey/uuid' => array( - 'pretty_version' => '4.7.5', - 'version' => '4.7.5.0', - 'reference' => '5f0df49ae5ad6efb7afa69e6bfab4e5b1e080d8e', + 'pretty_version' => '4.2.3', + 'version' => '4.2.3.0', + 'reference' => 'fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df', 'type' => 'library', 'install_path' => __DIR__ . '/../ramsey/uuid', 'aliases' => array(), @@ -172,17 +172,44 @@ 'rhumsaa/uuid' => array( 'dev_requirement' => false, 'replaced' => array( - 0 => '4.7.5', + 0 => '4.2.3', ), ), 'symfony/deprecation-contracts' => array( - 'pretty_version' => 'v3.4.0', - 'version' => '3.4.0.0', - 'reference' => '7c3aff79d10325257a001fcf92d991f24fc967cf', + 'pretty_version' => 'v2.5.2', + 'version' => '2.5.2.0', + 'reference' => 'e8b495ea28c1d97b5e0c121748d6f9b53d075c66', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', 'aliases' => array(), 'dev_requirement' => false, ), + 'symfony/polyfill-ctype' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'reference' => 'ea208ce43cbb04af6867b4fdddb1bdbf84cc28cb', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php80' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'reference' => '6caa57379c4aec19c0a12a38b59b26487dcfe4b5', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php80', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/polyfill-php81' => array( + 'pretty_version' => 'v1.28.0', + 'version' => '1.28.0.0', + 'reference' => '7581cd600fa9fd681b797d00b02f068e2f13263b', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/polyfill-php81', + 'aliases' => array(), + 'dev_requirement' => false, + ), ), ); diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php index 4c3a5d68f..580fa9609 100644 --- a/vendor/composer/platform_check.php +++ b/vendor/composer/platform_check.php @@ -4,8 +4,8 @@ $issues = array(); -if (!(PHP_VERSION_ID >= 80100)) { - $issues[] = 'Your Composer dependencies require a PHP version ">= 8.1.0". You are running ' . PHP_VERSION . '.'; +if (!(PHP_VERSION_ID >= 70400)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { diff --git a/vendor/monolog/monolog/CHANGELOG.md b/vendor/monolog/monolog/CHANGELOG.md index 13bb05390..aca1bdd0d 100644 --- a/vendor/monolog/monolog/CHANGELOG.md +++ b/vendor/monolog/monolog/CHANGELOG.md @@ -1,111 +1,3 @@ -### 3.5.0 (2023-10-27) - - * Added ability to indent stack traces in LineFormatter via e.g. `indentStacktraces(' ')` (#1835) - * Added ability to configure a max level name length in LineFormatter via e.g. `setMaxLevelNameLength(3)` (#1850) - * Added support for indexed arrays (i.e. `[]` and not `{}` arrays once json serialized) containing inline linebreaks in LineFormatter (#1818) - * Added `WithMonologChannel` attribute for integrators to use to configure autowiring (#1847) - * Fixed log record `extra` data leaking between handlers that have handler-specific processors set (#1819) - * Fixed LogglyHandler issue with record level filtering (#1841) - * Fixed display_errors parsing in ErrorHandler which did not support string values (#1804) - * Fixed bug where the previous error handler would not be restored in some cases where StreamHandler fails (#1815) - * Fixed normalization error when normalizing incomplete classes (#1833) - -### 3.4.0 (2023-06-21) - - * Added `LoadAverageProcessor` to track one of the 1, 5 or 15min load averages (#1803) - * Added support for priority to the `AsMonologProcessor` attribute (#1797) - * Added `TelegramBotHandler` `topic`/`message_thread_id` support (#1802) - * Fixed `FingersCrossedHandler` passthruLevel checking (#1801) - * Fixed support of yearly and monthly rotation log file to rotate only once a month/year (#1805) - * Fixed `TestHandler` method docs (#1794) - * Fixed handling of falsey `display_errors` string values (#1804) - -### 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.2 (2023-10-27) * Fixed display_errors parsing in ErrorHandler which did not support string values (#1804) diff --git a/vendor/monolog/monolog/README.md b/vendor/monolog/monolog/README.md index d7151de4f..bfcae0c00 100644 --- a/vendor/monolog/monolog/README.md +++ b/vendor/monolog/monolog/README.md @@ -1,12 +1,8 @@ -![Monolog](logo.jpg) - # Monolog - Logging for PHP [![Continuous Integration](https://github.com/Seldaek/monolog/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/Seldaek/monolog/actions) [![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) ->**Note** 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 @@ -32,13 +28,12 @@ $ composer require monolog/monolog ```php pushHandler(new StreamHandler('path/to/your.log', Level::Warning)); +$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); // add records to the log $log->warning('Foo'); @@ -55,7 +50,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. @@ -69,13 +64,11 @@ can also add your own there if you publish one. ### Requirements -- 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. +- Monolog `^2.0` works with PHP 7.2 or above, use Monolog `^1.25` for PHP 5.3+ support. ### Support -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. +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. ### Submitting bugs and feature requests @@ -103,7 +96,6 @@ 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/vendor/monolog/monolog/composer.json b/vendor/monolog/monolog/composer.json index 4ccd07211..b9437d6d5 100644 --- a/vendor/monolog/monolog/composer.json +++ b/vendor/monolog/monolog/composer.json @@ -13,25 +13,26 @@ } ], "require": { - "php": ">=8.1", - "psr/log": "^2.0 || ^3.0" + "php": ">=7.2", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" }, "require-dev": { "ext-json": "*", - "aws/aws-sdk-php": "^3.0", + "aws/aws-sdk-php": "^2.4.9 || ^3.0", "doctrine/couchdb": "~1.0@dev", "elasticsearch/elasticsearch": "^7 || ^8", - "graylog2/gelf-php": "^1.4.2 || ^2.0", - "guzzlehttp/guzzle": "^7.4.5", + "graylog2/gelf-php": "^1.4.2 || ^2@dev", + "guzzlehttp/guzzle": "^7.4", "guzzlehttp/psr7": "^2.2", "mongodb/mongodb": "^1.8", "php-amqplib/php-amqplib": "~2.4 || ^3", - "phpstan/phpstan": "^1.9", - "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-strict-rules": "^1.4", - "phpunit/phpunit": "^10.1", - "predis/predis": "^1.1 || ^2", + "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", "ruflin/elastica": "^7", + "swiftmailer/swiftmailer": "^5.3|^6.0", "symfony/mailer": "^5.4 || ^6", "symfony/mime": "^5.4 || ^6" }, @@ -58,11 +59,11 @@ "psr-4": {"Monolog\\": "tests/Monolog"} }, "provide": { - "psr/log-implementation": "3.0.0" + "psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0" }, "extra": { "branch-alias": { - "dev-main": "3.x-dev" + "dev-main": "2.x-dev" } }, "scripts": { @@ -72,6 +73,9 @@ "config": { "lock": false, "sort-packages": true, - "platform-check": false + "platform-check": false, + "allow-plugins": { + "composer/package-versions-deprecated": true + } } } diff --git a/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php b/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php index c519e0537..188bbb0d8 100644 --- a/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Attribute/AsMonologProcessor.php @@ -13,26 +13,34 @@ /** * 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 int|null $priority The priority of the processor so the order can be determined. */ public function __construct( - public readonly ?string $channel = null, - public readonly ?string $handler = null, - public readonly ?string $method = null, - public readonly ?int $priority = null + ?string $channel = null, + ?string $handler = null, + ?string $method = null ) { + $this->channel = $channel; + $this->handler = $handler; + $this->method = $method; } -} +} diff --git a/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php b/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php index 274b73ea1..6a1ba9b25 100644 --- a/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php +++ b/vendor/monolog/monolog/src/Monolog/DateTimeImmutable.php @@ -21,7 +21,10 @@ */ class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable { - private bool $useMicroseconds; + /** + * @var bool + */ + private $useMicroseconds; public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null) { diff --git a/vendor/monolog/monolog/src/Monolog/ErrorHandler.php b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php index 08d414b34..1406d34e8 100644 --- a/vendor/monolog/monolog/src/Monolog/ErrorHandler.php +++ b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php @@ -11,7 +11,6 @@ namespace Monolog; -use Closure; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; @@ -26,33 +25,35 @@ */ class ErrorHandler { - private Closure|null $previousExceptionHandler = null; + /** @var LoggerInterface */ + private $logger; + /** @var ?callable */ + private $previousExceptionHandler = null; /** @var array an array of class name to LogLevel::* constant mapping */ - private array $uncaughtExceptionLevelMap = []; - - /** @var Closure|true|null */ - private Closure|bool|null $previousErrorHandler = null; + private $uncaughtExceptionLevelMap = []; + /** @var callable|true|null */ + private $previousErrorHandler = null; /** @var array an array of E_* constant to LogLevel::* constant mapping */ - private array $errorLevelMap = []; - - private bool $handleOnlyReportedErrors = true; - - private bool $hasFatalErrorHandler = false; - - private string $fatalLevel = LogLevel::ALERT; - - private string|null $reservedMemory = null; - + private $errorLevelMap = []; + /** @var bool */ + private $handleOnlyReportedErrors = true; + + /** @var bool */ + private $hasFatalErrorHandler = false; + /** @var LogLevel::* */ + private $fatalLevel = LogLevel::ALERT; + /** @var ?string */ + private $reservedMemory = null; /** @var ?array{type: int, message: string, file: string, line: int, trace: mixed} */ - private array|null $lastFatalData = null; + private $lastFatalData = null; + /** @var int[] */ + private static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; - private const FATAL_ERRORS = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; - - public function __construct( - private LoggerInterface $logger - ) { + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; } /** @@ -60,10 +61,11 @@ public function __construct( * * 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 - * @return static + * @return ErrorHandler */ public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self { @@ -97,8 +99,8 @@ public function registerExceptionHandler(array $levelMap = [], bool $callPreviou $this->uncaughtExceptionLevelMap[$class] = $level; } } - if ($callPrevious && null !== $prev) { - $this->previousExceptionHandler = $prev(...); + if ($callPrevious && $prev) { + $this->previousExceptionHandler = $prev; } return $this; @@ -110,10 +112,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 !== null ? $prev(...) : true; + $this->previousErrorHandler = $prev ?: true; } else { $this->previousErrorHandler = null; } @@ -126,11 +128,10 @@ public function registerErrorHandler(array $levelMap = [], bool $callPrevious = /** * @param LogLevel::*|null $level a LogLevel::* constant, null to use the default LogLevel::ALERT * @param int $reservedMemorySize Amount of KBs to reserve in memory so that it can be freed when handling fatal errors giving Monolog some room in memory to get its job done - * @return $this */ 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; @@ -174,7 +175,10 @@ protected function defaultErrorLevelMap(): array ]; } - private function handleException(\Throwable $e): never + /** + * @phpstan-return never + */ + private function handleException(\Throwable $e): void { $level = LogLevel::ERROR; foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) { @@ -190,7 +194,7 @@ private function handleException(\Throwable $e): never ['exception' => $e] ); - if (null !== $this->previousExceptionHandler) { + if ($this->previousExceptionHandler) { ($this->previousExceptionHandler)($e); } @@ -201,14 +205,19 @@ private function handleException(\Throwable $e): never exit(255); } - private function handleError(int $code, string $message, string $file = '', int $line = 0): bool + /** + * @private + * + * @param mixed[] $context + */ + public function handleError(int $code, string $message, string $file = '', int $line = 0, ?array $context = []): bool { - if ($this->handleOnlyReportedErrors && 0 === (error_reporting() & $code)) { + if ($this->handleOnlyReportedErrors && !(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::FATAL_ERRORS, true)) { + if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) { $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL; $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]); } else { @@ -219,9 +228,8 @@ private function handleError(int $code, string $message, string $file = '', int if ($this->previousErrorHandler === true) { return false; - } - if ($this->previousErrorHandler instanceof Closure) { - return (bool) ($this->previousErrorHandler)($code, $message, $file, $line); + } elseif ($this->previousErrorHandler) { + return (bool) ($this->previousErrorHandler)($code, $message, $file, $line, $context); } return true; @@ -239,7 +247,8 @@ public function handleFatalError(): void } else { $lastError = error_get_last(); } - if (is_array($lastError) && in_array($lastError['type'], self::FATAL_ERRORS, true)) { + + if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) { $trace = $lastError['trace'] ?? null; $this->logger->log( $this->fatalLevel, @@ -255,25 +264,44 @@ public function handleFatalError(): void } } - private static function codeToString(int $code): string + /** + * @param int $code + */ + private static function codeToString($code): string { - 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', - }; + 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'; } } diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php index 3f1d45829..aa1884b9c 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ChromePHPFormatter.php @@ -11,8 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * Formats a log message according to the ChromePHP array format @@ -24,55 +23,52 @@ class ChromePHPFormatter implements FormatterInterface /** * Translates Monolog log levels to Wildfire levels. * - * @return 'log'|'info'|'warn'|'error' + * @var array */ - 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', - }; - } + 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', + ]; /** - * @inheritDoc + * {@inheritDoc} */ - public function format(LogRecord $record) + public function format(array $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 (\count($record->context) > 0) { - $message['context'] = $record->context; + $message = ['message' => $record['message']]; + if ($record['context']) { + $message['context'] = $record['context']; } - if (\count($record->extra) > 0) { - $message['extra'] = $record->extra; + if ($record['extra']) { + $message['extra'] = $record['extra']; } if (count($message) === 1) { $message = reset($message); } return [ - $record->channel, + $record['channel'], $message, $backtrace, - $this->toWildfireLevel($record->level), + $this->logLevels[$record['level']], ]; } /** - * @inheritDoc + * {@inheritDoc} */ public function formatBatch(array $records) { diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php index 8c92eff22..6c8a9ab5e 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticaFormatter.php @@ -12,30 +12,29 @@ 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 string $index; + protected $index; /** - * @var string|null Elastic search document type + * @var ?string Elastic search document type */ - protected string|null $type; + protected $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) { @@ -47,9 +46,9 @@ public function __construct(string $index, ?string $type) } /** - * @inheritDoc + * {@inheritDoc} */ - public function format(LogRecord $record) + public function format(array $record) { $record = parent::format($record); @@ -73,13 +72,14 @@ public function getType(): string /** * Convert a log message into an Elastica Document * - * @param mixed[] $record + * @phpstan-param Record $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/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php index b38aca079..b792b819c 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ElasticsearchFormatter.php @@ -12,7 +12,6 @@ namespace Monolog\Formatter; use DateTimeInterface; -use Monolog\LogRecord; /** * Format a log message into an Elasticsearch record @@ -24,18 +23,16 @@ class ElasticsearchFormatter extends NormalizerFormatter /** * @var string Elasticsearch index name */ - protected string $index; + protected $index; /** * @var string Elasticsearch record type */ - protected string $type; + protected $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) { @@ -47,9 +44,9 @@ public function __construct(string $index, string $type) } /** - * @inheritDoc + * {@inheritDoc} */ - public function format(LogRecord $record) + public function format(array $record) { $record = parent::format($record); @@ -58,6 +55,8 @@ public function format(LogRecord $record) /** * Getter index + * + * @return string */ public function getIndex(): string { @@ -66,6 +65,8 @@ public function getIndex(): string /** * Getter type + * + * @return string */ public function getType(): string { diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php index c64da7c06..867ae586b 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FlowdockFormatter.php @@ -11,8 +11,6 @@ namespace Monolog\Formatter; -use Monolog\LogRecord; - /** * formats the record to be used in the FlowdockHandler * @@ -21,9 +19,15 @@ */ class FlowdockFormatter implements FormatterInterface { - private string $source; + /** + * @var string + */ + private $source; - private string $sourceEmail; + /** + * @var string + */ + private $sourceEmail; public function __construct(string $source, string $sourceEmail) { @@ -32,41 +36,43 @@ public function __construct(string $source, string $sourceEmail) } /** - * @inheritDoc + * {@inheritDoc} * * @return mixed[] */ - public function format(LogRecord $record): array + public function format(array $record): array { $tags = [ '#logs', - '#' . $record->level->toPsrLogLevel(), - '#' . $record->channel, + '#' . strtolower($record['level_name']), + '#' . $record['channel'], ]; - foreach ($record->extra as $value) { + foreach ($record['extra'] as $value) { $tags[] = '#' . $value; } $subject = sprintf( 'in %s: %s - %s', $this->source, - $record->level->getName(), - $this->getShortMessage($record->message) + $record['level_name'], + $this->getShortMessage($record['message']) ); - return [ + $record['flowdock'] = [ '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/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php index 04495a614..29b14d30d 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FluentdFormatter.php @@ -12,7 +12,6 @@ namespace Monolog\Formatter; use Monolog\Utils; -use Monolog\LogRecord; /** * Class FluentdFormatter @@ -40,11 +39,8 @@ class FluentdFormatter implements FormatterInterface /** * @var bool $levelTag should message level be a part of the fluentd tag */ - protected bool $levelTag = false; + protected $levelTag = false; - /** - * @throws \RuntimeException If the function json_encode does not exist - */ public function __construct(bool $levelTag = false) { if (!function_exists('json_encode')) { @@ -59,25 +55,25 @@ public function isUsingLevelsInTag(): bool return $this->levelTag; } - public function format(LogRecord $record): string + public function format(array $record): string { - $tag = $record->channel; + $tag = $record['channel']; if ($this->levelTag) { - $tag .= '.' . $record->level->toPsrLogLevel(); + $tag .= '.' . strtolower($record['level_name']); } $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->value; - $message['level_name'] = $record->level->getName(); + $message['level'] = $record['level']; + $message['level_name'] = $record['level_name']; } - 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/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php b/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php index 3413a4b05..19617ec5f 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/FormatterInterface.php @@ -11,28 +11,32 @@ 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 LogRecord $record A record to format - * @return mixed The formatted record + * @param array $record A record to format + * @return mixed The formatted record + * + * @phpstan-param Record $record */ - public function format(LogRecord $record); + public function format(array $record); /** * Formats a set of log records. * - * @param array $records A set of records to format - * @return mixed The formatted set of records + * @param array $records A set of records to format + * @return mixed The formatted set of records + * + * @phpstan-param Record[] $records */ public function formatBatch(array $records); } diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php index 96cb60ffe..3b3e1e7f6 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/GelfMessageFormatter.php @@ -11,16 +11,17 @@ namespace Monolog\Formatter; -use Monolog\Level; +use Monolog\Logger; 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 { @@ -29,43 +30,46 @@ class GelfMessageFormatter extends NormalizerFormatter /** * @var string the name of the system for the Gelf log message */ - protected string $systemName; + protected $systemName; /** * @var string a prefix for 'extra' fields from the Monolog record (optional) */ - protected string $extraPrefix; + protected $extraPrefix; /** * @var string a prefix for 'context' fields from the Monolog record (optional) */ - protected string $contextPrefix; + protected $contextPrefix; /** * @var int max length per field */ - protected int $maxLength; + protected $maxLength; /** - * Translates Monolog log levels to Graylog2 log priorities. + * @var int */ - 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, - }; - } + private $gelfVersion = 2; /** - * @throws \RuntimeException + * Translates Monolog log levels to Graylog2 log priorities. + * + * @var array + * + * @phpstan-var array */ + 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)) { @@ -74,44 +78,64 @@ public function __construct(?string $systemName = null, ?string $extraPrefix = n parent::__construct('U.u'); - $this->systemName = (null === $systemName || $systemName === '') ? (string) gethostname() : $systemName; + $this->systemName = (is_null($systemName) || $systemName === '') ? (string) gethostname() : $systemName; - $this->extraPrefix = null === $extraPrefix ? '' : $extraPrefix; + $this->extraPrefix = is_null($extraPrefix) ? '' : $extraPrefix; $this->contextPrefix = $contextPrefix; - $this->maxLength = null === $maxLength ? self::DEFAULT_MAX_LENGTH : $maxLength; + $this->maxLength = is_null($maxLength) ? self::DEFAULT_MAX_LENGTH : $maxLength; + + if (method_exists(Message::class, 'setFacility')) { + $this->gelfVersion = 1; + } } /** - * @inheritDoc + * {@inheritDoc} */ - public function format(LogRecord $record): Message + public function format(array $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); + $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'); } $message = new Message(); $message - ->setTimestamp($record->datetime) - ->setShortMessage($record->message) + ->setTimestamp($record['datetime']) + ->setShortMessage((string) $record['message']) ->setHost($this->systemName) - ->setLevel($this->getGraylog2Priority($record->level)); + ->setLevel($this->logLevels[$record['level']]); // message length + system name length + 200 for padding / metadata - $len = 200 + strlen($record->message) + strlen($this->systemName); + $len = 200 + strlen((string) $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 (isset($record->channel)) { - $message->setAdditional('facility', $record->channel); + 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']); } foreach ($extra as $key => $val) { @@ -136,10 +160,13 @@ public function format(LogRecord $record): Message $message->setAdditional($this->contextPrefix . $key, $val); } - 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]); + 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]); + } } } diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php index ea555d4de..ca52ebf4e 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php @@ -24,17 +24,17 @@ */ final class GoogleCloudLoggingFormatter extends JsonFormatter { - protected function normalizeRecord(LogRecord $record): array + /** {@inheritdoc} **/ + public function format(array $record): string { - $normalized = parent::normalizeRecord($record); - // Re-key level for GCP logging - $normalized['severity'] = $normalized['level_name']; - $normalized['time'] = $record->datetime->format(DateTimeInterface::RFC3339_EXTENDED); + $record['severity'] = $record['level_name']; + $record['time'] = $record['datetime']->format(DateTimeInterface::RFC3339_EXTENDED); // Remove keys that are not used by GCP - unset($normalized['level'], $normalized['level_name'], $normalized['datetime']); + unset($record['level'], $record['level_name'], $record['datetime']); - return $normalized; + return parent::format($record); } } + diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php index c316b65ee..10a4311cb 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/HtmlFormatter.php @@ -11,9 +11,8 @@ namespace Monolog\Formatter; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Formats incoming records into an HTML table @@ -26,24 +25,22 @@ class HtmlFormatter extends NormalizerFormatter { /** * Translates Monolog log levels to html color priorities. + * + * @var array */ - 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', - }; - } + 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', + ]; /** * @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) { @@ -70,13 +67,15 @@ 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 string $title Text to be in the h1 + * @param int $level Error level + * @return string */ - protected function addTitle(string $title, Level $level): string + protected function addTitle(string $title, int $level): string { $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); - return '

'.$title.'

'; + return '

'.$title.'

'; } /** @@ -84,25 +83,25 @@ protected function addTitle(string $title, Level $level): string * * @return string The formatted record */ - public function format(LogRecord $record): string + public function format(array $record): string { - $output = $this->addTitle($record->level->getName(), $record->level); + $output = $this->addTitle($record['level_name'], $record['level']); $output .= ''; - $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) { + $output .= $this->addRow('Message', (string) $record['message']); + $output .= $this->addRow('Time', $this->formatDate($record['datetime'])); + $output .= $this->addRow('Channel', $record['channel']); + if ($record['context']) { $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 (\count($record->extra) > 0) { + if ($record['extra']) { $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/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php index ca3d7d27f..b737d82e3 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/JsonFormatter.php @@ -11,9 +11,7 @@ namespace Monolog\Formatter; -use Stringable; use Throwable; -use Monolog\LogRecord; /** * Encodes whatever record data is passed to it as json @@ -21,6 +19,8 @@ * 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,18 +28,16 @@ class JsonFormatter extends NormalizerFormatter public const BATCH_MODE_NEWLINES = 2; /** @var self::BATCH_MODE_* */ - protected int $batchMode; - - protected bool $appendNewline; - - protected bool $ignoreEmptyContextAndExtra; - - protected bool $includeStacktraces = false; + protected $batchMode; + /** @var bool */ + protected $appendNewline; + /** @var bool */ + protected $ignoreEmptyContextAndExtra; + /** @var bool */ + protected $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) { @@ -72,11 +70,11 @@ public function isAppendingNewlines(): bool } /** - * @inheritDoc + * {@inheritDoc} */ - public function format(LogRecord $record): string + public function format(array $record): string { - $normalized = parent::format($record); + $normalized = $this->normalize($record); if (isset($normalized['context']) && $normalized['context'] === []) { if ($this->ignoreEmptyContextAndExtra) { @@ -97,18 +95,22 @@ public function format(LogRecord $record): string } /** - * @inheritDoc + * {@inheritDoc} */ public function formatBatch(array $records): string { - return match ($this->batchMode) { - static::BATCH_MODE_NEWLINES => $this->formatBatchNewlines($records), - default => $this->formatBatchJson($records), - }; + switch ($this->batchMode) { + case static::BATCH_MODE_NEWLINES: + return $this->formatBatchNewlines($records); + + case static::BATCH_MODE_JSON: + default: + return $this->formatBatchJson($records); + } } /** - * @return $this + * @return self */ public function includeStacktraces(bool $include = true): self { @@ -120,7 +122,7 @@ public function includeStacktraces(bool $include = true): self /** * Return a JSON-encoded array of records. * - * @phpstan-param LogRecord[] $records + * @phpstan-param Record[] $records */ protected function formatBatchJson(array $records): string { @@ -131,24 +133,30 @@ protected function formatBatchJson(array $records): string * Use new lines to separate records instead of a * JSON-encoded array. * - * @phpstan-param LogRecord[] $records + * @phpstan-param Record[] $records */ protected function formatBatchNewlines(array $records): string { + $instance = $this; + $oldNewline = $this->appendNewline; $this->appendNewline = false; - $formatted = array_map(fn (LogRecord $record) => $this->format($record), $records); + array_walk($records, function (&$value, $key) use ($instance) { + $value = $instance->format($value); + }); $this->appendNewline = $oldNewline; - return implode("\n", $formatted); + return implode("\n", $records); } /** * Normalizes given $data. * - * @return null|scalar|array|object + * @param mixed $data + * + * @return mixed */ - protected function normalize(mixed $data, int $depth = 0): mixed + protected function normalize($data, int $depth = 0) { if ($depth > $this->maxNormalizeDepth) { return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization'; @@ -184,7 +192,7 @@ protected function normalize(mixed $data, int $depth = 0): mixed return $data; } - if ($data instanceof Stringable) { + if (method_exists($data, '__toString')) { return $data->__toString(); } @@ -202,7 +210,7 @@ protected function normalize(mixed $data, int $depth = 0): mixed * Normalizes given exception with or without its own stack trace based on * `includeStacktraces` property. * - * @inheritDoc + * {@inheritDoc} */ protected function normalizeException(Throwable $e, int $depth = 0): array { diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php index 025572a5c..e6e789833 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php @@ -11,9 +11,7 @@ namespace Monolog\Formatter; -use Closure; use Monolog\Utils; -use Monolog\LogRecord; /** * Formats incoming records into a one-line string @@ -27,20 +25,22 @@ class LineFormatter extends NormalizerFormatter { public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"; - protected string $format; - protected bool $allowInlineLineBreaks; - protected bool $ignoreEmptyContextAndExtra; - protected bool $includeStacktraces; - protected ?int $maxLevelNameLength = null; - protected string $indentStacktraces = ''; - protected Closure|null $stacktracesParser = null; + /** @var string */ + protected $format; + /** @var bool */ + protected $allowInlineLineBreaks; + /** @var bool */ + protected $ignoreEmptyContextAndExtra; + /** @var bool */ + protected $includeStacktraces; + /** @var ?callable */ + protected $stacktracesParser; /** - * @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 + * @param string|null $format The format of the message + * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries + * @param bool $ignoreEmptyContextAndExtra */ public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false) { @@ -51,10 +51,7 @@ public function __construct(?string $format = null, ?string $dateFormat = null, parent::__construct($dateFormat); } - /** - * @return $this - */ - public function includeStacktraces(bool $include = true, ?Closure $parser = null): self + public function includeStacktraces(bool $include = true, ?callable $parser = null): self { $this->includeStacktraces = $include; if ($this->includeStacktraces) { @@ -65,22 +62,6 @@ public function includeStacktraces(bool $include = true, ?Closure $parser = null return $this; } - /** - * Indent stack traces to separate them a bit from the main log record messages - * - * @param string $indent The string used to indent, for example " " - * @return $this - */ - public function indentStacktraces(string $indent): self - { - $this->indentStacktraces = $indent; - - return $this; - } - - /** - * @return $this - */ public function allowInlineLineBreaks(bool $allow = true): self { $this->allowInlineLineBreaks = $allow; @@ -88,9 +69,6 @@ public function allowInlineLineBreaks(bool $allow = true): self return $this; } - /** - * @return $this - */ public function ignoreEmptyContextAndExtra(bool $ignore = true): self { $this->ignoreEmptyContextAndExtra = $ignore; @@ -99,30 +77,14 @@ public function ignoreEmptyContextAndExtra(bool $ignore = true): self } /** - * Allows cutting the level name to get fixed-length levels like INF for INFO, ERR for ERROR if you set this to 3 for example - * - * @param int|null $maxLevelNameLength Maximum characters for the level name. Set null for infinite length (default) - * @return $this + * {@inheritDoc} */ - public function setMaxLevelNameLength(?int $maxLevelNameLength = null): self - { - $this->maxLevelNameLength = $maxLevelNameLength; - - return $this; - } - - /** - * @inheritDoc - */ - public function format(LogRecord $record): string + public function format(array $record): string { $vars = parent::format($record); - if ($this->maxLevelNameLength !== null) { - $vars['level_name'] = substr($vars['level_name'], 0, $this->maxLevelNameLength); - } - $output = $this->format; + foreach ($vars['extra'] as $var => $val) { if (false !== strpos($output, '%extra.'.$var.'%')) { $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output); @@ -138,12 +100,12 @@ public function format(LogRecord $record): string } if ($this->ignoreEmptyContextAndExtra) { - if (\count($vars['context']) === 0) { + if (empty($vars['context'])) { unset($vars['context']); $output = str_replace('%context%', '', $output); } - if (\count($vars['extra']) === 0) { + if (empty($vars['extra'])) { unset($vars['extra']); $output = str_replace('%extra%', '', $output); } @@ -160,7 +122,6 @@ public function format(LogRecord $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)); } } @@ -190,7 +151,7 @@ protected function normalizeException(\Throwable $e, int $depth = 0): string { $str = $this->formatException($e); - if (($previous = $e->getPrevious()) instanceof \Throwable) { + if ($previous = $e->getPrevious()) { do { $depth++; if ($depth > $this->maxNormalizeDepth) { @@ -224,7 +185,7 @@ protected function convertToString($data): string protected function replaceNewlines(string $str): string { if ($this->allowInlineLineBreaks) { - if (0 === strpos($str, '{') || 0 === strpos($str, '[')) { + if (0 === strpos($str, '{')) { $str = preg_replace('/(?getTraceAsString(); - if ($this->stacktracesParser !== null) { + if ($this->stacktracesParser) { $trace = $this->stacktracesParserCustom($trace); } - if ($this->indentStacktraces !== '') { - $trace = str_replace("\n", "\n{$this->indentStacktraces}", $trace); - } - - return "\n{$this->indentStacktraces}[stacktrace]\n{$this->indentStacktraces}" . $trace . "\n"; + return "\n[stacktrace]\n" . $trace . "\n"; } private function stacktracesParserCustom(string $trace): string diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php index 5f0b6a453..29841aa38 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogglyFormatter.php @@ -11,8 +11,6 @@ namespace Monolog\Formatter; -use Monolog\LogRecord; - /** * Encodes message information into JSON in a format compatible with Loggly. * @@ -35,13 +33,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() */ - protected function normalizeRecord(LogRecord $record): array + public function format(array $record): string { - $recordData = parent::normalizeRecord($record); - - $recordData["timestamp"] = $record->datetime->format("Y-m-d\TH:i:s.uO"); - unset($recordData["datetime"]); + if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) { + $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO"); + unset($record["datetime"]); + } - return $recordData; + return parent::format($record); } } diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php index 9e44c19f4..b0451aba7 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogmaticFormatter.php @@ -11,8 +11,6 @@ namespace Monolog\Formatter; -use Monolog\LogRecord; - /** * Encodes message information into JSON in a format compatible with Logmatic. * @@ -22,13 +20,16 @@ class LogmaticFormatter extends JsonFormatter { protected const MARKERS = ["sourcecode", "php"]; - protected string $hostname = ''; - - protected string $appName = ''; + /** + * @var string + */ + protected $hostname = ''; /** - * @return $this + * @var string */ + protected $appname = ''; + public function setHostname(string $hostname): self { $this->hostname = $hostname; @@ -36,12 +37,9 @@ public function setHostname(string $hostname): self return $this; } - /** - * @return $this - */ - public function setAppName(string $appName): self + public function setAppname(string $appname): self { - $this->appName = $appName; + $this->appname = $appname; return $this; } @@ -52,19 +50,17 @@ public function setAppName(string $appName): self * @see http://doc.logmatic.io/docs/basics-to-send-data * @see \Monolog\Formatter\JsonFormatter::format() */ - public function normalizeRecord(LogRecord $record): array + public function format(array $record): string { - $record = parent::normalizeRecord($record); - - if ($this->hostname !== '') { + if (!empty($this->hostname)) { $record["hostname"] = $this->hostname; } - if ($this->appName !== '') { - $record["appname"] = $this->appName; + if (!empty($this->appname)) { + $record["appname"] = $this->appname; } $record["@marker"] = static::MARKERS; - return $record; + return parent::format($record); } } diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php index abee3cd13..f8de0d333 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/LogstashFormatter.php @@ -11,8 +11,6 @@ namespace Monolog\Formatter; -use Monolog\LogRecord; - /** * Serializes a log message to Logstash Event Format * @@ -26,30 +24,28 @@ class LogstashFormatter extends NormalizerFormatter /** * @var string the name of the system for the Logstash log message, used to fill the @source field */ - protected string $systemName; + protected $systemName; /** * @var string an application name for the Logstash log message, used to fill the @type field */ - protected string $applicationName; + protected $applicationName; /** * @var string the key for 'extra' fields from the Monolog record */ - protected string $extraKey; + protected $extraKey; /** * @var string the key for 'context' fields from the Monolog record */ - protected string $contextKey; + protected $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') { @@ -63,38 +59,41 @@ public function __construct(string $applicationName, ?string $systemName = null, } /** - * @inheritDoc + * {@inheritDoc} */ - public function format(LogRecord $record): string + public function format(array $record): string { - $recordData = parent::format($record); + $record = parent::format($record); + if (empty($record['datetime'])) { + $record['datetime'] = gmdate('c'); + } $message = [ - '@timestamp' => $recordData['datetime'], + '@timestamp' => $record['datetime'], '@version' => 1, 'host' => $this->systemName, ]; - if (isset($recordData['message'])) { - $message['message'] = $recordData['message']; + if (isset($record['message'])) { + $message['message'] = $record['message']; } - if (isset($recordData['channel'])) { - $message['type'] = $recordData['channel']; - $message['channel'] = $recordData['channel']; + if (isset($record['channel'])) { + $message['type'] = $record['channel']; + $message['channel'] = $record['channel']; } - if (isset($recordData['level_name'])) { - $message['level'] = $recordData['level_name']; + if (isset($record['level_name'])) { + $message['level'] = $record['level_name']; } - if (isset($recordData['level'])) { - $message['monolog_level'] = $recordData['level']; + if (isset($record['level'])) { + $message['monolog_level'] = $record['level']; } - if ('' !== $this->applicationName) { + if ($this->applicationName) { $message['type'] = $this->applicationName; } - if (\count($recordData['extra']) > 0) { - $message[$this->extraKey] = $recordData['extra']; + if (!empty($record['extra'])) { + $message[$this->extraKey] = $record['extra']; } - if (\count($recordData['context']) > 0) { - $message[$this->contextKey] = $recordData['context']; + if (!empty($record['context'])) { + $message[$this->contextKey] = $record['context']; } return $this->toJson($message) . "\n"; diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php index 9b7da8a9c..fca69a899 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/MongoDBFormatter.php @@ -14,7 +14,6 @@ use MongoDB\BSON\Type; use MongoDB\BSON\UTCDateTime; use Monolog\Utils; -use Monolog\LogRecord; /** * Formats a record for use with the MongoDBHandler. @@ -23,12 +22,15 @@ */ class MongoDBFormatter implements FormatterInterface { - private bool $exceptionTraceAsString; - private int $maxNestingLevel; - private bool $isLegacyMongoExt; + /** @var bool */ + private $exceptionTraceAsString; + /** @var int */ + private $maxNestingLevel; + /** @var bool */ + private $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) @@ -40,20 +42,20 @@ public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsStri } /** - * @inheritDoc + * {@inheritDoc} * * @return mixed[] */ - public function format(LogRecord $record): array + public function format(array $record): array { /** @var mixed[] $res */ - $res = $this->formatArray($record->toArray()); + $res = $this->formatArray($record); return $res; } /** - * @inheritDoc + * {@inheritDoc} * * @return array */ @@ -154,6 +156,7 @@ private function legacyGetMongoDbDateTime(\DateTimeInterface $value): UTCDateTim ? (int) $milliseconds : (string) $milliseconds; + // @phpstan-ignore-next-line return new UTCDateTime($milliseconds); } } diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php index a5c99156f..f926a842f 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php @@ -14,7 +14,6 @@ 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 @@ -25,15 +24,18 @@ class NormalizerFormatter implements FormatterInterface { public const SIMPLE_DATE = "Y-m-d\TH:i:sP"; - protected string $dateFormat; - protected int $maxNormalizeDepth = 9; - protected int $maxNormalizeItemCount = 1000; + /** @var string */ + protected $dateFormat; + /** @var int */ + protected $maxNormalizeDepth = 9; + /** @var int */ + protected $maxNormalizeItemCount = 1000; - private int $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS; + /** @var int */ + private $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) { @@ -44,25 +46,17 @@ public function __construct(?string $dateFormat = null) } /** - * @inheritDoc - */ - public function format(LogRecord $record) - { - return $this->normalizeRecord($record); - } - - /** - * Normalize an arbitrary value to a scalar|array|null + * {@inheritDoc} * - * @return null|scalar|array + * @param mixed[] $record */ - public function normalizeValue(mixed $data): mixed + public function format(array $record) { - return $this->normalize($data); + return $this->normalize($record); } /** - * @inheritDoc + * {@inheritDoc} */ public function formatBatch(array $records) { @@ -78,9 +72,6 @@ public function getDateFormat(): string return $this->dateFormat; } - /** - * @return $this - */ public function setDateFormat(string $dateFormat): self { $this->dateFormat = $dateFormat; @@ -96,9 +87,6 @@ public function getMaxNormalizeDepth(): int return $this->maxNormalizeDepth; } - /** - * @return $this - */ public function setMaxNormalizeDepth(int $maxNormalizeDepth): self { $this->maxNormalizeDepth = $maxNormalizeDepth; @@ -114,9 +102,6 @@ public function getMaxNormalizeItemCount(): int return $this->maxNormalizeItemCount; } - /** - * @return $this - */ public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self { $this->maxNormalizeItemCount = $maxNormalizeItemCount; @@ -126,8 +111,6 @@ public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self /** * Enables `json_encode` pretty print. - * - * @return $this */ public function setJsonPrettyPrint(bool $enable): self { @@ -141,25 +124,10 @@ public function setJsonPrettyPrint(bool $enable): self } /** - * 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 normalizeRecord(LogRecord $record): array - { - /** @var array $normalized */ - $normalized = $this->normalize($record->toArray()); - - return $normalized; - } - - /** - * @return null|scalar|array + * @param mixed $data + * @return null|scalar|array */ - protected function normalize(mixed $data, int $depth = 0): mixed + protected function normalize($data, int $depth = 0) { if ($depth > $this->maxNormalizeDepth) { return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'; @@ -204,7 +172,7 @@ protected function normalize(mixed $data, int $depth = 0): mixed } if ($data instanceof \JsonSerializable) { - /** @var null|scalar|array $value */ + /** @var null|scalar|array $value */ $value = $data->jsonSerialize(); } elseif (\get_class($data) === '__PHP_Incomplete_Class') { $accessor = new \ArrayObject($data); @@ -214,7 +182,7 @@ protected function normalize(mixed $data, int $depth = 0): mixed $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); } @@ -268,12 +236,12 @@ protected function normalizeException(Throwable $e, int $depth = 0) $trace = $e->getTrace(); foreach ($trace as $frame) { - if (isset($frame['file'], $frame['line'])) { + if (isset($frame['file'])) { $data['trace'][] = $frame['file'].':'.$frame['line']; } } - if (($previous = $e->getPrevious()) instanceof \Throwable) { + if ($previous = $e->getPrevious()) { $data['previous'] = $this->normalizeException($previous, $depth + 1); } @@ -292,7 +260,10 @@ protected function toJson($data, bool $ignoreErrors = false): string return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors); } - protected function formatDate(\DateTimeInterface $date): string + /** + * @return string + */ + protected function formatDate(\DateTimeInterface $date) { // 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 @@ -303,9 +274,6 @@ protected function formatDate(\DateTimeInterface $date): string return $date->format($this->dateFormat); } - /** - * @return $this - */ public function addJsonEncodeOption(int $option): self { $this->jsonEncodeOptions |= $option; @@ -313,9 +281,6 @@ public function addJsonEncodeOption(int $option): self return $this; } - /** - * @return $this - */ public function removeJsonEncodeOption(int $option): self { $this->jsonEncodeOptions &= ~$option; diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php index 4bc20a08c..187bc550d 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/ScalarFormatter.php @@ -11,10 +11,8 @@ namespace Monolog\Formatter; -use Monolog\LogRecord; - /** - * Formats data into an associative array of scalar (+ null) values. + * Formats data into an associative array of scalar values. * Objects and arrays will be JSON encoded. * * @author Andrew Lawson @@ -22,21 +20,25 @@ class ScalarFormatter extends NormalizerFormatter { /** - * @inheritDoc + * {@inheritDoc} * * @phpstan-return array $record */ - public function format(LogRecord $record): array + public function format(array $record): array { $result = []; - foreach ($record->toArray() as $key => $value) { - $result[$key] = $this->toScalar($value); + foreach ($record as $key => $value) { + $result[$key] = $this->normalizeValue($value); } return $result; } - protected function toScalar(mixed $value): string|int|float|bool|null + /** + * @param mixed $value + * @return scalar|null + */ + protected function normalizeValue($value) { $normalized = $this->normalize($value); diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php index 2e28b3ab4..6539b3473 100644 --- a/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php +++ b/vendor/monolog/monolog/src/Monolog/Formatter/WildfireFormatter.php @@ -11,8 +11,7 @@ namespace Monolog\Formatter; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * Serializes a log message according to Wildfire's header requirements @@ -20,13 +19,29 @@ * @author Eric Clemmons (@ericclemmons) * @author Christophe Coevoet * @author Kirill chEbba Chebunin + * + * @phpstan-import-type Level from \Monolog\Logger */ class WildfireFormatter extends NormalizerFormatter { /** - * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format + * Translates Monolog log levels to Wildfire levels. * - * @throws \RuntimeException If the function json_encode does not exist + * @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 */ public function __construct(?string $dateFormat = null) { @@ -37,61 +52,46 @@ public function __construct(?string $dateFormat = null) } /** - * Translates Monolog log levels to Wildfire levels. + * {@inheritDoc} * - * @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 + * @return string */ - public function format(LogRecord $record): string + public function format(array $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']); } - $message = ['message' => $record->message]; + /** @var mixed[] $record */ + $record = $this->normalize($record); + $message = ['message' => $record['message']]; $handleError = false; - if (count($record->context) > 0) { - $message['context'] = $this->normalize($record->context); + if ($record['context']) { + $message['context'] = $record['context']; $handleError = true; } - if (count($record->extra) > 0) { - $message['extra'] = $this->normalize($record->extra); + if ($record['extra']) { + $message['extra'] = $record['extra']; $handleError = true; } if (count($message) === 1) { $message = reset($message); } - if (is_array($message) && isset($message['context']['table'])) { + if (isset($record['context']['table'])) { $type = 'TABLE'; - $label = $record->channel .': '. $record->message; - $message = $message['context']['table']; + $label = $record['channel'] .': '. $record['message']; + $message = $record['context']['table']; } else { - $type = $this->toWildfireLevel($record->level); - $label = $record->channel; + $type = $this->logLevels[$record['level']]; + $label = $record['channel']; } // Create JSON object describing the appearance of the message in the console @@ -114,7 +114,7 @@ public function format(LogRecord $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(mixed $data, int $depth = 0): mixed + protected function normalize($data, int $depth = 0) { if (is_object($data) && !$data instanceof \DateTimeInterface) { return $data; diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php index d3c2cbd7b..a5cdaa71f 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php @@ -11,51 +11,55 @@ 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 { - protected Level $level = Level::Debug; - protected bool $bubble = true; + /** + * @var int + * @phpstan-var Level + */ + protected $level = Logger::DEBUG; + /** @var bool */ + protected $bubble = true; /** - * @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 + * @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 * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($level = Logger::DEBUG, bool $bubble = true) { $this->setLevel($level); $this->bubble = $bubble; } /** - * @inheritDoc + * {@inheritDoc} */ - public function isHandling(LogRecord $record): bool + public function isHandling(array $record): bool { - return $record->level->value >= $this->level->value; + return $record['level'] >= $this->level; } /** * Sets minimum logging level at which this handler will be triggered. * - * @param Level|LogLevel::* $level Level or level name - * @return $this - * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @param Level|LevelName|LogLevel::* $level Level or level name + * @return self */ - public function setLevel(int|string|Level $level): self + public function setLevel($level): self { $this->level = Logger::toMonologLevel($level); @@ -64,8 +68,12 @@ public function setLevel(int|string|Level $level): self /** * Gets minimum logging level at which this handler will be triggered. + * + * @return int + * + * @phpstan-return Level */ - public function getLevel(): Level + public function getLevel(): int { return $this->level; } @@ -73,9 +81,9 @@ public function getLevel(): Level /** * Sets the bubbling behavior. * - * @param bool $bubble true means that this handler allows bubbling. - * false means that bubbling is not permitted. - * @return $this + * @param bool $bubble true means that this handler allows bubbling. + * false means that bubbling is not permitted. + * @return self */ public function setBubble(bool $bubble): self { @@ -96,9 +104,9 @@ public function getBubble(): bool } /** - * @inheritDoc + * {@inheritDoc} */ - public function reset(): void + public function reset() { } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php index de13a76be..77e533fca 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractProcessingHandler.php @@ -11,8 +11,6 @@ namespace Monolog\Handler; -use Monolog\LogRecord; - /** * Base Handler class providing the Handler structure, including processors and formatters * @@ -20,6 +18,11 @@ * * @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 { @@ -27,19 +30,20 @@ abstract class AbstractProcessingHandler extends AbstractHandler implements Proc use FormattableHandlerTrait; /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { if (!$this->isHandling($record)) { return false; } - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } - $record->formatted = $this->getFormatter()->format($record); + $record['formatted'] = $this->getFormatter()->format($record); $this->write($record); @@ -47,11 +51,16 @@ public function handle(LogRecord $record): bool } /** - * Writes the (already formatted) record down to the log of the implementing handler + * Writes the record down to the log of the implementing handler + * + * @phpstan-param FormattedRecord $record */ - abstract protected function write(LogRecord $record): void; + abstract protected function write(array $record): void; - public function reset(): void + /** + * @return void + */ + public function reset() { parent::reset(); diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php index 695a1c07f..5e5ad1c1f 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/AbstractSyslogHandler.php @@ -11,59 +11,70 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; /** * Common syslog functionality + * + * @phpstan-import-type Level from \Monolog\Logger */ abstract class AbstractSyslogHandler extends AbstractProcessingHandler { - protected int $facility; + /** @var int */ + protected $facility; /** - * List of valid log facility names. - * @var array + * Translates Monolog log levels to syslog log priorities. + * @var array + * @phpstan-var array */ - 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, + 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, ]; /** - * Translates Monolog log levels to syslog log priorities. + * List of valid log facility names. + * @var array */ - protected function toSyslogPriority(Level $level): int - { - return $level->toRFC5424Level(); - } + 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, + ]; /** * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant */ - public function __construct(string|int $facility = \LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($facility = LOG_USER, $level = Logger::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 @@ -86,7 +97,7 @@ public function __construct(string|int $facility = \LOG_USER, int|string|Level $ } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php index 72265d4ba..994872ce8 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/AmqpHandler.php @@ -11,38 +11,24 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; 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; - /** - * @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 + * @var AMQPExchange|AMQPChannel $exchange */ - 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); - } + protected $exchange; + /** @var array */ + private $extraAttributes = []; /** * @return array @@ -59,7 +45,7 @@ public function getExtraAttributes(): array * message_id, user_id, app_id, delivery_mode, * priority, timestamp, expiration, type * or reply_to, headers. - * @return $this + * @return AmqpHandler */ public function setExtraAttributes(array $extraAttributes): self { @@ -68,11 +54,34 @@ public function setExtraAttributes(array $extraAttributes): self } /** - * @inheritDoc + * @var string */ - protected function write(LogRecord $record): void + 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) { - $data = $record->formatted; + 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"]; $routingKey = $this->getRoutingKey($record); if ($this->exchange instanceof AMQPExchange) { @@ -80,7 +89,7 @@ protected function write(LogRecord $record): void 'delivery_mode' => 2, 'content_type' => 'application/json', ]; - if (\count($this->extraAttributes) > 0) { + if ($this->extraAttributes) { $attributes = array_merge($attributes, $this->extraAttributes); } $this->exchange->publish( @@ -99,7 +108,7 @@ protected function write(LogRecord $record): void } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { @@ -114,6 +123,7 @@ public function handleBatch(array $records): void continue; } + /** @var Record $record */ $record = $this->processRecord($record); $data = $this->getFormatter()->format($record); @@ -129,10 +139,12 @@ public function handleBatch(array $records): void /** * Gets the routing key for the AMQP exchange + * + * @phpstan-param Record $record */ - protected function getRoutingKey(LogRecord $record): string + protected function getRoutingKey(array $record): string { - $routingKey = sprintf('%s.%s', $record->level->name, $record->channel); + $routingKey = sprintf('%s.%s', $record['level_name'], $record['channel']); return strtolower($routingKey); } @@ -143,14 +155,14 @@ private function createAmqpMessage(string $data): AMQPMessage 'delivery_mode' => 2, 'content_type' => 'application/json', ]; - if (\count($this->extraAttributes) > 0) { + if ($this->extraAttributes) { $attributes = array_merge($attributes, $this->extraAttributes); } return new AMQPMessage($data, $attributes); } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php index 5930ca488..95bbfed42 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/BrowserConsoleHandler.php @@ -14,31 +14,35 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; use Monolog\Utils; -use Monolog\LogRecord; -use Monolog\Level; +use Monolog\Logger; 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 { - protected static bool $initialized = false; - - /** @var LogRecord[] */ - protected static array $records = []; + /** @var bool */ + protected static $initialized = false; + /** @var FormattedRecord[] */ + protected static $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. * @@ -52,9 +56,9 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { // Accumulate records static::$records[] = $record; @@ -77,11 +81,11 @@ public static function send(): void return; } - if (count(static::$records) > 0) { + if (count(static::$records)) { if ($format === self::FORMAT_HTML) { - static::writeOutput(''); - } else { // js format - static::writeOutput(self::generateScript()); + static::writeOutput(''); + } elseif ($format === self::FORMAT_JS) { + static::writeOutput(static::generateScript()); } static::resetStatic(); } @@ -92,7 +96,7 @@ public function close(): void self::resetStatic(); } - public function reset(): void + public function reset() { parent::reset(); @@ -170,18 +174,18 @@ private static function generateScript(): string { $script = []; foreach (static::$records as $record) { - $context = self::dump('Context', $record->context); - $extra = self::dump('Extra', $record->extra); + $context = static::dump('Context', $record['context']); + $extra = static::dump('Extra', $record['extra']); - if (\count($context) === 0 && \count($extra) === 0) { - $script[] = self::call_array(self::getConsoleMethodForLevel($record->level), self::handleStyles($record->formatted)); + if (empty($context) && empty($extra)) { + $script[] = static::call_array(static::getConsoleMethodForLevel($record['level']), static::handleStyles($record['formatted'])); } else { $script = array_merge( $script, - [self::call_array('groupCollapsed', self::handleStyles($record->formatted))], + [static::call_array('groupCollapsed', static::handleStyles($record['formatted']))], $context, $extra, - [self::call('groupEnd')] + [static::call('groupEnd')] ); } } @@ -189,14 +193,18 @@ private static function generateScript(): string return "(function (c) {if (c && c.groupCollapsed) {\n" . implode("\n", $script) . "\n}})(console);"; } - private static function getConsoleMethodForLevel(Level $level): string + private static function getConsoleMethodForLevel(int $level): string { - return match ($level) { - Level::Debug => 'debug', - Level::Info, Level::Notice => 'info', - Level::Warning => 'warn', - Level::Error, Level::Critical, Level::Alert, Level::Emergency => 'error', - }; + 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'; } /** @@ -210,14 +218,14 @@ private static function handleStyles(string $formatted): array foreach (array_reverse($matches) as $match) { $args[] = '"font-weight: normal"'; - $args[] = self::quote(self::handleCustomStyles($match[2][0], $match[1][0])); + $args[] = static::quote(static::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[] = self::quote('font-weight: normal'); - $args[] = self::quote($format); + $args[] = static::quote('font-weight: normal'); + $args[] = static::quote($format); return array_reverse($args); } @@ -243,7 +251,6 @@ 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)); } @@ -258,16 +265,16 @@ private static function dump(string $title, array $dict): array { $script = []; $dict = array_filter($dict); - if (\count($dict) === 0) { + if (empty($dict)) { return $script; } - $script[] = self::call('log', self::quote('%c%s'), self::quote('font-weight: bold'), self::quote($title)); + $script[] = static::call('log', static::quote('%c%s'), static::quote('font-weight: bold'), static::quote($title)); foreach ($dict as $key => $value) { $value = json_encode($value); - if (false === $value) { - $value = self::quote(''); + if (empty($value)) { + $value = static::quote(''); } - $script[] = self::call('log', self::quote('%s: %o'), self::quote((string) $key), $value); + $script[] = static::call('log', static::quote('%s: %o'), static::quote((string) $key), $value); } return $script; @@ -288,7 +295,7 @@ private static function call(...$args): string throw new \UnexpectedValueException('Expected the first arg to be a string, got: '.var_export($method, true)); } - return self::call_array($method, $args); + return static::call_array($method, $args); } /** diff --git a/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php index ff89faa8a..fcce5d630 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/BufferHandler.php @@ -11,10 +11,9 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * Buffers all records until closing the handler and then pass them as batch. @@ -23,30 +22,32 @@ * sending one per log message. * * @author Christophe Coevoet + * + * @phpstan-import-type Record from \Monolog\Logger */ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface { use ProcessableHandlerTrait; - protected HandlerInterface $handler; - - protected int $bufferSize = 0; - - protected int $bufferLimit; - - protected bool $flushOnOverflow; - - /** @var LogRecord[] */ - protected array $buffer = []; - - protected bool $initialized = false; + /** @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; /** * @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, int|string|Level $level = Level::Debug, bool $bubble = true, bool $flushOnOverflow = false) + public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, bool $flushOnOverflow = false) { parent::__construct($level, $bubble); $this->handler = $handler; @@ -55,11 +56,11 @@ public function __construct(HandlerInterface $handler, int $bufferLimit = 0, int } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { - if ($record->level->isLowerThan($this->level)) { + if ($record['level'] < $this->level) { return false; } @@ -78,7 +79,8 @@ public function handle(LogRecord $record): bool } } - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } @@ -106,7 +108,7 @@ public function __destruct() } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { @@ -124,7 +126,7 @@ public function clear(): void $this->buffer = []; } - public function reset(): void + public function reset() { $this->flush(); @@ -138,7 +140,7 @@ public function reset(): void } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -152,7 +154,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php index 2f7f21d5f..234ecf614 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ChromePHPHandler.php @@ -13,10 +13,8 @@ use Monolog\Formatter\ChromePHPFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; -use Monolog\DateTimeImmutable; /** * Handler sending logs to the ChromePHP extension (http://www.chromephp.com/) @@ -24,6 +22,8 @@ * 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,28 +44,29 @@ 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}'; - protected static bool $initialized = false; + /** @var bool */ + protected static $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 bool $overflowed = false; + protected static $overflowed = false; /** @var mixed[] */ - protected static array $json = [ + protected static $json = [ 'version' => self::VERSION, 'columns' => ['label', 'log', 'backtrace', 'type'], 'rows' => [], ]; - protected static bool $sendHeaders = true; + /** @var bool */ + protected static $sendHeaders = true; - /** - * @throws \RuntimeException If the function json_encode does not exist - */ - public function __construct(int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($level = Logger::DEBUG, bool $bubble = true) { parent::__construct($level, $bubble); if (!function_exists('json_encode')) { @@ -74,7 +75,7 @@ public function __construct(int|string|Level $level = Level::Debug, bool $bubble } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { @@ -85,15 +86,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 (\count($messages) > 0) { + if (!empty($messages)) { $messages = $this->getFormatter()->formatBatch($messages); self::$json['rows'] = array_merge(self::$json['rows'], $messages); $this->send(); @@ -101,7 +102,7 @@ public function handleBatch(array $records): void } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { @@ -114,13 +115,13 @@ protected function getDefaultFormatter(): FormatterInterface * @see sendHeader() * @see send() */ - protected function write(LogRecord $record): void + protected function write(array $record): void { if (!$this->isWebRequest()) { return; } - self::$json['rows'][] = $record->formatted; + self::$json['rows'][] = $record['formatted']; $this->send(); } @@ -152,12 +153,15 @@ protected function send(): void if (strlen($data) > 3 * 1024) { self::$overflowed = true; - $record = new LogRecord( - message: 'Incomplete logs, chrome header size limit reached', - level: Level::Warning, - channel: 'monolog', - datetime: new DateTimeImmutable(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' => [], + ]; 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); @@ -183,7 +187,7 @@ protected function sendHeader(string $header, string $content): void */ protected function headersAccepted(): bool { - if (!isset($_SERVER['HTTP_USER_AGENT'])) { + if (empty($_SERVER['HTTP_USER_AGENT'])) { return false; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php index 8d9c10e76..526576132 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/CouchDBHandler.php @@ -13,42 +13,22 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\JsonFormatter; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * 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[] - * @phpstan-var Options - */ - private array $options; + /** @var mixed[] */ + private $options; /** * @param mixed[] $options - * - * @phpstan-param InputOptions $options */ - public function __construct(array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(array $options = [], $level = Logger::DEBUG, bool $bubble = true) { $this->options = array_merge([ 'host' => 'localhost', @@ -62,12 +42,12 @@ public function __construct(array $options = [], int|string|Level $level = Level } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { $basicAuth = null; - if (null !== $this->options['username'] && null !== $this->options['password']) { + if ($this->options['username']) { $basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']); } @@ -75,7 +55,7 @@ protected function write(LogRecord $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', @@ -88,7 +68,7 @@ protected function write(LogRecord $record): void } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php index 8388f5ade..3535a4fcd 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/CubeHandler.php @@ -11,9 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Logs to Cube. @@ -24,13 +23,18 @@ */ class CubeHandler extends AbstractProcessingHandler { - private ?\Socket $udpConnection = null; - private ?\CurlHandle $httpConnection = null; - private string $scheme; - private string $host; - private int $port; + /** @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; /** @var string[] */ - private array $acceptedSchemes = ['http', 'udp']; + private $acceptedSchemes = ['http', 'udp']; /** * Create a Cube handler @@ -39,7 +43,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, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = true) { $urlInfo = parse_url($url); @@ -47,7 +51,7 @@ public function __construct(string $url, int|string|Level $level = Level::Debug, throw new \UnexpectedValueException('URL "'.$url.'" is not valid'); } - if (!in_array($urlInfo['scheme'], $this->acceptedSchemes, true)) { + if (!in_array($urlInfo['scheme'], $this->acceptedSchemes)) { throw new \UnexpectedValueException( 'Invalid protocol (' . $urlInfo['scheme'] . ').' . ' Valid options are ' . implode(', ', $this->acceptedSchemes) @@ -56,7 +60,7 @@ public function __construct(string $url, int|string|Level $level = Level::Debug, $this->scheme = $urlInfo['scheme']; $this->host = $urlInfo['host']; - $this->port = $urlInfo['port']; + $this->port = (int) $urlInfo['port']; parent::__construct($level, $bubble); } @@ -107,24 +111,24 @@ protected function connectHttp(): void } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $date = $record->datetime; + $date = $record['datetime']; $data = ['time' => $date->format('Y-m-d\TH:i:s.uO')]; - $context = $record->context; + unset($record['datetime']); - if (isset($context['type'])) { - $data['type'] = $context['type']; - unset($context['type']); + if (isset($record['context']['type'])) { + $data['type'] = $record['context']['type']; + unset($record['context']['type']); } else { - $data['type'] = $record->channel; + $data['type'] = $record['channel']; } - $data['data'] = $context; - $data['data']['level'] = $record->level; + $data['data'] = $record['context']; + $data['data']['level'] = $record['level']; if ($this->scheme === 'http') { $this->writeHttp(Utils::jsonEncode($data)); @@ -135,20 +139,16 @@ protected function write(LogRecord $record): void private function writeUdp(string $data): void { - if (null === $this->udpConnection) { + if (!$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 (null === $this->httpConnection) { + if (!$this->httpConnection) { $this->connectHttp(); } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php b/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php index 4decf0e62..7213e8ee2 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/Curl/Util.php @@ -21,7 +21,7 @@ final class Util { /** @var array */ - private static array $retriableErrorCodes = [ + private static $retriableErrorCodes = [ CURLE_COULDNT_RESOLVE_HOST, CURLE_COULDNT_CONNECT, CURLE_HTTP_NOT_FOUND, @@ -34,17 +34,19 @@ final class Util /** * Executes a CURL request with optional retries and exception on failure * - * @param CurlHandle $ch curl handler - * @return bool|string @see curl_exec + * @param resource|CurlHandle $ch curl handler + * @param int $retries + * @param bool $closeAfterDone + * @return bool|string @see curl_exec */ - public static function execute(CurlHandle $ch, int $retries = 5, bool $closeAfterDone = true) + public static function execute($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 === 0) { + if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) { $curlError = curl_error($ch); if ($closeAfterDone) { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php index b8ec90099..9b85ae7ed 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/DeduplicationHandler.php @@ -11,10 +11,8 @@ 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 @@ -35,29 +33,45 @@ * 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 { - protected string $deduplicationStore; + /** + * @var string + */ + protected $deduplicationStore; - protected Level $deduplicationLevel; + /** + * @var Level + */ + protected $deduplicationLevel; - protected int $time; + /** + * @var int + */ + protected $time; - private bool $gc = false; + /** + * @var bool + */ + private $gc = false; /** - * @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 + * @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 * - * @phpstan-param value-of|value-of|Level|LogLevel::* $deduplicationLevel + * @phpstan-param Level|LevelName|LogLevel::* $deduplicationLevel */ - public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, int|string|Level $deduplicationLevel = Level::Error, int $time = 60, bool $bubble = true) + public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, int $time = 60, bool $bubble = true) { - parent::__construct($handler, 0, Level::Debug, $bubble, false); + parent::__construct($handler, 0, Logger::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); @@ -73,8 +87,8 @@ public function flush(): void $passthru = null; foreach ($this->buffer as $record) { - if ($record->level->value >= $this->deduplicationLevel->value) { - $passthru = $passthru === true || !$this->isDuplicate($record); + if ($record['level'] >= $this->deduplicationLevel) { + $passthru = $passthru || !$this->isDuplicate($record); if ($passthru) { $this->appendRecord($record); } @@ -93,7 +107,10 @@ public function flush(): void } } - private function isDuplicate(LogRecord $record): bool + /** + * @phpstan-param Record $record + */ + private function isDuplicate(array $record): bool { if (!file_exists($this->deduplicationStore)) { return false; @@ -105,13 +122,13 @@ private function isDuplicate(LogRecord $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->getName() && $message === $expectedMessage && $timestamp > $timestampValidity) { + if ($level === $record['level_name'] && $message === $expectedMessage && $timestamp > $timestampValidity) { return true; } @@ -131,7 +148,7 @@ private function collectLogs(): void $handle = fopen($this->deduplicationStore, 'rw+'); - if (false === $handle) { + if (!$handle) { throw new \RuntimeException('Failed to open file for reading and writing: ' . $this->deduplicationStore); } @@ -142,7 +159,7 @@ private function collectLogs(): void while (!feof($handle)) { $log = fgets($handle); - if (is_string($log) && '' !== $log && substr($log, 0, 10) >= $timestampValidity) { + if ($log && substr($log, 0, 10) >= $timestampValidity) { $validLogs[] = $log; } } @@ -159,8 +176,11 @@ private function collectLogs(): void $this->gc = false; } - private function appendRecord(LogRecord $record): void + /** + * @phpstan-param Record $record + */ + private function appendRecord(array $record): void { - file_put_contents($this->deduplicationStore, $record->datetime->getTimestamp() . ':' . $record->level->getName() . ':' . preg_replace('{[\r\n].*}', '', $record->message) . "\n", FILE_APPEND); + file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND); } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php index eab9f1089..ebd52c3a0 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/DoctrineCouchDBHandler.php @@ -11,11 +11,10 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\NormalizerFormatter; use Monolog\Formatter\FormatterInterface; use Doctrine\CouchDB\CouchDBClient; -use Monolog\LogRecord; /** * CouchDB handler for Doctrine CouchDB ODM @@ -24,20 +23,21 @@ */ class DoctrineCouchDBHandler extends AbstractProcessingHandler { - private CouchDBClient $client; + /** @var CouchDBClient */ + private $client; - public function __construct(CouchDBClient $client, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(CouchDBClient $client, $level = Logger::DEBUG, bool $bubble = true) { $this->client = $client; parent::__construct($level, $bubble); } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->client->postDocument($record->formatted); + $this->client->postDocument($record['formatted']); } protected function getDefaultFormatter(): FormatterInterface diff --git a/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php index f1c5a9590..21840bf60 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/DynamoDbHandler.php @@ -16,8 +16,7 @@ use Monolog\Formatter\FormatterInterface; use Aws\DynamoDb\Marshaler; use Monolog\Formatter\ScalarFormatter; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/) @@ -29,15 +28,35 @@ class DynamoDbHandler extends AbstractProcessingHandler { public const DATE_FORMAT = 'Y-m-d\TH:i:s.uO'; - protected DynamoDbClient $client; + /** + * @var DynamoDbClient + */ + protected $client; - protected string $table; + /** + * @var string + */ + protected $table; - protected Marshaler $marshaler; + /** + * @var int + */ + protected $version; + + /** + * @var Marshaler + */ + protected $marshaler; - public function __construct(DynamoDbClient $client, string $table, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(DynamoDbClient $client, string $table, $level = Logger::DEBUG, bool $bubble = true) { - $this->marshaler = new Marshaler; + /** @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->client = $client; $this->table = $table; @@ -46,12 +65,17 @@ public function __construct(DynamoDbClient $client, string $table, int|string|Le } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $filtered = $this->filterEmptyFields($record->formatted); - $formatted = $this->marshaler->marshalItem($filtered); + $filtered = $this->filterEmptyFields($record['formatted']); + if ($this->version === 3) { + $formatted = $this->marshaler->marshalItem($filtered); + } else { + /** @phpstan-ignore-next-line */ + $formatted = $this->client->formatAttributes($filtered); + } $this->client->putItem([ 'TableName' => $this->table, @@ -66,12 +90,12 @@ protected function write(LogRecord $record): void protected function filterEmptyFields(array $record): array { return array_filter($record, function ($value) { - return [] !== $value; + return !empty($value) || false === $value || 0 === $value; }); } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php index d9b85b4d0..fc92ca42d 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ElasticaHandler.php @@ -14,10 +14,9 @@ use Elastica\Document; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\ElasticaFormatter; -use Monolog\Level; +use Monolog\Logger; use Elastica\Client; use Elastica\Exception\ExceptionInterface; -use Monolog\LogRecord; /** * Elastic Search handler @@ -34,34 +33,24 @@ * $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 { - protected Client $client; + /** + * @var Client + */ + protected $client; /** * @var mixed[] Handler config options - * @phpstan-var Options */ - protected array $options; + protected $options = []; /** * @param Client $client Elastica Client object * @param mixed[] $options Handler configuration - * - * @phpstan-param InputOptions $options */ - public function __construct(Client $client, array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) { parent::__construct($level, $bubble); $this->client = $client; @@ -76,15 +65,15 @@ public function __construct(Client $client, array $options = [], int|string|Leve } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->bulkSend([$record->formatted]); + $this->bulkSend([$record['formatted']]); } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -97,8 +86,6 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface /** * @return mixed[] - * - * @phpstan-return Options */ public function getOptions(): array { @@ -106,7 +93,7 @@ public function getOptions(): array } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { @@ -114,7 +101,7 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php index 74cc7b6e6..e88375c0e 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ElasticsearchHandler.php @@ -14,13 +14,12 @@ use Elastic\Elasticsearch\Response\Elasticsearch; use Throwable; use RuntimeException; -use Monolog\Level; +use Monolog\Logger; 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; @@ -44,28 +43,18 @@ * $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 { - protected Client|Client8 $client; + /** + * @var Client|Client8 + */ + protected $client; /** * @var mixed[] Handler config options - * @phpstan-var Options */ - protected array $options; + protected $options = []; /** * @var bool @@ -75,11 +64,13 @@ class ElasticsearchHandler extends AbstractProcessingHandler /** * @param Client|Client8 $client Elasticsearch Client object * @param mixed[] $options Handler configuration - * - * @phpstan-param InputOptions $options */ - public function __construct(Client|Client8 $client, array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($client, array $options = [], $level = Logger::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( @@ -87,7 +78,6 @@ public function __construct(Client|Client8 $client, array $options = [], int|str '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 ); @@ -102,15 +92,15 @@ public function __construct(Client|Client8 $client, array $options = [], int|str } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->bulkSend([$record->formatted]); + $this->bulkSend([$record['formatted']]); } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -125,8 +115,6 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface * Getter options * * @return mixed[] - * - * @phpstan-return Options */ public function getOptions(): array { @@ -134,7 +122,7 @@ public function getOptions(): array } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { @@ -142,7 +130,7 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { @@ -153,7 +141,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 @@ -165,7 +153,7 @@ protected function bulkSend(array $records): void foreach ($records as $record) { $params['body'][] = [ - $this->options['op_type'] => $this->needsType ? [ + 'index' => $this->needsType ? [ '_index' => $record['_index'], '_type' => $record['_type'], ] : [ diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php index 571c439e1..f2e22036b 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ErrorLogHandler.php @@ -13,9 +13,8 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Stores to PHP error_log() handler. @@ -27,16 +26,16 @@ class ErrorLogHandler extends AbstractProcessingHandler public const OPERATING_SYSTEM = 0; public const SAPI = 4; - protected int $messageType; - protected bool $expandNewlines; + /** @var int */ + protected $messageType; + /** @var bool */ + protected $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, int|string|Level $level = Level::Debug, bool $bubble = true, bool $expandNewlines = false) + public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, bool $expandNewlines = false) { parent::__construct($level, $bubble); @@ -62,7 +61,7 @@ public static function getAvailableTypes(): array } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { @@ -70,20 +69,19 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $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/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php index 58318bee7..d4e234ce0 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FallbackGroupHandler.php @@ -12,7 +12,6 @@ namespace Monolog\Handler; use Throwable; -use Monolog\LogRecord; /** * Forwards records to at most one handler @@ -20,20 +19,23 @@ * 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(LogRecord $record): bool + public function handle(array $record): bool { - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } foreach ($this->handlers as $handler) { try { - $handler->handle(clone $record); + $handler->handle($record); break; } catch (Throwable $e) { // What throwable? @@ -44,21 +46,22 @@ public function handle(LogRecord $record): bool } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { - if (\count($this->processors) > 0) { + if ($this->processors) { $processed = []; foreach ($records as $record) { $processed[] = $this->processRecord($record); } + /** @var Record[] $records */ $records = $processed; } foreach ($this->handlers as $handler) { try { - $handler->handleBatch(array_map(fn ($record) => clone $record, $records)); + $handler->handleBatch($records); break; } catch (Throwable $e) { // What throwable? diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php index 5fa558e19..718f17ef1 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FilterHandler.php @@ -11,13 +11,10 @@ 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 @@ -26,100 +23,110 @@ * * @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 Closure($record, $this) + * Handler or factory callable($record, $this) * - * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + * @var callable|HandlerInterface + * @phpstan-var callable(?Record, HandlerInterface): HandlerInterface|HandlerInterface */ - protected Closure|HandlerInterface $handler; + protected $handler; /** * Minimum level for logs that are passed to handler * - * @var bool[] Map of Level value => true - * @phpstan-var array, true> + * @var int[] + * @phpstan-var array */ - protected array $acceptedLevels; + protected $acceptedLevels; /** * Whether the messages that are handled can bubble up the stack or not + * + * @var bool */ - protected bool $bubble; + protected $bubble; /** - * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * @psalm-param HandlerInterface|callable(?Record, HandlerInterface): HandlerInterface $handler * - * @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 + * @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 * - * @phpstan-param value-of|value-of|Level|LogLevel::*|array|value-of|Level|LogLevel::*> $minLevelOrList - * @phpstan-param value-of|value-of|Level|LogLevel::* $maxLevel + * @phpstan-param Level|LevelName|LogLevel::*|array $minLevelOrList + * @phpstan-param Level|LevelName|LogLevel::* $maxLevel */ - public function __construct(Closure|HandlerInterface $handler, int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency, bool $bubble = true) + public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::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 list List of levels + * @phpstan-return array */ public function getAcceptedLevels(): array { - return array_map(fn (int $level) => Level::from($level), array_keys($this->acceptedLevels)); + return array_flip($this->acceptedLevels); } /** - * @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 - * @return $this + * @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 * - * @phpstan-param value-of|value-of|Level|LogLevel::*|array|value-of|Level|LogLevel::*> $minLevelOrList - * @phpstan-param value-of|value-of|Level|LogLevel::* $maxLevel + * @phpstan-param Level|LevelName|LogLevel::*|array $minLevelOrList + * @phpstan-param Level|LevelName|LogLevel::* $maxLevel */ - public function setAcceptedLevels(int|string|Level|array $minLevelOrList = Level::Debug, int|string|Level $maxLevel = Level::Emergency): self + public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY): self { if (is_array($minLevelOrList)) { - $acceptedLevels = array_map(Logger::toMonologLevel(...), $minLevelOrList); + $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); } else { $minLevelOrList = Logger::toMonologLevel($minLevelOrList); $maxLevel = Logger::toMonologLevel($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; + $acceptedLevels = array_values(array_filter(Logger::getLevels(), function ($level) use ($minLevelOrList, $maxLevel) { + return $level >= $minLevelOrList && $level <= $maxLevel; + })); } + $this->acceptedLevels = array_flip($acceptedLevels); return $this; } /** - * @inheritDoc + * {@inheritDoc} */ - public function isHandling(LogRecord $record): bool + public function isHandling(array $record): bool { - return isset($this->acceptedLevels[$record->level->value]); + return isset($this->acceptedLevels[$record['level']]); } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { if (!$this->isHandling($record)) { return false; } - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } @@ -129,7 +136,7 @@ public function handle(LogRecord $record): bool } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { @@ -148,23 +155,26 @@ public function handleBatch(array $records): void /** * Return the nested handler * - * If the handler was provided as a factory, this will trigger the handler's instantiation. + * If the handler was provided as a factory callable, this will trigger the handler's instantiation. + * + * @return HandlerInterface + * + * @phpstan-param Record $record */ - public function getHandler(LogRecord $record = null): HandlerInterface + public function getHandler(array $record = null) { if (!$this->handler instanceof HandlerInterface) { - $handler = ($this->handler)($record, $this); - if (!$handler instanceof HandlerInterface) { - throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + $this->handler = ($this->handler)($record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); } - $this->handler = $handler; } return $this->handler; } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -179,7 +189,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { @@ -191,7 +201,7 @@ public function getFormatter(): FormatterInterface throw new \UnexpectedValueException('The nested handler of type '.get_class($handler).' does not support formatters.'); } - public function reset(): void + public function reset() { $this->resetProcessors(); diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php index e8a1b0b0d..0aa5607b1 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php @@ -11,17 +11,19 @@ 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(LogRecord $record): bool; + public function isHandlerActivated(array $record): bool; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php index 383e19af9..7b9abb582 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php @@ -11,10 +11,8 @@ 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 @@ -25,45 +23,55 @@ * * * $activationStrategy = new ChannelLevelActivationStrategy( - * Level::Critical, + * Logger::CRITICAL, * array( - * 'request' => Level::Alert, - * 'sensitive' => Level::Error, + * 'request' => Logger::ALERT, + * 'sensitive' => Logger::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 { - private Level $defaultActionLevel; + /** + * @var Level + */ + private $defaultActionLevel; /** * @var array */ - private array $channelToActionLevel; + private $channelToActionLevel; /** - * @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. + * @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. * - * @phpstan-param value-of|value-of|Level|LogLevel::* $defaultActionLevel - * @phpstan-param array|value-of|Level|LogLevel::*> $channelToActionLevel + * @phpstan-param array $channelToActionLevel + * @phpstan-param Level|LevelName|LogLevel::* $defaultActionLevel */ - public function __construct(int|string|Level $defaultActionLevel, array $channelToActionLevel = []) + public function __construct($defaultActionLevel, array $channelToActionLevel = []) { $this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel); - $this->channelToActionLevel = array_map(Logger::toMonologLevel(...), $channelToActionLevel); + $this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel); } - public function isHandlerActivated(LogRecord $record): bool + /** + * @phpstan-param Record $record + */ + public function isHandlerActivated(array $record): bool { - if (isset($this->channelToActionLevel[$record->channel])) { - return $record->level->value >= $this->channelToActionLevel[$record->channel]->value; + if (isset($this->channelToActionLevel[$record['channel']])) { + return $record['level'] >= $this->channelToActionLevel[$record['channel']]; } - return $record->level->value >= $this->defaultActionLevel->value; + return $record['level'] >= $this->defaultActionLevel; } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php index c3ca2967a..5ec88eab6 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php @@ -11,8 +11,6 @@ namespace Monolog\Handler\FingersCrossed; -use Monolog\Level; -use Monolog\LogRecord; use Monolog\Logger; use Psr\Log\LogLevel; @@ -20,23 +18,29 @@ * 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 { - private Level $actionLevel; + /** + * @var Level + */ + private $actionLevel; /** - * @param int|string|Level $actionLevel Level or name or value + * @param int|string $actionLevel Level or name or value * - * @phpstan-param value-of|value-of|Level|LogLevel::* $actionLevel + * @phpstan-param Level|LevelName|LogLevel::* $actionLevel */ - public function __construct(int|string|Level $actionLevel) + public function __construct($actionLevel) { $this->actionLevel = Logger::toMonologLevel($actionLevel); } - public function isHandlerActivated(LogRecord $record): bool + public function isHandlerActivated(array $record): bool { - return $record->level->value >= $this->actionLevel->value; + return $record['level'] >= $this->actionLevel; } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php index 1c3df386d..0627b4451 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FingersCrossedHandler.php @@ -11,15 +11,12 @@ 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 @@ -36,50 +33,55 @@ * 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; /** - * Handler or factory Closure($record, $this) - * - * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + * @var callable|HandlerInterface + * @phpstan-var callable(?Record, HandlerInterface): HandlerInterface|HandlerInterface */ - 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; + 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 + */ + protected $passthruLevel; + /** @var bool */ + protected $bubble; /** - * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * @psalm-param HandlerInterface|callable(?Record, HandlerInterface): HandlerInterface $handler * - * @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 + * @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 * - * @phpstan-param value-of|value-of|Level|LogLevel::*|ActivationStrategyInterface $activationStrategy - * @phpstan-param value-of|value-of|Level|LogLevel::* $passthruLevel + * @phpstan-param Level|LevelName|LogLevel::* $passthruLevel + * @phpstan-param Level|LevelName|LogLevel::*|ActivationStrategyInterface $activationStrategy */ - 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) + public function __construct($handler, $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, $passthruLevel = null) { if (null === $activationStrategy) { - $activationStrategy = new ErrorLevelActivationStrategy(Level::Warning); + $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); } // convert simple int activationStrategy to an object @@ -96,12 +98,16 @@ public function __construct(Closure|HandlerInterface $handler, int|string|Level| 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(LogRecord $record): bool + public function isHandling(array $record): bool { return true; } @@ -120,11 +126,12 @@ public function activate(): void } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } @@ -144,7 +151,7 @@ public function handle(LogRecord $record): bool } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { @@ -153,7 +160,7 @@ public function close(): void $this->getHandler()->close(); } - public function reset(): void + public function reset() { $this->flushBuffer(); @@ -181,9 +188,9 @@ public function clear(): void private function flushBuffer(): void { if (null !== $this->passthruLevel) { - $passthruLevel = $this->passthruLevel; - $this->buffer = array_filter($this->buffer, static function ($record) use ($passthruLevel) { - return $passthruLevel->includes($record->level); + $level = $this->passthruLevel; + $this->buffer = array_filter($this->buffer, function ($record) use ($level) { + return $record['level'] >= $level; }); if (count($this->buffer) > 0) { $this->getHandler(end($this->buffer))->handleBatch($this->buffer); @@ -197,23 +204,26 @@ private function flushBuffer(): void /** * Return the nested handler * - * If the handler was provided as a factory, this will trigger the handler's instantiation. + * If the handler was provided as a factory callable, this will trigger the handler's instantiation. + * + * @return HandlerInterface + * + * @phpstan-param Record $record */ - public function getHandler(LogRecord $record = null): HandlerInterface + public function getHandler(array $record = null) { if (!$this->handler instanceof HandlerInterface) { - $handler = ($this->handler)($record, $this); - if (!$handler instanceof HandlerInterface) { - throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + $this->handler = ($this->handler)($record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); } - $this->handler = $handler; } return $this->handler; } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -228,7 +238,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php index 6b9e5103a..72718de63 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FirePHPHandler.php @@ -13,12 +13,13 @@ 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 { @@ -46,15 +47,18 @@ class FirePHPHandler extends AbstractProcessingHandler /** * Whether or not Wildfire vendor-specific headers have been generated & sent yet + * @var bool */ - protected static bool $initialized = false; + protected static $initialized = false; /** * Shared static message index between potentially multiple handlers + * @var int */ - protected static int $messageIndex = 1; + protected static $messageIndex = 1; - protected static bool $sendHeaders = true; + /** @var bool */ + protected static $sendHeaders = true; /** * Base header creation function used by init headers & record headers @@ -81,19 +85,21 @@ protected function createHeader(array $meta, string $message): array * @phpstan-return non-empty-array * * @see createHeader() + * + * @phpstan-param FormattedRecord $record */ - protected function createRecordHeader(LogRecord $record): array + protected function createRecordHeader(array $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 { @@ -134,7 +140,7 @@ protected function sendHeader(string $header, string $content): void * @see sendHeader() * @see sendInitHeaders() */ - protected function write(LogRecord $record): void + protected function write(array $record): void { if (!self::$sendHeaders || !$this->isWebRequest()) { return; @@ -165,7 +171,7 @@ protected function write(LogRecord $record): void */ protected function headersAccepted(): bool { - if (isset($_SERVER['HTTP_USER_AGENT']) && 1 === preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { + if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { return true; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php index 220648223..85c95b9d7 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FleepHookHandler.php @@ -13,8 +13,7 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LineFormatter; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * Sends logs to Fleep.io using Webhook integrations @@ -23,6 +22,8 @@ * * @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation * @author Ando Roots + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class FleepHookHandler extends SocketHandler { @@ -33,7 +34,7 @@ class FleepHookHandler extends SocketHandler /** * @var string Webhook token (specifies the conversation where logs are sent) */ - protected string $token; + protected $token; /** * Construct a new Fleep.io Handler. @@ -41,12 +42,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 if OpenSSL is missing + * @param string $token Webhook token + * @throws MissingExtensionException */ public function __construct( string $token, - $level = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -88,16 +89,16 @@ protected function getDefaultFormatter(): FormatterInterface /** * Handles a log record */ - public function write(LogRecord $record): void + public function write(array $record): void { parent::write($record); $this->closeSocket(); } /** - * @inheritDoc + * {@inheritDoc} */ - protected function generateDataStream(LogRecord $record): string + protected function generateDataStream(array $record): string { $content = $this->buildContent($record); @@ -120,11 +121,13 @@ private function buildHeader(string $content): string /** * Builds the body of API call + * + * @phpstan-param FormattedRecord $record */ - private function buildContent(LogRecord $record): string + private function buildContent(array $record): string { $dataArray = [ - 'message' => $record->formatted, + 'message' => $record['formatted'], ]; return http_build_query($dataArray); diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php index d24bec40b..5715d5800 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FlowdockHandler.php @@ -11,11 +11,10 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; use Monolog\Formatter\FlowdockFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * Sends notifications through the Flowdock push API @@ -27,18 +26,23 @@ * * @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 { - protected string $apiToken; + /** + * @var string + */ + protected $apiToken; /** * @throws MissingExtensionException if OpenSSL is missing */ public function __construct( string $apiToken, - $level = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -64,7 +68,7 @@ public function __construct( } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -84,9 +88,9 @@ protected function getDefaultFormatter(): FormatterInterface } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { parent::write($record); @@ -94,9 +98,9 @@ protected function write(LogRecord $record): void } /** - * @inheritDoc + * {@inheritDoc} */ - protected function generateDataStream(LogRecord $record): string + protected function generateDataStream(array $record): string { $content = $this->buildContent($record); @@ -105,10 +109,12 @@ protected function generateDataStream(LogRecord $record): string /** * Builds the body of API call + * + * @phpstan-param FormattedRecord $record */ - private function buildContent(LogRecord $record): string + private function buildContent(array $record): string { - return Utils::jsonEncode($record->formatted); + return Utils::jsonEncode($record['formatted']['flowdock']); } /** diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php index 72da59e1c..fc1693cd0 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerInterface.php @@ -23,12 +23,15 @@ interface FormattableHandlerInterface /** * Sets the formatter. * - * @return HandlerInterface self + * @param FormatterInterface $formatter + * @return HandlerInterface self */ public function setFormatter(FormatterInterface $formatter): HandlerInterface; /** * Gets the formatter. + * + * @return FormatterInterface */ public function getFormatter(): FormatterInterface; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php index c044e0786..b60bdce0e 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/FormattableHandlerTrait.php @@ -21,10 +21,13 @@ */ trait FormattableHandlerTrait { - protected FormatterInterface|null $formatter = null; + /** + * @var ?FormatterInterface + */ + protected $formatter; /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -34,11 +37,11 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { - if (null === $this->formatter) { + if (!$this->formatter) { $this->formatter = $this->getDefaultFormatter(); } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php index ba5bb975d..4ff26c4cd 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/GelfHandler.php @@ -12,10 +12,9 @@ namespace Monolog\Handler; use Gelf\PublisherInterface; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\GelfMessageFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * Handler to send messages to a Graylog2 (http://www.graylog2.org) server @@ -28,12 +27,12 @@ class GelfHandler extends AbstractProcessingHandler /** * @var PublisherInterface the publisher object that sends the message to the server */ - protected PublisherInterface $publisher; + protected $publisher; /** * @param PublisherInterface $publisher a gelf publisher object */ - public function __construct(PublisherInterface $publisher, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true) { parent::__construct($level, $bubble); @@ -41,15 +40,15 @@ public function __construct(PublisherInterface $publisher, int|string|Level $lev } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->publisher->publish($record->formatted); + $this->publisher->publish($record['formatted']); } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php index 0423dc346..3c9dc4b3b 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/GroupHandler.php +++ b/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 array $handlers; - protected bool $bubble; + protected $handlers; + /** @var bool */ + protected $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(LogRecord $record): bool + public function isHandling(array $record): bool { foreach ($this->handlers as $handler) { if ($handler->isHandling($record)) { @@ -61,40 +61,42 @@ public function isHandling(LogRecord $record): bool } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } foreach ($this->handlers as $handler) { - $handler->handle(clone $record); + $handler->handle($record); } return false === $this->bubble; } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { - if (\count($this->processors) > 0) { + if ($this->processors) { $processed = []; foreach ($records as $record) { $processed[] = $this->processRecord($record); } + /** @var Record[] $records */ $records = $processed; } foreach ($this->handlers as $handler) { - $handler->handleBatch(array_map(fn ($record) => clone $record, $records)); + $handler->handleBatch($records); } } - public function reset(): void + public function reset() { $this->resetProcessors(); @@ -115,7 +117,7 @@ public function close(): void } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Handler.php b/vendor/monolog/monolog/src/Monolog/Handler/Handler.php index e89f969b8..34b4935dd 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/Handler.php +++ b/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/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php index 83905c323..affcc51fc 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/HandlerInterface.php @@ -11,12 +11,13 @@ 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 { @@ -29,9 +30,13 @@ interface HandlerInterface * is no guarantee that handle() will not be called, and isHandling() might not be called * for a given record. * - * @param LogRecord $record Partial log record having only a level initialized + * @param array $record Partial log record containing only a level key + * + * @return bool + * + * @phpstan-param array{level: Level} $record */ - public function isHandling(LogRecord $record): bool; + public function isHandling(array $record): bool; /** * Handles a record. @@ -43,16 +48,20 @@ public function isHandling(LogRecord $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 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. + * @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 */ - public function handle(LogRecord $record): bool; + public function handle(array $record): bool; /** * Handles a set of records at once. * - * @param array $records The records to handle + * @param array $records The records to handle (an array of record arrays) + * + * @phpstan-param Record[] $records */ public function handleBatch(array $records): void; diff --git a/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php b/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php index 541ec2541..d4351b9f9 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/HandlerWrapper.php @@ -13,7 +13,6 @@ use Monolog\ResettableInterface; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * This simple wrapper class can be used to extend handlers functionality. @@ -22,7 +21,7 @@ * * Inherit from this class and override handle() like this: * - * public function handle(LogRecord $record) + * public function handle(array $record) * { * if ($record meets certain conditions) { * return false; @@ -34,7 +33,10 @@ */ class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, FormattableHandlerInterface, ResettableInterface { - protected HandlerInterface $handler; + /** + * @var HandlerInterface + */ + protected $handler; public function __construct(HandlerInterface $handler) { @@ -42,23 +44,23 @@ public function __construct(HandlerInterface $handler) } /** - * @inheritDoc + * {@inheritDoc} */ - public function isHandling(LogRecord $record): bool + public function isHandling(array $record): bool { return $this->handler->isHandling($record); } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { return $this->handler->handle($record); } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { @@ -66,7 +68,7 @@ public function handleBatch(array $records): void } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { @@ -74,7 +76,7 @@ public function close(): void } /** - * @inheritDoc + * {@inheritDoc} */ public function pushProcessor(callable $callback): HandlerInterface { @@ -88,7 +90,7 @@ public function pushProcessor(callable $callback): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function popProcessor(): callable { @@ -100,7 +102,7 @@ public function popProcessor(): callable } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -114,7 +116,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { @@ -125,7 +127,7 @@ public function getFormatter(): FormatterInterface throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class); } - public function reset(): void + public function reset() { if ($this->handler instanceof ResettableInterface) { $this->handler->reset(); diff --git a/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php index 418f2ba03..000ccea40 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/IFTTTHandler.php @@ -11,9 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * IFTTTHandler uses cURL to trigger IFTTT Maker actions @@ -28,16 +27,16 @@ */ class IFTTTHandler extends AbstractProcessingHandler { - private string $eventName; - private string $secretKey; + /** @var string */ + private $eventName; + /** @var string */ + private $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, int|string|Level $level = Level::Error, bool $bubble = true) + public function __construct(string $eventName, string $secretKey, $level = Logger::ERROR, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler'); @@ -50,14 +49,14 @@ public function __construct(string $eventName, string $secretKey, int|string|Lev } /** - * @inheritDoc + * {@inheritDoc} */ - public function write(LogRecord $record): void + public function write(array $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/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php index abb2f88f7..71f64a267 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/InsightOpsHandler.php @@ -11,8 +11,7 @@ namespace Monolog\Handler; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * Inspired on LogEntriesHandler. @@ -22,12 +21,15 @@ */ class InsightOpsHandler extends SocketHandler { - protected string $logToken; + /** + * @var string + */ + protected $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 */ @@ -35,7 +37,7 @@ public function __construct( string $token, string $region = 'us', bool $useSSL = true, - $level = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -65,10 +67,10 @@ public function __construct( } /** - * @inheritDoc + * {@inheritDoc} */ - protected function generateDataStream(LogRecord $record): string + protected function generateDataStream(array $record): string { - return $this->logToken . ' ' . $record->formatted; + return $this->logToken . ' ' . $record['formatted']; } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php index 00259834e..25fcd1594 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogEntriesHandler.php @@ -11,27 +11,29 @@ namespace Monolog\Handler; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * @author Robert Kaufmann III */ class LogEntriesHandler extends SocketHandler { - protected string $logToken; + /** + * @var string + */ + protected $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 = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, string $host = 'data.logentries.com', bool $persistent = false, @@ -59,10 +61,10 @@ public function __construct( } /** - * @inheritDoc + * {@inheritDoc} */ - protected function generateDataStream(LogRecord $record): string + protected function generateDataStream(array $record): string { - return $this->logToken . ' ' . $record->formatted; + return $this->logToken . ' ' . $record['formatted']; } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php index 6a9a20e01..6d13db375 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogglyHandler.php @@ -11,12 +11,11 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LogglyFormatter; use function array_key_exists; use CurlHandle; -use Monolog\LogRecord; /** * Sends errors to Loggly. @@ -34,21 +33,22 @@ class LogglyHandler extends AbstractProcessingHandler /** * Caches the curl handlers for every given endpoint. * - * @var CurlHandle[] + * @var resource[]|CurlHandle[] */ - protected array $curlHandlers = []; + protected $curlHandlers = []; - protected string $token; + /** @var string */ + protected $token; /** @var string[] */ - protected array $tag = []; + protected $tag = []; /** * @param string $token API token supplied by Loggly * * @throws MissingExtensionException If the curl extension is missing */ - public function __construct(string $token, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler'); @@ -61,8 +61,12 @@ public function __construct(string $token, int|string|Level $level = Level::Debu /** * Loads and returns the shared curl handler for the given endpoint. + * + * @param string $endpoint + * + * @return resource|CurlHandle */ - protected function getCurlHandler(string $endpoint): CurlHandle + protected function getCurlHandler(string $endpoint) { if (!array_key_exists($endpoint, $this->curlHandlers)) { $this->curlHandlers[$endpoint] = $this->loadCurlHandle($endpoint); @@ -73,8 +77,12 @@ protected function getCurlHandler(string $endpoint): CurlHandle /** * Starts a fresh curl session for the given endpoint and returns its handler. + * + * @param string $endpoint + * + * @return resource|CurlHandle */ - private function loadCurlHandle(string $endpoint): CurlHandle + private function loadCurlHandle(string $endpoint) { $url = sprintf("https://%s/%s/%s/", static::HOST, $endpoint, $this->token); @@ -89,26 +97,21 @@ private function loadCurlHandle(string $endpoint): CurlHandle /** * @param string[]|string $tag - * @return $this */ - public function setTag(string|array $tag): self + public function setTag($tag): self { - if ('' === $tag || [] === $tag) { - $this->tag = []; - } else { - $this->tag = is_array($tag) ? $tag : [$tag]; - } + $tag = !empty($tag) ? $tag : []; + $this->tag = is_array($tag) ? $tag : [$tag]; return $this; } /** * @param string[]|string $tag - * @return $this */ - public function addTag(string|array $tag): self + public function addTag($tag): self { - if ('' !== $tag) { + if (!empty($tag)) { $tag = is_array($tag) ? $tag : [$tag]; $this->tag = array_unique(array_merge($this->tag, $tag)); } @@ -116,9 +119,9 @@ public function addTag(string|array $tag): self return $this; } - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->send($record->formatted, static::ENDPOINT_SINGLE); + $this->send($record["formatted"], static::ENDPOINT_SINGLE); } public function handleBatch(array $records): void @@ -126,10 +129,10 @@ public function handleBatch(array $records): void $level = $this->level; $records = array_filter($records, function ($record) use ($level) { - return ($record->level->value >= $level->value); + return ($record['level'] >= $level); }); - if (\count($records) > 0) { + if ($records) { $this->send($this->getFormatter()->formatBatch($records), static::ENDPOINT_BATCH); } } @@ -140,7 +143,7 @@ protected function send(string $data, string $endpoint): void $headers = ['Content-Type: application/json']; - if (\count($this->tag) > 0) { + if (!empty($this->tag)) { $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag); } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php index 876b1a953..859a46906 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/LogmaticHandler.php @@ -11,36 +11,44 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\LogmaticFormatter; -use Monolog\LogRecord; /** * @author Julien Breux */ class LogmaticHandler extends SocketHandler { - private string $logToken; + /** + * @var string + */ + private $logToken; - private string $hostname; + /** + * @var string + */ + private $hostname; - private string $appName; + /** + * @var string + */ + private $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 = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -68,29 +76,29 @@ public function __construct( $this->logToken = $token; $this->hostname = $hostname; - $this->appName = $appName; + $this->appname = $appname; } /** - * @inheritDoc + * {@inheritDoc} */ - protected function generateDataStream(LogRecord $record): string + protected function generateDataStream(array $record): string { - return $this->logToken . ' ' . $record->formatted; + return $this->logToken . ' ' . $record['formatted']; } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { $formatter = new LogmaticFormatter(); - if ($this->hostname !== '') { + if (!empty($this->hostname)) { $formatter->setHostname($this->hostname); } - if ($this->appName !== '') { - $formatter->setAppName($this->appName); + if (!empty($this->appname)) { + $formatter->setAppname($this->appname); } return $formatter; diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php index b6c822772..97f343202 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/MailHandler.php @@ -13,32 +13,33 @@ 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->isLowerThan($this->level)) { + if ($record['level'] < $this->level) { continue; } - + /** @var Record $message */ $message = $this->processRecord($record); $messages[] = $message; } - if (\count($messages) > 0) { + if (!empty($messages)) { $this->send((string) $this->getFormatter()->formatBatch($messages), $messages); } } @@ -49,26 +50,27 @@ 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 non-empty-array $records + * @phpstan-param Record[] $records */ abstract protected function send(string $content, array $records): void; /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->send((string) $record->formatted, [$record]); + $this->send((string) $record['formatted'], [$record]); } /** - * @phpstan-param non-empty-array $records + * @phpstan-param non-empty-array $records + * @phpstan-return Record */ - protected function getHighestRecord(array $records): LogRecord + protected function getHighestRecord(array $records): array { $highestRecord = null; foreach ($records as $record) { - if ($highestRecord === null || $record->level->isHigherThan($highestRecord->level)) { + if ($highestRecord === null || $highestRecord['level'] < $record['level']) { $highestRecord = $record; } } @@ -83,6 +85,8 @@ protected function isHtmlBody(string $body): bool /** * Gets the default formatter. + * + * @return FormatterInterface */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php index 64e16c9de..3003500ec 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/MandrillHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Swift; use Swift_Message; @@ -22,22 +22,22 @@ */ class MandrillHandler extends MailHandler { - protected Swift_Message $message; - protected string $apiKey; + /** @var Swift_Message */ + protected $message; + /** @var string */ + protected $apiKey; /** - * @phpstan-param (Swift_Message|callable(): Swift_Message) $message + * @psalm-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, callable|Swift_Message $message, int|string|Level $level = Level::Error, bool $bubble = true) + public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true) { parent::__construct($level, $bubble); - if (!$message instanceof Swift_Message) { + if (!$message instanceof Swift_Message && is_callable($message)) { $message = $message(); } if (!$message instanceof Swift_Message) { @@ -48,7 +48,7 @@ public function __construct(string $apiKey, callable|Swift_Message $message, int } /** - * @inheritDoc + * {@inheritDoc} */ protected function send(string $content, array $records): void { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php index 33ab68c6d..306309119 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/MongoDBHandler.php @@ -14,10 +14,9 @@ use MongoDB\Driver\BulkWrite; use MongoDB\Driver\Manager; use MongoDB\Client; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\MongoDBFormatter; -use Monolog\LogRecord; /** * Logs to a MongoDB database. @@ -34,11 +33,12 @@ */ class MongoDBHandler extends AbstractProcessingHandler { - private \MongoDB\Collection $collection; - - private Client|Manager $manager; - - private string|null $namespace = null; + /** @var \MongoDB\Collection */ + private $collection; + /** @var Client|Manager */ + private $manager; + /** @var string */ + private $namespace; /** * Constructor. @@ -47,8 +47,12 @@ class MongoDBHandler extends AbstractProcessingHandler * @param string $database Database name * @param string $collection Collection name */ - public function __construct(Client|Manager $mongodb, string $database, string $collection, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($mongodb, string $database, string $collection, $level = Logger::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 { @@ -59,21 +63,21 @@ public function __construct(Client|Manager $mongodb, string $database, string $c parent::__construct($level, $bubble); } - protected function write(LogRecord $record): void + protected function write(array $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/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php index 70d6004e1..0c0a3bdb1 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/NativeMailerHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\LineFormatter; /** @@ -26,39 +26,43 @@ class NativeMailerHandler extends MailHandler * The email addresses to which the message will be sent * @var string[] */ - protected array $to; + protected $to; /** * The subject of the email + * @var string */ - protected string $subject; + protected $subject; /** * Optional headers for the message * @var string[] */ - protected array $headers = []; + protected $headers = []; /** * Optional parameters for the message * @var string[] */ - protected array $parameters = []; + protected $parameters = []; /** * The wordwrap length for the message + * @var int */ - protected int $maxColumnWidth; + protected $maxColumnWidth; /** * The Content-type for the message + * @var string|null */ - protected string|null $contentType = null; + protected $contentType; /** * The encoding for the message + * @var string */ - protected string $encoding = 'utf-8'; + protected $encoding = 'utf-8'; /** * @param string|string[] $to The receiver of the mail @@ -66,7 +70,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(string|array $to, string $subject, string $from, int|string|Level $level = Level::Error, bool $bubble = true, int $maxColumnWidth = 70) + public function __construct($to, string $subject, string $from, $level = Logger::ERROR, bool $bubble = true, int $maxColumnWidth = 70) { parent::__construct($level, $bubble); $this->to = (array) $to; @@ -79,7 +83,6 @@ public function __construct(string|array $to, string $subject, string $from, int * Add headers to the message * * @param string|string[] $headers Custom added headers - * @return $this */ public function addHeader($headers): self { @@ -97,7 +100,6 @@ public function addHeader($headers): self * Add parameters to the message * * @param string|string[] $parameters Custom added parameters - * @return $this */ public function addParameter($parameters): self { @@ -107,11 +109,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); @@ -123,8 +125,11 @@ protected function send(string $content, array $records): void $headers .= 'MIME-Version: 1.0' . "\r\n"; } - $subjectFormatter = new LineFormatter($this->subject); - $subject = $subjectFormatter->format($this->getHighestRecord($records)); + $subject = $this->subject; + if ($records) { + $subjectFormatter = new LineFormatter($this->subject); + $subject = $subjectFormatter->format($this->getHighestRecord($records)); + } $parameters = implode(' ', $this->parameters); foreach ($this->to as $to) { @@ -144,7 +149,6 @@ public function getEncoding(): string /** * @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML messages. - * @return $this */ public function setContentType(string $contentType): self { @@ -157,9 +161,6 @@ public function setContentType(string $contentType): self return $this; } - /** - * @return $this - */ public function setEncoding(string $encoding): self { if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php index b8cb3785b..114d749eb 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/NewRelicHandler.php @@ -11,17 +11,16 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; 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 @@ -29,58 +28,75 @@ class NewRelicHandler extends AbstractProcessingHandler { /** - * @inheritDoc + * 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 */ public function __construct( - int|string|Level $level = Level::Error, + $level = Logger::ERROR, bool $bubble = true, - - /** - * 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 + ?string $appName = null, + bool $explodeArrays = false, + ?string $transactionName = null ) { parent::__construct($level, $bubble); + + $this->appName = $appName; + $this->explodeArrays = $explodeArrays; + $this->transactionName = $transactionName; } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { if (!$this->isNewRelicEnabled()) { throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler'); } - if (null !== ($appName = $this->getAppName($record->context))) { + if ($appName = $this->getAppName($record['context'])) { $this->setNewRelicAppName($appName); } - if (null !== ($transactionName = $this->getTransactionName($record->context))) { + if ($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); @@ -91,8 +107,8 @@ protected function write(LogRecord $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); @@ -106,6 +122,8 @@ protected function write(LogRecord $record): void /** * Checks whether the NewRelic extension is enabled in the system. + * + * @return bool */ protected function isNewRelicEnabled(): bool { @@ -159,7 +177,8 @@ protected function setNewRelicTransactionName(string $transactionName): void } /** - * @param mixed $value + * @param string $key + * @param mixed $value */ protected function setNewRelicParameter(string $key, $value): void { @@ -171,7 +190,7 @@ protected function setNewRelicParameter(string $key, $value): void } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php index d9fea180c..1ddf0beb9 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/NoopHandler.php @@ -11,8 +11,6 @@ namespace Monolog\Handler; -use Monolog\LogRecord; - /** * No-op * @@ -25,17 +23,17 @@ class NoopHandler extends Handler { /** - * @inheritDoc + * {@inheritDoc} */ - public function isHandling(LogRecord $record): bool + public function isHandling(array $record): bool { return true; } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { return false; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php index 1aa84e4f8..e75ee0c6e 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/NullHandler.php @@ -11,10 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; -use Psr\Log\LogLevel; use Monolog\Logger; -use Monolog\LogRecord; +use Psr\Log\LogLevel; /** * Blackhole @@ -23,34 +21,40 @@ * 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 { - private Level $level; + /** + * @var int + */ + private $level; /** - * @param string|int|Level $level The minimum logging level at which this handler will be triggered + * @param string|int $level The minimum logging level at which this handler will be triggered * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function __construct(string|int|Level $level = Level::Debug) + public function __construct($level = Logger::DEBUG) { $this->level = Logger::toMonologLevel($level); } /** - * @inheritDoc + * {@inheritDoc} */ - public function isHandling(LogRecord $record): bool + public function isHandling(array $record): bool { - return $record->level->value >= $this->level->value; + return $record['level'] >= $this->level; } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { - return $record->level->value >= $this->level->value; + return $record['level'] >= $this->level; } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php index a72b7a11d..22068c9a3 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/OverflowHandler.php @@ -11,9 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * Handler to only pass log messages when a certain threshold of number of messages is reached. @@ -28,7 +27,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, [Level::Warning->value => 10, Level::Error->value => 5]); + * $overflow = new OverflowHandler($handler, [Logger::WARNING => 10, Logger::ERROR => 5]); * * $log->pushHandler($overflow); *``` @@ -37,25 +36,36 @@ */ class OverflowHandler extends AbstractHandler implements FormattableHandlerInterface { - private HandlerInterface $handler; - - /** @var array */ - private array $thresholdMap = []; + /** @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, + ]; /** * Buffer of all messages passed to the handler before the threshold was reached * * @var mixed[][] */ - private array $buffer = []; + private $buffer = []; /** - * @param array $thresholdMap Dictionary of log level value => threshold + * @param HandlerInterface $handler + * @param int[] $thresholdMap Dictionary of logger level => threshold */ public function __construct( HandlerInterface $handler, array $thresholdMap = [], - $level = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true ) { $this->handler = $handler; @@ -75,15 +85,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(LogRecord $record): bool + public function handle(array $record): bool { - if ($record->level->isLowerThan($this->level)) { + if ($record['level'] < $this->level) { return false; } - $level = $record->level->value; + $level = $record['level']; if (!isset($this->thresholdMap[$level])) { $this->thresholdMap[$level] = 0; @@ -112,7 +122,7 @@ public function handle(LogRecord $record): bool } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -126,7 +136,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php index 8aa78e4c4..23a1d1178 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/PHPConsoleHandler.php @@ -13,13 +13,11 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; +use Monolog\Logger; 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" @@ -39,59 +37,14 @@ * 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 { - /** - * @phpstan-var Options - */ - private array $options = [ + /** @var array */ + private $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 @@ -114,15 +67,15 @@ class PHPConsoleHandler extends AbstractProcessingHandler 'dataStorage' => null, // \PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ) ]; - private Connector $connector; + /** @var Connector */ + private $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, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::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'); @@ -133,16 +86,14 @@ public function __construct(array $options = [], ?Connector $connector = null, i } /** - * @param array $options - * @return array + * @param array $options * - * @phpstan-param InputOptions $options - * @phpstan-return Options + * @return array */ private function initOptions(array $options): array { $wrongOptions = array_diff(array_keys($options), array_keys($this->options)); - if (\count($wrongOptions) > 0) { + if ($wrongOptions) { throw new \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions)); } @@ -151,8 +102,8 @@ private function initOptions(array $options): array private function initConnector(?Connector $connector = null): Connector { - if (null === $connector) { - if ($this->options['dataStorage'] instanceof Storage) { + if (!$connector) { + if ($this->options['dataStorage']) { Connector::setPostponeStorage($this->options['dataStorage']); } $connector = Connector::getInstance(); @@ -169,22 +120,22 @@ private function initConnector(?Connector $connector = null): Connector $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']); $handler->start(); } - if (null !== $this->options['sourcesBasePath']) { + if ($this->options['sourcesBasePath']) { $connector->setSourcesBasePath($this->options['sourcesBasePath']); } - if (null !== $this->options['serverEncoding']) { + if ($this->options['serverEncoding']) { $connector->setServerEncoding($this->options['serverEncoding']); } - if (null !== $this->options['password']) { + if ($this->options['password']) { $connector->setPassword($this->options['password']); } if ($this->options['enableSslOnlyMode']) { $connector->enableSslOnlyMode(); } - if (\count($this->options['ipMasks']) > 0) { + if ($this->options['ipMasks']) { $connector->setAllowedIpMasks($this->options['ipMasks']); } - if (null !== $this->options['headersLimit'] && $this->options['headersLimit'] > 0) { + if ($this->options['headersLimit']) { $connector->setHeadersLimit($this->options['headersLimit']); } if ($this->options['detectDumpTraceAndSource']) { @@ -217,7 +168,7 @@ public function getOptions(): array return $this->options; } - public function handle(LogRecord $record): bool + public function handle(array $record): bool { if ($this->options['enabled'] && $this->connector->isActiveClient()) { return parent::handle($record); @@ -229,39 +180,48 @@ public function handle(LogRecord $record): bool /** * Writes the record down to the log of the implementing handler */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - if ($record->level->isLowerThan(Level::Notice)) { + if ($record['level'] < Logger::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); } } - private function handleDebugRecord(LogRecord $record): void + /** + * @phpstan-param Record $record + */ + private function handleDebugRecord(array $record): void { - [$tags, $filteredContext] = $this->getRecordTags($record); - $message = $record->message; - if (\count($filteredContext) > 0) { - $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($filteredContext)), null, true); + $tags = $this->getRecordTags($record); + $message = $record['message']; + if ($record['context']) { + $message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($record['context'])), null, true); } $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']); } - private function handleExceptionRecord(LogRecord $record): void + /** + * @phpstan-param Record $record + */ + private function handleExceptionRecord(array $record): void { - $this->connector->getErrorsDispatcher()->dispatchException($record->context['exception']); + $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']); } - private function handleErrorRecord(LogRecord $record): void + /** + * @phpstan-param Record $record + */ + private function handleErrorRecord(array $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'] @@ -269,32 +229,32 @@ private function handleErrorRecord(LogRecord $record): void } /** - * @return array{string, mixed[]} + * @phpstan-param Record $record + * @return string */ - private function getRecordTags(LogRecord $record): array + private function getRecordTags(array &$record) { $tags = null; - $filteredContext = []; - if ($record->context !== []) { - $filteredContext = $record->context; + if (!empty($record['context'])) { + $context = & $record['context']; foreach ($this->options['debugTagsKeysInContext'] as $key) { - if (isset($filteredContext[$key])) { - $tags = $filteredContext[$key]; + if (!empty($context[$key])) { + $tags = $context[$key]; if ($key === 0) { - array_shift($filteredContext); + array_shift($context); } else { - unset($filteredContext[$key]); + unset($context[$key]); } break; } } } - return [$tags ?? $record->level->toPsrLogLevel(), $filteredContext]; + return $tags ?: strtolower($record['level_name']); } /** - * @inheritDoc + * {@inheritDoc} */ protected function getDefaultFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php index 9edc9ac54..8a8cf1be6 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ProcessHandler.php @@ -11,8 +11,7 @@ namespace Monolog\Handler; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * Stores to STDIN of any process, specified by a command. @@ -34,14 +33,20 @@ class ProcessHandler extends AbstractProcessingHandler */ private $process; - private string $command; + /** + * @var string + */ + private $command; - private ?string $cwd; + /** + * @var string|null + */ + private $cwd; /** * @var resource[] */ - private array $pipes = []; + private $pipes = []; /** * @var array @@ -58,7 +63,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, int|string|Level $level = Level::Debug, bool $bubble = true, ?string $cwd = null) + public function __construct(string $command, $level = Logger::DEBUG, bool $bubble = true, ?string $cwd = null) { if ($command === '') { throw new \InvalidArgumentException('The command argument must be a non-empty string.'); @@ -78,14 +83,14 @@ public function __construct(string $command, int|string|Level $level = Level::De * * @throws \UnexpectedValueException */ - protected function write(LogRecord $record): void + protected function write(array $record): void { $this->ensureProcessIsStarted(); - $this->writeProcessInput($record->formatted); + $this->writeProcessInput($record['formatted']); $errors = $this->readProcessErrors(); - if ($errors !== '') { + if (empty($errors) === false) { throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors)); } } @@ -129,7 +134,7 @@ private function handleStartupErrors(): void $errors = $this->readProcessErrors(); - if (is_resource($this->process) === false || $errors !== '') { + if (is_resource($this->process) === false || empty($errors) === false) { throw new \UnexpectedValueException( sprintf('The process "%s" could not be opened: ' . $errors, $this->command) ); @@ -171,7 +176,7 @@ protected function writeProcessInput(string $string): void } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php index 9fb290faa..3adec7a4d 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerInterface.php @@ -12,19 +12,20 @@ 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. * - * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback + * @psalm-param ProcessorInterface|callable(Record): Record $callback * * @param ProcessorInterface|callable $callback * @return HandlerInterface self @@ -34,7 +35,7 @@ public function pushProcessor(callable $callback): HandlerInterface; /** * Removes the processor on top of the stack and returns it. * - * @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord) $callback + * @psalm-return ProcessorInterface|callable(Record): Record $callback * * @throws \LogicException In case the processor stack is empty * @return callable|ProcessorInterface diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php index 74eeddddc..9ef6e301c 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ProcessableHandlerTrait.php @@ -13,23 +13,24 @@ 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<(callable(LogRecord): LogRecord)|ProcessorInterface> + * @phpstan-var array */ - protected array $processors = []; + protected $processors = []; /** - * @inheritDoc + * {@inheritDoc} */ public function pushProcessor(callable $callback): HandlerInterface { @@ -39,18 +40,24 @@ public function pushProcessor(callable $callback): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function popProcessor(): callable { - if (\count($this->processors) === 0) { + if (!$this->processors) { throw new \LogicException('You tried to pop from an empty processor stack.'); } return array_shift($this->processors); } - protected function processRecord(LogRecord $record): LogRecord + /** + * Processes a record. + * + * @phpstan-param Record $record + * @phpstan-return Record + */ + protected function processRecord(array $record): array { foreach ($this->processors as $processor) { $record = $processor($record); diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php index 6599a83b4..36e19cccf 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php @@ -11,10 +11,9 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Psr\Log\LoggerInterface; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * Proxies log messages to an existing PSR-3 compliant logger. @@ -29,15 +28,20 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface { /** * PSR-3 compliant logger + * + * @var LoggerInterface */ - protected LoggerInterface $logger; + protected $logger; - protected FormatterInterface|null $formatter = null; + /** + * @var FormatterInterface|null + */ + protected $formatter; /** * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied */ - public function __construct(LoggerInterface $logger, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true) { parent::__construct($level, $bubble); @@ -45,19 +49,19 @@ public function __construct(LoggerInterface $logger, int|string|Level $level = L } /** - * @inheritDoc + * {@inheritDoc} */ - public function handle(LogRecord $record): bool + public function handle(array $record): bool { if (!$this->isHandling($record)) { return false; } - if ($this->formatter !== null) { + if ($this->formatter) { $formatted = $this->formatter->format($record); - $this->logger->log($record->level->toPsrLogLevel(), (string) $formatted, $record->context); + $this->logger->log(strtolower($record['level_name']), (string) $formatted, $record['context']); } else { - $this->logger->log($record->level->toPsrLogLevel(), $record->message, $record->context); + $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']); } return false === $this->bubble; @@ -65,6 +69,8 @@ public function handle(LogRecord $record): bool /** * Sets the formatter. + * + * @param FormatterInterface $formatter */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -75,10 +81,12 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface /** * Gets the formatter. + * + * @return FormatterInterface */ public function getFormatter(): FormatterInterface { - if ($this->formatter === null) { + if (!$this->formatter) { throw new \LogicException('No formatter has been set and this handler does not have a default formatter'); } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php index 615f12194..fed2303d7 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/PushoverHandler.php @@ -11,45 +11,48 @@ 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 { - private string $token; - + /** @var string */ + private $token; /** @var array */ - 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; + 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; /** * All parameters that can be sent to Pushover * @see https://pushover.net/api * @var array */ - private array $parameterNames = [ + private $parameterNames = [ 'token' => true, 'user' => true, 'message' => true, @@ -70,42 +73,40 @@ class PushoverHandler extends SocketHandler * @see https://pushover.net/api#sounds * @var string[] */ - private array $sounds = [ + private $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 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 - * + * @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). * * @phpstan-param string|array $users - * @phpstan-param value-of|value-of|Level|LogLevel::* $highPriorityLevel - * @phpstan-param value-of|value-of|Level|LogLevel::* $emergencyLevel + * @phpstan-param Level|LevelName|LogLevel::* $highPriorityLevel + * @phpstan-param Level|LevelName|LogLevel::* $emergencyLevel */ public function __construct( string $token, $users, ?string $title = null, - int|string|Level $level = Level::Critical, + $level = Logger::CRITICAL, bool $bubble = true, bool $useSSL = true, - int|string|Level $highPriorityLevel = Level::Critical, - int|string|Level $emergencyLevel = Level::Emergency, + $highPriorityLevel = Logger::CRITICAL, + $emergencyLevel = Logger::EMERGENCY, int $retry = 30, int $expire = 25200, bool $persistent = false, @@ -128,29 +129,32 @@ 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(LogRecord $record): string + protected function generateDataStream(array $record): string { $content = $this->buildContent($record); return $this->buildHeader($content) . $content; } - private function buildContent(LogRecord $record): string + /** + * @phpstan-param FormattedRecord $record + */ + private function buildContent(array $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, @@ -160,23 +164,23 @@ private function buildContent(LogRecord $record): string 'timestamp' => $timestamp, ]; - if ($record->level->value >= $this->emergencyLevel->value) { + if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) { $dataArray['priority'] = 2; $dataArray['retry'] = $this->retry; $dataArray['expire'] = $this->expire; - } elseif ($record->level->value >= $this->highPriorityLevel->value) { + } elseif (isset($record['level']) && $record['level'] >= $this->highPriorityLevel) { $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, true)) { + if (isset($dataArray['sound']) && !in_array($dataArray['sound'], $this->sounds)) { unset($dataArray['sound']); } @@ -194,7 +198,7 @@ private function buildHeader(string $content): string return $header; } - protected function write(LogRecord $record): void + protected function write(array $record): void { foreach ($this->users as $user) { $this->user = $user; @@ -207,39 +211,35 @@ protected function write(LogRecord $record): void } /** - * @param int|string|Level|LogLevel::* $level - * @return $this + * @param int|string $value * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $value */ - public function setHighPriorityLevel(int|string|Level $level): self + public function setHighPriorityLevel($value): self { - $this->highPriorityLevel = Logger::toMonologLevel($level); + $this->highPriorityLevel = Logger::toMonologLevel($value); return $this; } /** - * @param int|string|Level|LogLevel::* $level - * @return $this + * @param int|string $value * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $value */ - public function setEmergencyLevel(int|string|Level $level): self + public function setEmergencyLevel($value): self { - $this->emergencyLevel = Logger::toMonologLevel($level); + $this->emergencyLevel = Logger::toMonologLevel($value); return $this; } /** * Use the formatted message? - * - * @return $this */ - public function useFormattedMessage(bool $useFormattedMessage): self + public function useFormattedMessage(bool $value): self { - $this->useFormattedMessage = $useFormattedMessage; + $this->useFormattedMessage = $value; return $this; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php index 5eee5dc69..91d16eaf6 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/RedisHandler.php @@ -13,10 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; -use Monolog\LogRecord; -use Predis\Client as Predis; -use Redis; +use Monolog\Logger; /** * Logs to a Redis key using rpush @@ -28,21 +25,29 @@ * $log->pushHandler($redis); * * @author Thomas Tourlourat + * + * @phpstan-import-type FormattedRecord from AbstractProcessingHandler */ class RedisHandler extends AbstractProcessingHandler { - /** @var Predis|Redis */ - private Predis|Redis $redisClient; - private string $redisKey; - protected int $capSize; + /** @var \Predis\Client<\Predis\Client>|\Redis */ + private $redisClient; + /** @var string */ + private $redisKey; + /** @var int */ + protected $capSize; /** - * @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 + * @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 */ - public function __construct(Predis|Redis $redis, string $key, int|string|Level $level = Level::Debug, bool $bubble = true, int $capSize = 0) + public function __construct($redis, string $key, $level = Logger::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; @@ -51,41 +56,43 @@ public function __construct(Predis|Redis $redis, string $key, int|string|Level $ } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - if ($this->capSize > 0) { + if ($this->capSize) { $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(LogRecord $record): void + protected function writeCapped(array $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/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php index fa8e9e9ff..7789309c1 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/RedisPubSubHandler.php @@ -13,10 +13,7 @@ use Monolog\Formatter\LineFormatter; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; -use Monolog\LogRecord; -use Predis\Client as Predis; -use Redis; +use Monolog\Logger; /** * Sends the message to a Redis Pub/Sub channel using PUBLISH @@ -24,23 +21,28 @@ * usage example: * * $log = new Logger('application'); - * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Level::Warning); + * $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Logger::WARNING); * $log->pushHandler($redis); * * @author Gaëtan Faugère */ class RedisPubSubHandler extends AbstractProcessingHandler { - /** @var Predis|Redis */ - private Predis|Redis $redisClient; - private string $channelKey; + /** @var \Predis\Client<\Predis\Client>|\Redis */ + private $redisClient; + /** @var string */ + private $channelKey; /** - * @param Predis|Redis $redis The redis instance - * @param string $key The channel key to publish records to + * @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance + * @param string $key The channel key to publish records to */ - public function __construct(Predis|Redis $redis, string $key, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($redis, string $key, $level = Logger::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; @@ -48,15 +50,15 @@ public function __construct(Predis|Redis $redis, string $key, int|string|Level $ } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $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/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php index 1d124723b..adcc9395a 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/RollbarHandler.php @@ -11,10 +11,9 @@ namespace Monolog\Handler; -use Monolog\Level; use Rollbar\RollbarLogger; use Throwable; -use Monolog\LogRecord; +use Monolog\Logger; /** * Sends errors to Rollbar @@ -34,19 +33,37 @@ */ class RollbarHandler extends AbstractProcessingHandler { - protected RollbarLogger $rollbarLogger; + /** + * @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', + ]; /** * Records whether any log records have been added since the last flush of the rollbar notifier + * + * @var bool */ - private bool $hasRecords = false; + private $hasRecords = false; - protected bool $initialized = false; + /** @var bool */ + protected $initialized = false; /** * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token */ - public function __construct(RollbarLogger $rollbarLogger, int|string|Level $level = Level::Error, bool $bubble = true) + public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true) { $this->rollbarLogger = $rollbarLogger; @@ -54,41 +71,22 @@ public function __construct(RollbarLogger $rollbarLogger, int|string|Level $leve } /** - * 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 + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { if (!$this->initialized) { // __destructor() doesn't get called on Fatal errors - register_shutdown_function([$this, 'close']); + register_shutdown_function(array($this, 'close')); $this->initialized = true; } - $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'), + $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'), ]); if (isset($context['exception']) && $context['exception'] instanceof Throwable) { @@ -96,7 +94,7 @@ protected function write(LogRecord $record): void unset($context['exception']); $toLog = $exception; } else { - $toLog = $record->message; + $toLog = $record['message']; } // @phpstan-ignore-next-line @@ -114,7 +112,7 @@ public function flush(): void } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { @@ -122,9 +120,9 @@ public function close(): void } /** - * @inheritDoc + * {@inheritDoc} */ - public function reset(): void + public function reset() { $this->flush(); diff --git a/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php index 86240b44f..17745d221 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/RotatingFileHandler.php @@ -12,9 +12,8 @@ namespace Monolog\Handler; use InvalidArgumentException; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Stores logs to files that are rotated every day and a limited number of files are kept. @@ -31,30 +30,38 @@ class RotatingFileHandler extends StreamHandler public const FILE_PER_MONTH = 'Y-m'; public const FILE_PER_YEAR = 'Y'; - protected string $filename; - protected int $maxFiles; - protected bool|null $mustRotate = null; - protected \DateTimeImmutable $nextRotation; - protected string $filenameFormat; - protected string $dateFormat; + /** @var string */ + protected $filename; + /** @var int */ + protected $maxFiles; + /** @var bool */ + protected $mustRotate; + /** @var \DateTimeImmutable */ + protected $nextRotation; + /** @var string */ + protected $filenameFormat; + /** @var string */ + protected $dateFormat; /** - * @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 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 */ - public function __construct(string $filename, int $maxFiles = 0, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false, string $dateFormat = self::FILE_PER_DAY, string $filenameFormat = '{filename}-{date}') + public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) { $this->filename = Utils::canonicalizePath($filename); $this->maxFiles = $maxFiles; - $this->setFilenameFormat($filenameFormat, $dateFormat); - $this->nextRotation = $this->getNextRotation(); + $this->nextRotation = new \DateTimeImmutable('tomorrow'); + $this->filenameFormat = '{filename}-{date}'; + $this->dateFormat = static::FILE_PER_DAY; parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking); } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { @@ -66,9 +73,9 @@ public function close(): void } /** - * @inheritDoc + * {@inheritDoc} */ - public function reset(): void + public function reset() { parent::reset(); @@ -77,18 +84,23 @@ public function reset(): void } } - /** - * @return $this - */ public function setFilenameFormat(string $filenameFormat, string $dateFormat): self { - $this->setDateFormat($dateFormat); + if (!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") '. + 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '. + 'date formats using slashes, underscores and/or dots instead of dashes.' + ); + } if (substr_count($filenameFormat, '{date}') === 0) { throw new InvalidArgumentException( 'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.' ); } $this->filenameFormat = $filenameFormat; + $this->dateFormat = $dateFormat; $this->url = $this->getTimedFilename(); $this->close(); @@ -96,16 +108,16 @@ public function setFilenameFormat(string $filenameFormat, string $dateFormat): s } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $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(); } @@ -120,7 +132,7 @@ protected function rotate(): void { // update filename $this->url = $this->getTimedFilename(); - $this->nextRotation = $this->getNextRotation(); + $this->nextRotation = new \DateTimeImmutable('tomorrow'); // skip GC of old logs if files are unlimited if (0 === $this->maxFiles) { @@ -164,7 +176,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'])) { @@ -184,7 +196,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']; @@ -192,26 +204,4 @@ protected function getGlobPattern(): string return $glob; } - - protected function setDateFormat(string $dateFormat): void - { - 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") '. - 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '. - 'date formats using slashes, underscores and/or dots instead of dashes.' - ); - } - $this->dateFormat = $dateFormat; - } - - protected function getNextRotation(): \DateTimeImmutable - { - return match (str_replace(['/','_','.'], '-', $this->dateFormat)) { - self::FILE_PER_MONTH => (new \DateTimeImmutable('first day of next month'))->setTime(0, 0, 0), - self::FILE_PER_YEAR => (new \DateTimeImmutable('first day of January next year'))->setTime(0, 0, 0), - default => (new \DateTimeImmutable('tomorrow'))->setTime(0, 0, 0), - }; - } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php index 511ec5854..c128a32d1 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SamplingHandler.php @@ -11,9 +11,7 @@ namespace Monolog\Handler; -use Closure; use Monolog\Formatter\FormatterInterface; -use Monolog\LogRecord; /** * Sampling handler @@ -28,42 +26,52 @@ * * @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; /** - * Handler or factory Closure($record, $this) - * - * @phpstan-var (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface + * @var HandlerInterface|callable + * @phpstan-var HandlerInterface|callable(Record|array{level: Level}|null, HandlerInterface): HandlerInterface */ - protected Closure|HandlerInterface $handler; + protected $handler; - protected int $factor; + /** + * @var int $factor + */ + protected $factor; /** - * @phpstan-param (Closure(LogRecord|null, HandlerInterface): HandlerInterface)|HandlerInterface $handler + * @psalm-param HandlerInterface|callable(Record|array{level: Level}|null, HandlerInterface): HandlerInterface $handler * - * @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) + * @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) */ - public function __construct(Closure|HandlerInterface $handler, int $factor) + public function __construct($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(LogRecord $record): bool + public function isHandling(array $record): bool { return $this->getHandler($record)->isHandling($record); } - public function handle(LogRecord $record): bool + public function handle(array $record): bool { if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) { - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } @@ -76,23 +84,26 @@ public function handle(LogRecord $record): bool /** * Return the nested handler * - * If the handler was provided as a factory, this will trigger the handler's instantiation. + * 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 */ - public function getHandler(LogRecord $record = null): HandlerInterface + public function getHandler(array $record = null) { if (!$this->handler instanceof HandlerInterface) { - $handler = ($this->handler)($record, $this); - if (!$handler instanceof HandlerInterface) { - throw new \RuntimeException("The factory Closure should return a HandlerInterface"); + $this->handler = ($this->handler)($record, $this); + if (!$this->handler instanceof HandlerInterface) { + throw new \RuntimeException("The factory callable should return a HandlerInterface"); } - $this->handler = $handler; } return $this->handler; } /** - * @inheritDoc + * {@inheritDoc} */ public function setFormatter(FormatterInterface $formatter): HandlerInterface { @@ -107,7 +118,7 @@ public function setFormatter(FormatterInterface $formatter): HandlerInterface } /** - * @inheritDoc + * {@inheritDoc} */ public function getFormatter(): FormatterInterface { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php index b8f574bb4..1280ee703 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SendGridHandler.php @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; /** * 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,29 +22,33 @@ class SendGridHandler extends MailHandler { /** * The SendGrid API User + * @var string */ - protected string $apiUser; + protected $apiUser; /** * The SendGrid API Key + * @var string */ - protected string $apiKey; + protected $apiKey; /** * The email addresses to which the message will be sent + * @var string */ - protected string $from; + protected $from; /** * The email addresses to which the message will be sent * @var string[] */ - protected array $to; + protected $to; /** * The subject of the email + * @var string */ - protected string $subject; + protected $subject; /** * @param string $apiUser The SendGrid API User @@ -52,10 +56,8 @@ 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, string|array $to, string $subject, int|string|Level $level = Level::Error, bool $bubble = true) + public function __construct(string $apiUser, string $apiKey, string $from, $to, string $subject, $level = Logger::ERROR, bool $bubble = true) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the SendGridHandler'); @@ -70,7 +72,7 @@ public function __construct(string $apiUser, string $apiKey, string $from, strin } /** - * @inheritDoc + * {@inheritDoc} */ protected function send(string $content, array $records): void { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php b/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php index 147d8f80b..71a410946 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/Slack/SlackRecord.php @@ -11,11 +11,10 @@ namespace Monolog\Handler\Slack; -use Monolog\Level; +use Monolog\Logger; 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. @@ -24,6 +23,9 @@ * @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 { @@ -37,43 +39,55 @@ class SlackRecord /** * Slack channel (encoded ID or name) + * @var string|null */ - private string|null $channel; + private $channel; /** * Name of a bot + * @var string|null */ - private string|null $username; + private $username; /** * User icon e.g. 'ghost', 'http://example.com/user.png' + * @var string|null */ - private string|null $userIcon; + private $userIcon; /** * Whether the message should be added to Slack as attachment (plain text otherwise) + * @var bool */ - private bool $useAttachment; + private $useAttachment; /** * Whether the the context/extra messages added to Slack as attachments are in a short style + * @var bool */ - private bool $useShortAttachment; + private $useShortAttachment; /** * Whether the attachment should include context and extra data + * @var bool */ - private bool $includeContextAndExtra; + private $includeContextAndExtra; /** * Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] * @var string[] */ - private array $excludeFields; + private $excludeFields; - private FormatterInterface|null $formatter; + /** + * @var ?FormatterInterface + */ + private $formatter; - private NormalizerFormatter $normalizerFormatter; + /** + * @var NormalizerFormatter + */ + private $normalizerFormatter; /** * @param string[] $excludeFields @@ -85,7 +99,7 @@ public function __construct( ?string $userIcon = null, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - array $excludeFields = [], + array $excludeFields = array(), FormatterInterface $formatter = null ) { $this @@ -107,76 +121,77 @@ public function __construct( * Returns required data in format that Slack * is expecting. * + * @phpstan-param FormattedRecord $record * @phpstan-return mixed[] */ - public function getSlackData(LogRecord $record): array + public function getSlackData(array $record): array { - $dataArray = []; + $dataArray = array(); + $record = $this->removeExcludedFields($record); - if ($this->username !== null) { + if ($this->username) { $dataArray['username'] = $this->username; } - if ($this->channel !== null) { + if ($this->channel) { $dataArray['channel'] = $this->channel; } - if ($this->formatter !== null && !$this->useAttachment) { + if ($this->formatter && !$this->useAttachment) { + /** @phpstan-ignore-next-line */ $message = $this->formatter->format($record); } else { - $message = $record->message; + $message = $record['message']; } - $recordData = $this->removeExcludedFields($record); - if ($this->useAttachment) { - $attachment = [ - 'fallback' => $message, - 'text' => $message, - 'color' => $this->getAttachmentColor($record->level), - 'fields' => [], - 'mrkdwn_in' => ['fields'], - 'ts' => $recordData['datetime']->getTimestamp(), + $attachment = array( + 'fallback' => $message, + 'text' => $message, + 'color' => $this->getAttachmentColor($record['level']), + 'fields' => array(), + 'mrkdwn_in' => array('fields'), + 'ts' => $record['datetime']->getTimestamp(), 'footer' => $this->username, 'footer_icon' => $this->userIcon, - ]; + ); if ($this->useShortAttachment) { - $attachment['title'] = $recordData['level_name']; + $attachment['title'] = $record['level_name']; } else { $attachment['title'] = 'Message'; - $attachment['fields'][] = $this->generateAttachmentField('Level', $recordData['level_name']); + $attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']); } if ($this->includeContextAndExtra) { - foreach (['extra', 'context'] as $key) { - if (!isset($recordData[$key]) || \count($recordData[$key]) === 0) { + foreach (array('extra', 'context') as $key) { + if (empty($record[$key])) { continue; } if ($this->useShortAttachment) { $attachment['fields'][] = $this->generateAttachmentField( - $key, - $recordData[$key] + (string) $key, + $record[$key] ); } else { // Add all extra fields as individual fields in attachment $attachment['fields'] = array_merge( $attachment['fields'], - $this->generateAttachmentFields($recordData[$key]) + $this->generateAttachmentFields($record[$key]) ); } } } - $dataArray['attachments'] = [$attachment]; + $dataArray['attachments'] = array($attachment); } else { $dataArray['text'] = $message; } - if ($this->userIcon !== null) { - if (false !== ($iconUrl = filter_var($this->userIcon, FILTER_VALIDATE_URL))) { - $dataArray['icon_url'] = $iconUrl; + if ($this->userIcon) { + if (filter_var($this->userIcon, FILTER_VALIDATE_URL)) { + $dataArray['icon_url'] = $this->userIcon; } else { $dataArray['icon_emoji'] = ":{$this->userIcon}:"; } @@ -189,14 +204,18 @@ public function getSlackData(LogRecord $record): array * Returns a Slack message attachment color associated with * provided level. */ - public function getAttachmentColor(Level $level): string + public function getAttachmentColor(int $level): string { - 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 - }; + 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; + } } /** @@ -206,13 +225,13 @@ public function getAttachmentColor(Level $level): string */ public function stringify(array $fields): string { - /** @var array $normalized */ - $normalized = $this->normalizerFormatter->normalizeValue($fields); + /** @var Record $fields */ + $normalized = $this->normalizerFormatter->format($fields); - $hasSecondDimension = \count(array_filter($normalized, 'is_array')) > 0; - $hasOnlyNonNumericKeys = \count(array_filter(array_keys($normalized), 'is_numeric')) === 0; + $hasSecondDimension = count(array_filter($normalized, 'is_array')); + $hasNonNumericKeys = !count(array_filter(array_keys($normalized), 'is_numeric')); - return $hasSecondDimension || $hasOnlyNonNumericKeys + return $hasSecondDimension || $hasNonNumericKeys ? Utils::jsonEncode($normalized, JSON_PRETTY_PRINT|Utils::DEFAULT_JSON_FLAGS) : Utils::jsonEncode($normalized, Utils::DEFAULT_JSON_FLAGS); } @@ -221,7 +240,8 @@ public function stringify(array $fields): string * Channel used by the bot when posting * * @param ?string $channel - * @return $this + * + * @return static */ public function setChannel(?string $channel = null): self { @@ -234,7 +254,8 @@ public function setChannel(?string $channel = null): self * Username used by the bot when posting * * @param ?string $username - * @return $this + * + * @return static */ public function setUsername(?string $username = null): self { @@ -243,9 +264,6 @@ public function setUsername(?string $username = null): self return $this; } - /** - * @return $this - */ public function useAttachment(bool $useAttachment = true): self { $this->useAttachment = $useAttachment; @@ -253,9 +271,6 @@ public function useAttachment(bool $useAttachment = true): self return $this; } - /** - * @return $this - */ public function setUserIcon(?string $userIcon = null): self { $this->userIcon = $userIcon; @@ -267,9 +282,6 @@ public function setUserIcon(?string $userIcon = null): self return $this; } - /** - * @return $this - */ public function useShortAttachment(bool $useShortAttachment = false): self { $this->useShortAttachment = $useShortAttachment; @@ -277,9 +289,6 @@ public function useShortAttachment(bool $useShortAttachment = false): self return $this; } - /** - * @return $this - */ public function includeContextAndExtra(bool $includeContextAndExtra = false): self { $this->includeContextAndExtra = $includeContextAndExtra; @@ -293,7 +302,6 @@ public function includeContextAndExtra(bool $includeContextAndExtra = false): se /** * @param string[] $excludeFields - * @return $this */ public function excludeFields(array $excludeFields = []): self { @@ -302,9 +310,6 @@ public function excludeFields(array $excludeFields = []): self return $this; } - /** - * @return $this - */ public function setFormatter(?FormatterInterface $formatter = null): self { $this->formatter = $formatter; @@ -325,11 +330,11 @@ private function generateAttachmentField(string $title, $value): array ? sprintf('```%s```', substr($this->stringify($value), 0, 1990)) : $value; - return [ + return array( 'title' => ucfirst($title), 'value' => $value, 'short' => false, - ]; + ); } /** @@ -341,10 +346,10 @@ private function generateAttachmentField(string $title, $value): array */ private function generateAttachmentFields(array $data): array { - /** @var array $normalized */ - $normalized = $this->normalizerFormatter->normalizeValue($data); + /** @var Record $data */ + $normalized = $this->normalizerFormatter->format($data); - $fields = []; + $fields = array(); foreach ($normalized as $key => $value) { $fields[] = $this->generateAttachmentField((string) $key, $value); } @@ -355,14 +360,15 @@ 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(LogRecord $record): array + private function removeExcludedFields(array $record): array { - $recordData = $record->toArray(); foreach ($this->excludeFields as $field) { $keys = explode('.', $field); - $node = &$recordData; + $node = &$record; $lastKey = end($keys); foreach ($keys as $key) { if (!isset($node[$key])) { @@ -376,6 +382,6 @@ private function removeExcludedFields(LogRecord $record): array } } - return $recordData; + return $record; } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php index 1d9a17712..a648513e0 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackHandler.php @@ -12,28 +12,31 @@ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; +use Monolog\Logger; 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 string $token; + private $token; /** * Instance of the SlackRecord util class preparing data for Slack API. + * @var SlackRecord */ - private SlackRecord $slackRecord; + private $slackRecord; /** * @param string $token Slack API token @@ -52,11 +55,11 @@ public function __construct( ?string $username = null, bool $useAttachment = true, ?string $iconEmoji = null, - $level = Level::Critical, + $level = Logger::CRITICAL, bool $bubble = true, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - array $excludeFields = [], + array $excludeFields = array(), bool $persistent = false, float $timeout = 0.0, float $writingTimeout = 10.0, @@ -102,9 +105,9 @@ public function getToken(): string } /** - * @inheritDoc + * {@inheritDoc} */ - protected function generateDataStream(LogRecord $record): string + protected function generateDataStream(array $record): string { $content = $this->buildContent($record); @@ -113,8 +116,10 @@ protected function generateDataStream(LogRecord $record): string /** * Builds the body of API call + * + * @phpstan-param FormattedRecord $record */ - private function buildContent(LogRecord $record): string + private function buildContent(array $record): string { $dataArray = $this->prepareContentData($record); @@ -122,14 +127,15 @@ private function buildContent(LogRecord $record): string } /** + * @phpstan-param FormattedRecord $record * @return string[] */ - protected function prepareContentData(LogRecord $record): array + protected function prepareContentData(array $record): array { $dataArray = $this->slackRecord->getSlackData($record); $dataArray['token'] = $this->token; - if (isset($dataArray['attachments']) && is_array($dataArray['attachments']) && \count($dataArray['attachments']) > 0) { + if (!empty($dataArray['attachments'])) { $dataArray['attachments'] = Utils::jsonEncode($dataArray['attachments']); } @@ -151,9 +157,9 @@ private function buildHeader(string $content): string } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { parent::write($record); $this->finalizeWrite(); @@ -192,8 +198,6 @@ public function getFormatter(): FormatterInterface /** * Channel used by the bot when posting - * - * @return $this */ public function setChannel(string $channel): self { @@ -204,8 +208,6 @@ public function setChannel(string $channel): self /** * Username used by the bot when posting - * - * @return $this */ public function setUsername(string $username): self { @@ -214,9 +216,6 @@ public function setUsername(string $username): self return $this; } - /** - * @return $this - */ public function useAttachment(bool $useAttachment): self { $this->slackRecord->useAttachment($useAttachment); @@ -224,9 +223,6 @@ public function useAttachment(bool $useAttachment): self return $this; } - /** - * @return $this - */ public function setIconEmoji(string $iconEmoji): self { $this->slackRecord->setUserIcon($iconEmoji); @@ -234,9 +230,6 @@ public function setIconEmoji(string $iconEmoji): self return $this; } - /** - * @return $this - */ public function useShortAttachment(bool $useShortAttachment): self { $this->slackRecord->useShortAttachment($useShortAttachment); @@ -244,9 +237,6 @@ public function useShortAttachment(bool $useShortAttachment): self return $this; } - /** - * @return $this - */ public function includeContextAndExtra(bool $includeContextAndExtra): self { $this->slackRecord->includeContextAndExtra($includeContextAndExtra); @@ -256,7 +246,6 @@ public function includeContextAndExtra(bool $includeContextAndExtra): self /** * @param string[] $excludeFields - * @return $this */ public function excludeFields(array $excludeFields): self { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php index 6466ba3af..8ae3c7882 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SlackWebhookHandler.php @@ -12,10 +12,9 @@ namespace Monolog\Handler; use Monolog\Formatter\FormatterInterface; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; use Monolog\Handler\Slack\SlackRecord; -use Monolog\LogRecord; /** * Sends notifications through Slack Webhooks @@ -27,13 +26,15 @@ class SlackWebhookHandler extends AbstractProcessingHandler { /** * Slack Webhook token + * @var string */ - private string $webhookUrl; + private $webhookUrl; /** * Instance of the SlackRecord util class preparing data for Slack API. + * @var SlackRecord */ - private SlackRecord $slackRecord; + private $slackRecord; /** * @param string $webhookUrl Slack Webhook URL @@ -44,8 +45,6 @@ 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, @@ -55,9 +54,9 @@ public function __construct( ?string $iconEmoji = null, bool $useShortAttachment = false, bool $includeContextAndExtra = false, - $level = Level::Critical, + $level = Logger::CRITICAL, bool $bubble = true, - array $excludeFields = [] + array $excludeFields = array() ) { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the SlackWebhookHandler'); @@ -89,21 +88,21 @@ public function getWebhookUrl(): string } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { $postData = $this->slackRecord->getSlackData($record); $postString = Utils::jsonEncode($postData); $ch = curl_init(); - $options = [ + $options = array( CURLOPT_URL => $this->webhookUrl, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, - CURLOPT_HTTPHEADER => ['Content-type: application/json'], + CURLOPT_HTTPHEADER => array('Content-type: application/json'), CURLOPT_POSTFIELDS => $postString, - ]; + ); if (defined('CURLOPT_SAFE_UPLOAD')) { $options[CURLOPT_SAFE_UPLOAD] = true; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php index 63f437f3f..21701afa2 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SocketHandler.php @@ -11,29 +11,41 @@ namespace Monolog\Handler; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * 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 { - private string $connectionString; - private float $connectionTimeout; + /** @var string */ + private $connectionString; + /** @var float */ + private $connectionTimeout; /** @var resource|null */ private $resource; - 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; + /** @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; /** * @param string $connectionString Socket connection string @@ -44,11 +56,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 = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, bool $persistent = false, float $timeout = 0.0, @@ -75,12 +87,12 @@ public function __construct( /** * Connect (if necessary) and write to the socket * - * @inheritDoc + * {@inheritDoc} * * @throws \UnexpectedValueException * @throws \RuntimeException */ - protected function write(LogRecord $record): void + protected function write(array $record): void { $this->connectIfNotConnected(); $data = $this->generateDataStream($record); @@ -110,8 +122,6 @@ public function closeSocket(): void /** * Set socket connection to be persistent. It only has effect before the connection is initiated. - * - * @return $this */ public function setPersistent(bool $persistent): self { @@ -124,7 +134,6 @@ public function setPersistent(bool $persistent): self * Set connection timeout. Only has effect before we connect. * * @see http://php.net/manual/en/function.fsockopen.php - * @return $this */ public function setConnectionTimeout(float $seconds): self { @@ -138,7 +147,6 @@ public function setConnectionTimeout(float $seconds): self * Set write timeout. Only has effect before we connect. * * @see http://php.net/manual/en/function.stream-set-timeout.php - * @return $this */ public function setTimeout(float $seconds): self { @@ -152,7 +160,6 @@ public function setTimeout(float $seconds): self * Set writing timeout. Only has effect during connection in the writing cycle. * * @param float $seconds 0 for no timeout - * @return $this */ public function setWritingTimeout(float $seconds): self { @@ -164,8 +171,6 @@ public function setWritingTimeout(float $seconds): self /** * Set chunk size. Only has effect during connection in the writing cycle. - * - * @return $this */ public function setChunkSize(int $bytes): self { @@ -208,6 +213,8 @@ public function getTimeout(): float /** * Get current local writing timeout + * + * @return float */ public function getWritingTimeout(): float { @@ -257,8 +264,10 @@ protected function fsockopen() * Wrapper to allow mocking * * @see http://php.net/manual/en/function.stream-set-timeout.php + * + * @return bool */ - protected function streamSetTimeout(): bool + protected function streamSetTimeout() { $seconds = floor($this->timeout); $microseconds = round(($this->timeout - $seconds) * 1e6); @@ -275,9 +284,9 @@ protected function streamSetTimeout(): bool * * @see http://php.net/manual/en/function.stream-set-chunk-size.php * - * @return int|false + * @return int|bool */ - protected function streamSetChunkSize(): int|bool + protected function streamSetChunkSize() { if (!is_resource($this->resource)) { throw new \LogicException('streamSetChunkSize called but $this->resource is not a resource'); @@ -293,9 +302,9 @@ protected function streamSetChunkSize(): int|bool /** * Wrapper to allow mocking * - * @return int|false + * @return int|bool */ - protected function fwrite(string $data): int|bool + protected function fwrite(string $data) { if (!is_resource($this->resource)) { throw new \LogicException('fwrite called but $this->resource is not a resource'); @@ -309,7 +318,7 @@ protected function fwrite(string $data): int|bool * * @return mixed[]|bool */ - protected function streamGetMetadata(): array|bool + protected function streamGetMetadata() { if (!is_resource($this->resource)) { throw new \LogicException('streamGetMetadata called but $this->resource is not a resource'); @@ -333,9 +342,12 @@ private function connectIfNotConnected(): void $this->connect(); } - protected function generateDataStream(LogRecord $record): string + /** + * @phpstan-param FormattedRecord $record + */ + protected function generateDataStream(array $record): string { - return (string) $record->formatted; + return (string) $record['formatted']; } /** @@ -375,7 +387,7 @@ private function setSocketTimeout(): void private function setStreamChunkSize(): void { - if (null !== $this->chunkSize && false === $this->streamSetChunkSize()) { + if ($this->chunkSize && !$this->streamSetChunkSize()) { throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()"); } } @@ -396,7 +408,7 @@ private function writeToSocket(string $data): void } $sent += $chunk; $socketInfo = $this->streamGetMetadata(); - if (is_array($socketInfo) && (bool) $socketInfo['timed_out']) { + if (is_array($socketInfo) && $socketInfo['timed_out']) { throw new \RuntimeException("Write timed-out"); } @@ -425,7 +437,7 @@ private function writingIsTimedOut(int $sent): bool usleep(100); } - if ((microtime(true) - (float) $this->lastWritingAt) >= $this->writingTimeout) { + if ((microtime(true) - $this->lastWritingAt) >= $this->writingTimeout) { $this->closeSocket(); return true; diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php index b4512a601..dcf282b45 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SqsHandler.php @@ -12,9 +12,8 @@ namespace Monolog\Handler; use Aws\Sqs\SqsClient; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Writes to any sqs queue. @@ -28,10 +27,12 @@ class SqsHandler extends AbstractProcessingHandler /** 100 KB in bytes - head message size for new error log */ protected const HEAD_MESSAGE_SIZE = 102400; - private SqsClient $client; - private string $queueUrl; + /** @var SqsClient */ + private $client; + /** @var string */ + private $queueUrl; - public function __construct(SqsClient $sqsClient, string $queueUrl, int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true) { parent::__construct($level, $bubble); @@ -40,15 +41,15 @@ public function __construct(SqsClient $sqsClient, string $queueUrl, int|string|L } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $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/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php index a87577c8d..82c048e1c 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php @@ -11,9 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Stores to any stream resource @@ -21,21 +20,29 @@ * 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; - /** 10MB */ + /** @const int 10MB */ protected const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024; - protected int $streamChunkSize; + /** @var int */ + protected $streamChunkSize; /** @var resource|null */ protected $stream; - protected string|null $url = null; - private string|null $errorMessage = null; - protected int|null $filePermission; - protected bool $useLocking; + /** @var ?string */ + protected $url = null; + /** @var ?string */ + private $errorMessage = null; + /** @var ?int */ + protected $filePermission; + /** @var bool */ + protected $useLocking; /** @var true|null */ - private bool|null $dirCreated = null; + private $dirCreated = null; /** * @param resource|string $stream If a missing path can't be created, an UnexpectedValueException will be thrown on first write @@ -44,7 +51,7 @@ class StreamHandler extends AbstractProcessingHandler * * @throws \InvalidArgumentException If stream is not a resource or string */ - public function __construct($stream, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) + public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false) { parent::__construct($level, $bubble); @@ -76,11 +83,11 @@ public function __construct($stream, int|string|Level $level = Level::Debug, boo } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { - if (null !== $this->url && is_resource($this->stream)) { + if ($this->url && is_resource($this->stream)) { fclose($this->stream); } $this->stream = null; @@ -99,21 +106,26 @@ 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(LogRecord $record): void + protected function write(array $record): void { if (!is_resource($this->stream)) { $url = $this->url; @@ -141,6 +153,10 @@ protected function write(LogRecord $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); @@ -156,10 +172,13 @@ protected function write(LogRecord $record): void /** * Write to stream * @param resource $stream + * @param array $record + * + * @phpstan-param FormattedRecord $record */ - protected function streamWrite($stream, LogRecord $record): void + protected function streamWrite($stream, array $record): void { - fwrite($stream, (string) $record->formatted); + fwrite($stream, (string) $record['formatted']); } private function customErrorHandler(int $code, string $msg): bool @@ -186,7 +205,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 (true === $this->dirCreated) { + if ($this->dirCreated) { return; } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php index 842b6577f..130e6f1f3 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SymfonyMailerHandler.php @@ -11,10 +11,7 @@ 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; @@ -26,20 +23,23 @@ * SymfonyMailerHandler uses Symfony's Mailer component to send the emails * * @author Jordi Boggiano + * + * @phpstan-import-type Record from \Monolog\Logger */ class SymfonyMailerHandler extends MailHandler { - protected MailerInterface|TransportInterface $mailer; - /** @var Email|Closure(string, LogRecord[]): Email */ - private Email|Closure $emailTemplate; + /** @var MailerInterface|TransportInterface */ + protected $mailer; + /** @var Email|callable(string, Record[]): Email */ + private $emailTemplate; /** - * @phpstan-param Email|Closure(string, LogRecord[]): Email $email + * @psalm-param Email|callable(string, Record[]): Email $email * * @param MailerInterface|TransportInterface $mailer The mailer to use - * @param Closure|Email $email An email template, the subject/body will be replaced + * @param callable|Email $email An email template, the subject/body will be replaced */ - public function __construct($mailer, Email|Closure $email, int|string|Level $level = Level::Error, bool $bubble = true) + public function __construct($mailer, $email, $level = Logger::ERROR, bool $bubble = true) { parent::__construct($level, $bubble); @@ -68,8 +68,10 @@ protected function getSubjectFormatter(?string $format): FormatterInterface /** * Creates instance of Email to be sent * - * @param string $content formatted email body to be sent - * @param LogRecord[] $records Log records that formed the content + * @param string $content formatted email body to be sent + * @param array $records Log records that formed the content + * + * @phpstan-param Record[] $records */ protected function buildMessage(string $content, array $records): Email { @@ -82,10 +84,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 instanceof LogRecord ? Utils::getRecordMessageForException($record) : '')); + throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it' . ($record ? Utils::getRecordMessageForException($record) : '')); } - if (\count($records) > 0) { + if ($records) { $subjectFormatter = $this->getSubjectFormatter($message->getSubject()); $message->subject($subjectFormatter->format($this->getHighestRecord($records))); } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php index 99507a170..1d543b7ec 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogHandler.php @@ -11,9 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** * Logs to syslog service. @@ -30,14 +29,17 @@ */ class SyslogHandler extends AbstractSyslogHandler { - protected string $ident; - protected int $logopts; + /** @var string */ + protected $ident; + /** @var int */ + protected $logopts; /** + * @param string $ident * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID */ - public function __construct(string $ident, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, int $logopts = LOG_PID) + public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID) { parent::__construct($facility, $level, $bubble); @@ -46,7 +48,7 @@ public function __construct(string $ident, string|int $facility = LOG_USER, int| } /** - * @inheritDoc + * {@inheritDoc} */ public function close(): void { @@ -54,11 +56,13 @@ public function close(): void } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - openlog($this->ident, $this->logopts, $this->facility); - syslog($this->toSyslogPriority($record->level), (string) $record->formatted); + 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']); } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php index 6a4833450..dbd8ef69d 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdp/UdpSocket.php @@ -18,9 +18,12 @@ class UdpSocket { protected const DATAGRAM_MAX_LENGTH = 65023; - protected string $ip; - protected int $port; - protected ?Socket $socket = null; + /** @var string */ + protected $ip; + /** @var int */ + protected $port; + /** @var resource|Socket|null */ + protected $socket = null; public function __construct(string $ip, int $port = 514) { @@ -28,20 +31,28 @@ public function __construct(string $ip, int $port = 514) $this->port = $port; } - public function write(string $line, string $header = ""): void + /** + * @param string $line + * @param string $header + * @return void + */ + public function write($line, $header = "") { $this->send($this->assembleMessage($line, $header)); } public function close(): void { - if ($this->socket instanceof Socket) { + if (is_resource($this->socket) || $this->socket instanceof Socket) { socket_close($this->socket); $this->socket = null; } } - protected function getSocket(): Socket + /** + * @return resource|Socket + */ + protected function getSocket() { if (null !== $this->socket) { return $this->socket; @@ -55,12 +66,12 @@ protected function getSocket(): Socket $protocol = IPPROTO_IP; } - $socket = socket_create($domain, SOCK_DGRAM, $protocol); - if ($socket instanceof Socket) { - return $this->socket = $socket; + $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'); } - throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create'); + return $this->socket; } protected function send(string $chunk): void diff --git a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php index 607409353..deaa19f80 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/SyslogUdpHandler.php @@ -12,9 +12,8 @@ namespace Monolog\Handler; use DateTimeInterface; +use Monolog\Logger; use Monolog\Handler\SyslogUdp\UdpSocket; -use Monolog\Level; -use Monolog\LogRecord; use Monolog\Utils; /** @@ -30,29 +29,31 @@ class SyslogUdpHandler extends AbstractSyslogHandler const RFC5424e = 2; /** @var array */ - private array $dateFormats = [ + private $dateFormats = array( self::RFC3164 => 'M d H:i:s', self::RFC5424 => \DateTime::RFC3339, self::RFC5424e => \DateTime::RFC3339_EXTENDED, - ]; + ); - protected UdpSocket $socket; - protected string $ident; + /** @var UdpSocket */ + protected $socket; + /** @var string */ + protected $ident; /** @var self::RFC* */ - protected int $rfc; + protected $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 when there is no socket extension + * @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 * * @phpstan-param self::RFC* $rfc */ - public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424) + public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Logger::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'); @@ -66,11 +67,11 @@ public function __construct(string $host, int $port = 514, string|int $facility $this->socket = new UdpSocket($host, $port); } - protected function write(LogRecord $record): void + protected function write(array $record): void { - $lines = $this->splitMessageIntoLines($record->formatted); + $lines = $this->splitMessageIntoLines($record['formatted']); - $header = $this->makeCommonSyslogHeader($this->toSyslogPriority($record->level), $record->datetime); + $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']], $record['datetime']); foreach ($lines as $line) { $this->socket->write($line, $header); @@ -95,7 +96,6 @@ 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,13 +109,11 @@ protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $date { $priority = $severity + $this->facility; - $pid = getmypid(); - if (false === $pid) { + if (!$pid = getmypid()) { $pid = '-'; } - $hostname = gethostname(); - if (false === $hostname) { + if (!$hostname = gethostname()) { $hostname = '-'; } @@ -142,8 +140,6 @@ protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $date /** * Inject your own socket, mainly used for testing - * - * @return $this */ public function setSocket(UdpSocket $socket): self { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php index feaa002fa..8912eba51 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/TelegramBotHandler.php @@ -12,27 +12,24 @@ namespace Monolog\Handler; use RuntimeException; -use Monolog\Level; +use Monolog\Logger; use Monolog\Utils; -use Monolog\LogRecord; /** - * Handler sends logs to Telegram using Telegram Bot API. + * Handler send logs to Telegram using Telegram Bot API. * * How to use: - * 1) Create a Telegram bot with https://telegram.me/BotFather; - * 2) Create a Telegram channel or a group where logs will be recorded; - * 3) Add the created bot from step 1 to the created channel/group from step 2. + * 1) Create telegram bot with https://telegram.me/BotFather + * 2) Create a telegram channel where logs will be recorded. + * 3) Add created bot from step 1 to the created channel from step 2. * - * In order to create an instance of TelegramBotHandler use - * 1. The Telegram bot API key from step 1 - * 2. The channel name with the `@` prefix if you created a public channel (e.g. `@my_public_channel`), - * or the channel ID with the `-100` prefix if you created a private channel (e.g. `-1001234567890`), - * or the group ID from step 2 (e.g. `-1234567890`). + * Use telegram bot API key from step 1 and channel name with '@' prefix from step 2 to create instance of TelegramBotHandler * * @link https://core.telegram.org/bots/api * * @author Mazur Alexandr + * + * @phpstan-import-type Record from \Monolog\Logger */ class TelegramBotHandler extends AbstractProcessingHandler { @@ -55,69 +52,69 @@ 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 string $apiKey; + private $apiKey; /** * Telegram channel name. * Since to start with '@' symbol as prefix. + * @var string */ - private string $channel; + private $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 string|null $parseMode; + private $parseMode; /** * Disables link previews for links in the message. + * @var ?bool */ - private bool|null $disableWebPagePreview; + private $disableWebPagePreview; /** * Sends the message silently. Users will receive a notification with no sound. + * @var ?bool */ - private bool|null $disableNotification; + private $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 bool $splitLongMessages; + private $splitLongMessages; /** * Adds 1-second delay between sending a split message (according to Telegram API to avoid 429 Too Many Requests). + * @var bool */ - private bool $delayBetweenMessages; - - /** - * Telegram message thread id, unique identifier for the target message thread (topic) of the forum; for forum supergroups only - * See how to get the `message_thread_id` https://stackoverflow.com/a/75178418 - */ - private int|null $topic; + private $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 - * @param int $topic Telegram message thread id, unique identifier for the target message thread (topic) of the forum - * @throws MissingExtensionException If the curl extension is missing + * @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 */ public function __construct( string $apiKey, string $channel, - $level = Level::Debug, + $level = Logger::DEBUG, bool $bubble = true, string $parseMode = null, bool $disableWebPagePreview = null, bool $disableNotification = null, bool $splitLongMessages = false, - bool $delayBetweenMessages = false, - int $topic = null - ) { + bool $delayBetweenMessages = false + ) + { if (!extension_loaded('curl')) { throw new MissingExtensionException('The curl extension is needed to use the TelegramBotHandler'); } @@ -131,15 +128,11 @@ public function __construct( $this->disableNotification($disableNotification); $this->splitLongMessages($splitLongMessages); $this->delayBetweenMessages($delayBetweenMessages); - $this->setTopic($topic); } - /** - * @return $this - */ public function setParseMode(string $parseMode = null): self { - if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES, true)) { + if ($parseMode !== null && !in_array($parseMode, self::AVAILABLE_PARSE_MODES)) { throw new \InvalidArgumentException('Unknown parseMode, use one of these: ' . implode(', ', self::AVAILABLE_PARSE_MODES) . '.'); } @@ -148,9 +141,6 @@ public function setParseMode(string $parseMode = null): self return $this; } - /** - * @return $this - */ public function disableWebPagePreview(bool $disableWebPagePreview = null): self { $this->disableWebPagePreview = $disableWebPagePreview; @@ -158,9 +148,6 @@ public function disableWebPagePreview(bool $disableWebPagePreview = null): self return $this; } - /** - * @return $this - */ public function disableNotification(bool $disableNotification = null): self { $this->disableNotification = $disableNotification; @@ -171,7 +158,7 @@ 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 @@ -183,7 +170,7 @@ 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 @@ -194,20 +181,11 @@ public function delayBetweenMessages(bool $delayBetweenMessages = false): self } /** - * @return $this - */ - public function setTopic(int $topic = null): self - { - $this->topic = $topic; - - return $this; - } - - /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { + /** @var Record[] $messages */ $messages = []; foreach ($records as $record) { @@ -215,28 +193,30 @@ public function handleBatch(array $records): void continue; } - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } $messages[] = $record; } - if (\count($messages) > 0) { - $this->send((string) $this->getFormatter()->formatBatch($messages)); + if (!empty($messages)) { + $this->send((string)$this->getFormatter()->formatBatch($messages)); } } /** * @inheritDoc */ - protected function write(LogRecord $record): void + protected function write(array $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 { @@ -258,17 +238,13 @@ protected function sendCurl(string $message): void curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - $params = [ + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'text' => $message, 'chat_id' => $this->channel, 'parse_mode' => $this->parseMode, 'disable_web_page_preview' => $this->disableWebPagePreview, 'disable_notification' => $this->disableNotification, - ]; - if ($this->topic !== null) { - $params['message_thread_id'] = $this->topic; - } - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); + ])); $result = Curl\Util::execute($ch); if (!is_string($result)) { @@ -283,6 +259,7 @@ 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/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php index 8e356ef31..0986da270 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/TestHandler.php @@ -11,10 +11,8 @@ namespace Monolog\Handler; -use Monolog\Level; use Monolog\Logger; use Psr\Log\LogLevel; -use Monolog\LogRecord; /** * Used for testing purposes. @@ -23,14 +21,14 @@ * * @author Jordi Boggiano * - * @method bool hasEmergency(string|array $recordAssertions) - * @method bool hasAlert(string|array $recordAssertions) - * @method bool hasCritical(string|array $recordAssertions) - * @method bool hasError(string|array $recordAssertions) - * @method bool hasWarning(string|array $recordAssertions) - * @method bool hasNotice(string|array $recordAssertions) - * @method bool hasInfo(string|array $recordAssertions) - * @method bool hasDebug(string|array $recordAssertions) + * @method bool hasEmergency($record) + * @method bool hasAlert($record) + * @method bool hasCritical($record) + * @method bool hasError($record) + * @method bool hasWarning($record) + * @method bool hasNotice($record) + * @method bool hasInfo($record) + * @method bool hasDebug($record) * * @method bool hasEmergencyRecords() * @method bool hasAlertRecords() @@ -41,93 +39,111 @@ * @method bool hasInfoRecords() * @method bool hasDebugRecords() * - * @method bool hasEmergencyThatContains(string $message) - * @method bool hasAlertThatContains(string $message) - * @method bool hasCriticalThatContains(string $message) - * @method bool hasErrorThatContains(string $message) - * @method bool hasWarningThatContains(string $message) - * @method bool hasNoticeThatContains(string $message) - * @method bool hasInfoThatContains(string $message) - * @method bool hasDebugThatContains(string $message) + * @method bool hasEmergencyThatContains($message) + * @method bool hasAlertThatContains($message) + * @method bool hasCriticalThatContains($message) + * @method bool hasErrorThatContains($message) + * @method bool hasWarningThatContains($message) + * @method bool hasNoticeThatContains($message) + * @method bool hasInfoThatContains($message) + * @method bool hasDebugThatContains($message) * - * @method bool hasEmergencyThatMatches(string $regex) - * @method bool hasAlertThatMatches(string $regex) - * @method bool hasCriticalThatMatches(string $regex) - * @method bool hasErrorThatMatches(string $regex) - * @method bool hasWarningThatMatches(string $regex) - * @method bool hasNoticeThatMatches(string $regex) - * @method bool hasInfoThatMatches(string $regex) - * @method bool hasDebugThatMatches(string $regex) + * @method bool hasEmergencyThatMatches($message) + * @method bool hasAlertThatMatches($message) + * @method bool hasCriticalThatMatches($message) + * @method bool hasErrorThatMatches($message) + * @method bool hasWarningThatMatches($message) + * @method bool hasNoticeThatMatches($message) + * @method bool hasInfoThatMatches($message) + * @method bool hasDebugThatMatches($message) * - * @method bool hasEmergencyThatPasses(callable $predicate) - * @method bool hasAlertThatPasses(callable $predicate) - * @method bool hasCriticalThatPasses(callable $predicate) - * @method bool hasErrorThatPasses(callable $predicate) - * @method bool hasWarningThatPasses(callable $predicate) - * @method bool hasNoticeThatPasses(callable $predicate) - * @method bool hasInfoThatPasses(callable $predicate) - * @method bool hasDebugThatPasses(callable $predicate) + * @method bool hasEmergencyThatPasses($message) + * @method bool hasAlertThatPasses($message) + * @method bool hasCriticalThatPasses($message) + * @method bool hasErrorThatPasses($message) + * @method bool hasWarningThatPasses($message) + * @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 LogRecord[] */ - protected array $records = []; - /** @phpstan-var array, LogRecord[]> */ - protected array $recordsByLevel = []; - private bool $skipReset = false; + /** @var Record[] */ + protected $records = []; + /** @var array */ + protected $recordsByLevel = []; + /** @var bool */ + private $skipReset = false; /** - * @return array + * @return array + * + * @phpstan-return Record[] */ - public function getRecords(): array + public function getRecords() { return $this->records; } - public function clear(): void + /** + * @return void + */ + public function clear() { $this->records = []; $this->recordsByLevel = []; } - public function reset(): void + /** + * @return void + */ + public function reset() { if (!$this->skipReset) { $this->clear(); } } - public function setSkipReset(bool $skipReset): void + /** + * @return void + */ + public function setSkipReset(bool $skipReset) { $this->skipReset = $skipReset; } /** - * @param int|string|Level|LogLevel::* $level Logging level value or name + * @param string|int $level Logging level value or name * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function hasRecords(int|string|Level $level): bool + public function hasRecords($level): bool { - return isset($this->recordsByLevel[Logger::toMonologLevel($level)->value]); + return isset($this->recordsByLevel[Logger::toMonologLevel($level)]); } /** - * @param string|array $recordAssertions Either a message string or an array containing message and optionally context keys that will be checked against all records + * @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 * - * @phpstan-param array{message: string, context?: mixed[]}|string $recordAssertions + * @phpstan-param array{message: string, context?: mixed[]}|string $record + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function hasRecord(string|array $recordAssertions, Level $level): bool + public function hasRecord($record, $level): bool { - if (is_string($recordAssertions)) { - $recordAssertions = ['message' => $recordAssertions]; + if (is_string($record)) { + $record = array('message' => $record); } - return $this->hasRecordThatPasses(function (LogRecord $rec) use ($recordAssertions) { - if ($rec->message !== $recordAssertions['message']) { + return $this->hasRecordThatPasses(function ($rec) use ($record) { + if ($rec['message'] !== $record['message']) { return false; } - if (isset($recordAssertions['context']) && $rec->context !== $recordAssertions['context']) { + if (isset($record['context']) && $rec['context'] !== $record['context']) { return false; } @@ -135,29 +151,47 @@ public function hasRecord(string|array $recordAssertions, Level $level): bool }, $level); } - public function hasRecordThatContains(string $message, Level $level): bool + /** + * @param string|int $level Logging level value or name + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecordThatContains(string $message, $level): bool { - return $this->hasRecordThatPasses(fn (LogRecord $rec) => str_contains($rec->message, $message), $level); + return $this->hasRecordThatPasses(function ($rec) use ($message) { + return strpos($rec['message'], $message) !== false; + }, $level); } - public function hasRecordThatMatches(string $regex, Level $level): bool + /** + * @param string|int $level Logging level value or name + * + * @phpstan-param Level|LevelName|LogLevel::* $level + */ + public function hasRecordThatMatches(string $regex, $level): bool { - return $this->hasRecordThatPasses(fn (LogRecord $rec) => preg_match($regex, $rec->message) > 0, $level); + return $this->hasRecordThatPasses(function (array $rec) use ($regex): bool { + return preg_match($regex, $rec['message']) > 0; + }, $level); } /** - * @phpstan-param callable(LogRecord, int): mixed $predicate + * @param string|int $level Logging level value or name + * @return bool + * + * @psalm-param callable(Record, int): mixed $predicate + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function hasRecordThatPasses(callable $predicate, Level $level): bool + public function hasRecordThatPasses(callable $predicate, $level) { $level = Logger::toMonologLevel($level); - if (!isset($this->recordsByLevel[$level->value])) { + if (!isset($this->recordsByLevel[$level])) { return false; } - foreach ($this->recordsByLevel[$level->value] as $i => $rec) { - if ((bool) $predicate($rec, $i)) { + foreach ($this->recordsByLevel[$level] as $i => $rec) { + if ($predicate($rec, $i)) { return true; } } @@ -166,22 +200,24 @@ public function hasRecordThatPasses(callable $predicate, Level $level): bool } /** - * @inheritDoc + * {@inheritDoc} */ - protected function write(LogRecord $record): void + protected function write(array $record): void { - $this->recordsByLevel[$record->level->value][] = $record; + $this->recordsByLevel[$record['level']][] = $record; $this->records[] = $record; } /** - * @param mixed[] $args + * @param string $method + * @param mixed[] $args + * @return bool */ - public function __call(string $method, array $args): bool + public function __call($method, $args) { 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(Level::class.'::' . $matches[2]); + $level = constant('Monolog\Logger::' . strtoupper($matches[2])); $callback = [$this, $genericMethod]; if (is_callable($callback)) { $args[] = $level; diff --git a/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php b/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php index 9c12c3d56..c81835288 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/WebRequestRecognizerTrait.php @@ -15,6 +15,7 @@ trait WebRequestRecognizerTrait { /** * Checks if PHP's serving a web request + * @return bool */ protected function isWebRequest(): bool { diff --git a/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php index 932fa70e7..b6d3d3b19 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/WhatFailureGroupHandler.php +++ b/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(LogRecord $record): bool + public function handle(array $record): bool { - if (\count($this->processors) > 0) { + if ($this->processors) { + /** @var Record $record */ $record = $this->processRecord($record); } foreach ($this->handlers as $handler) { try { - $handler->handle(clone $record); - } catch (Throwable) { + $handler->handle($record); + } catch (\Throwable $e) { // What failure? } } @@ -43,22 +43,23 @@ public function handle(LogRecord $record): bool } /** - * @inheritDoc + * {@inheritDoc} */ public function handleBatch(array $records): void { - if (\count($this->processors) > 0) { - $processed = []; + if ($this->processors) { + $processed = array(); foreach ($records as $record) { $processed[] = $this->processRecord($record); } + /** @var Record[] $records */ $records = $processed; } foreach ($this->handlers as $handler) { try { - $handler->handleBatch(array_map(fn ($record) => clone $record, $records)); - } catch (Throwable) { + $handler->handleBatch($records); + } catch (\Throwable $e) { // What failure? } } diff --git a/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php index 1e71194bc..ddd46d8c5 100644 --- a/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php +++ b/vendor/monolog/monolog/src/Monolog/Handler/ZendMonitorHandler.php @@ -13,67 +13,70 @@ use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\NormalizerFormatter; -use Monolog\Level; -use Monolog\LogRecord; +use Monolog\Logger; /** * 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(int|string|Level $level = Level::Debug, bool $bubble = true) + public function __construct($level = Logger::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); } /** - * Translates Monolog log levels to ZendMonitor levels. + * {@inheritDoc} */ - 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 + protected function write(array $record): void { $this->writeZendMonitorCustomEvent( - $record->level->getName(), - $record->message, - $record->formatted, - $this->toZendMonitorLevel($record->level) + Logger::getLevelName($record['level']), + $record['message'], + $record['formatted'], + $this->levelMap[$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) + * @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 */ protected function writeZendMonitorCustomEvent(string $type, string $message, array $formatted, int $severity): void { @@ -81,10 +84,18 @@ 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/vendor/monolog/monolog/src/Monolog/LogRecord.php b/vendor/monolog/monolog/src/Monolog/LogRecord.php index df758c58b..702807d71 100644 --- a/vendor/monolog/monolog/src/Monolog/LogRecord.php +++ b/vendor/monolog/monolog/src/Monolog/LogRecord.php @@ -14,111 +14,21 @@ use ArrayAccess; /** - * Monolog log record + * 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. * * @author Jordi Boggiano - * @template-implements ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra', int|string|\DateTimeImmutable|array> + * @template-extends \ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra'|'formatted', mixed> + * @phpstan-import-type Record from Logger */ -class LogRecord implements ArrayAccess +interface LogRecord extends \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 array{message: string, context: mixed[], level: value-of, level_name: value-of, channel: string, datetime: \DateTimeImmutable, extra: mixed[]} + * @phpstan-return Record */ - 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); - } + public function toArray(): array; } diff --git a/vendor/monolog/monolog/src/Monolog/Logger.php b/vendor/monolog/monolog/src/Monolog/Logger.php index b04194bf9..84a2f5510 100644 --- a/vendor/monolog/monolog/src/Monolog/Logger.php +++ b/vendor/monolog/monolog/src/Monolog/Logger.php @@ -11,17 +11,13 @@ 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 @@ -30,14 +26,15 @@ * and uses them to store records that are added to it. * * @author Jordi Boggiano - * @final + * + * @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[]} */ class Logger implements LoggerInterface, ResettableInterface { /** * Detailed debug information - * - * @deprecated Use \Monolog\Level::Debug */ public const DEBUG = 100; @@ -45,15 +42,11 @@ 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; @@ -62,15 +55,11 @@ 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; @@ -78,8 +67,6 @@ class Logger implements LoggerInterface, ResettableInterface * Critical conditions * * Example: Application component unavailable, unexpected exception. - * - * @deprecated Use \Monolog\Level::Critical */ public const CRITICAL = 500; @@ -88,15 +75,11 @@ 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; @@ -105,8 +88,28 @@ 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 */ - public const API = 3; + 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', + ]; /** * Mapping between levels numbers defined in RFC 5424 and Monolog ones @@ -114,71 +117,90 @@ class Logger implements LoggerInterface, ResettableInterface * @phpstan-var array $rfc_5424_levels */ private const RFC_5424_LEVELS = [ - 7 => Level::Debug, - 6 => Level::Info, - 5 => Level::Notice, - 4 => Level::Warning, - 3 => Level::Error, - 2 => Level::Critical, - 1 => Level::Alert, - 0 => Level::Emergency, + 7 => self::DEBUG, + 6 => self::INFO, + 5 => self::NOTICE, + 4 => self::WARNING, + 3 => self::ERROR, + 2 => self::CRITICAL, + 1 => self::ALERT, + 0 => self::EMERGENCY, ]; - protected string $name; + /** + * @var string + */ + protected $name; /** * The handler stack * - * @var list + * @var HandlerInterface[] */ - protected array $handlers; + protected $handlers; /** * Processors that will process all log records * * To process records of a single handler instead, add the processor on that specific handler * - * @var array<(callable(LogRecord): LogRecord)|ProcessorInterface> + * @var callable[] */ - protected array $processors; + protected $processors; - protected bool $microsecondTimestamps = true; + /** + * @var bool + */ + protected $microsecondTimestamps = true; - protected DateTimeZone $timezone; + /** + * @var DateTimeZone + */ + protected $timezone; - protected Closure|null $exceptionHandler = null; + /** + * @var callable|null + */ + protected $exceptionHandler; /** - * Keeps track of depth to prevent infinite logging loops + * @var int Keeps track of depth to prevent infinite logging loops */ - private int $logDepth = 0; + private $logDepth = 0; /** - * @var WeakMap, int> Keeps track of depth inside fibers to prevent infinite logging loops + * @var \WeakMap<\Fiber, int>|null Keeps track of depth inside fibers to prevent infinite logging loops */ - private WeakMap $fiberLogDepth; + private $fiberLogDepth; /** - * Whether to detect infinite logging loops + * @var bool 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 bool $detectCycles = true; + private $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|null $timezone = null) + public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null) { $this->name = $name; $this->setHandlers($handlers); $this->processors = $processors; - $this->timezone = $timezone ?? new DateTimeZone(date_default_timezone_get()); - $this->fiberLogDepth = new \WeakMap(); + $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; + } } public function getName(): string @@ -188,8 +210,6 @@ public function getName(): string /** * Return a new cloned instance with the name changed - * - * @return static */ public function withName(string $name): self { @@ -201,8 +221,6 @@ public function withName(string $name): self /** * Pushes a handler on to the stack. - * - * @return $this */ public function pushHandler(HandlerInterface $handler): self { @@ -218,7 +236,7 @@ public function pushHandler(HandlerInterface $handler): self */ public function popHandler(): HandlerInterface { - if (0 === \count($this->handlers)) { + if (!$this->handlers) { throw new \LogicException('You tried to pop from an empty handler stack.'); } @@ -230,8 +248,7 @@ public function popHandler(): HandlerInterface * * If a map is passed, keys will be ignored. * - * @param list $handlers - * @return $this + * @param HandlerInterface[] $handlers */ public function setHandlers(array $handlers): self { @@ -244,7 +261,7 @@ public function setHandlers(array $handlers): self } /** - * @return list + * @return HandlerInterface[] */ public function getHandlers(): array { @@ -253,11 +270,8 @@ public function getHandlers(): array /** * Adds a processor on to the stack. - * - * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback - * @return $this */ - public function pushProcessor(ProcessorInterface|callable $callback): self + public function pushProcessor(callable $callback): self { array_unshift($this->processors, $callback); @@ -267,12 +281,12 @@ public function pushProcessor(ProcessorInterface|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 (0 === \count($this->processors)) { + if (!$this->processors) { throw new \LogicException('You tried to pop from an empty processor stack.'); } @@ -281,7 +295,6 @@ public function popProcessor(): callable /** * @return callable[] - * @phpstan-return array */ public function getProcessors(): array { @@ -298,7 +311,6 @@ public function getProcessors(): array * to suppress microseconds from the output. * * @param bool $micro True to use microtime() to create timestamps - * @return $this */ public function useMicrosecondTimestamps(bool $micro): self { @@ -307,9 +319,6 @@ public function useMicrosecondTimestamps(bool $micro): self return $this; } - /** - * @return $this - */ public function useLoggingLoopDetection(bool $detectCycles): self { $this->detectCycles = $detectCycles; @@ -326,17 +335,18 @@ 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 value-of|Level $level + * @phpstan-param Level $level */ - public function addRecord(int|Level $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool + public function addRecord(int $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool { - if (is_int($level) && isset(self::RFC_5424_LEVELS[$level])) { + if (isset(self::RFC_5424_LEVELS[$level])) { $level = self::RFC_5424_LEVELS[$level]; } if ($this->detectCycles) { - if (null !== ($fiber = Fiber::getCurrent())) { - $logDepth = $this->fiberLogDepth[$fiber] = ($this->fiberLogDepth[$fiber] ?? 0) + 1; + if (\PHP_VERSION_ID >= 80100 && $fiber = \Fiber::getCurrent()) { + $this->fiberLogDepth[$fiber] = $this->fiberLogDepth[$fiber] ?? 0; + $logDepth = ++$this->fiberLogDepth[$fiber]; } else { $logDepth = ++$this->logDepth; } @@ -352,30 +362,31 @@ public function addRecord(int|Level $level, string $message, array $context = [] } try { - $recordInitialized = count($this->processors) === 0; - - $record = new LogRecord( - datetime: $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), - channel: $this->name, - level: self::toMonologLevel($level), - message: $message, - context: $context, - extra: [], - ); - $handled = false; + $record = null; foreach ($this->handlers as $handler) { - if (false === $recordInitialized) { - // skip initializing the record as long as no handler is going to handle it - if (!$handler->isHandling($record)) { + if (null === $record) { + // skip creating the record as long as no handler is going to handle it + if (!$handler->isHandling(['level' => $level])) { 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); @@ -383,10 +394,9 @@ public function addRecord(int|Level $level, string $message, array $context = [] } } - // once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted + // once the record exists, send it to all handlers as long as the bubbling chain is not interrupted try { - $handled = true; - if (true === $handler->handle(clone $record)) { + if (true === $handler->handle($record)) { break; } } catch (Throwable $e) { @@ -395,8 +405,6 @@ public function addRecord(int|Level $level, string $message, array $context = [] return true; } } - - return $handled; } finally { if ($this->detectCycles) { if (isset($fiber)) { @@ -406,6 +414,8 @@ public function addRecord(int|Level $level, string $message, array $context = [] } } } + + return null !== $record; } /** @@ -451,77 +461,77 @@ public function reset(): void } /** - * Gets the name of the logging level as a string. + * Gets all supported logging levels. * - * This still returns a string instead of a Level for BC, but new code should not rely on this method. + * @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. * * @throws \Psr\Log\InvalidArgumentException If level is not defined * - * @phpstan-param value-of|Level $level - * @phpstan-return value-of - * - * @deprecated Since 3.0, use {@see toMonologLevel} or {@see \Monolog\Level->getName()} instead + * @phpstan-param Level $level + * @phpstan-return LevelName */ - public static function getLevelName(int|Level $level): string + public static function getLevelName(int $level): string { - return self::toMonologLevel($level)->getName(); + 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]; } /** * Converts PSR-3 levels to Monolog ones if necessary * - * @param int|string|Level|LogLevel::* $level Level number (monolog) or name (PSR-3) - * @throws \Psr\Log\InvalidArgumentException If level is not defined + * @param string|int $level Level number (monolog) or name (PSR-3) + * @throws \Psr\Log\InvalidArgumentException If level is not defined * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level + * @phpstan-return Level */ - public static function toMonologLevel(string|int|Level $level): Level + public static function toMonologLevel($level): int { - 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; + if (is_string($level)) { + if (is_numeric($level)) { + /** @phpstan-ignore-next-line */ + return intval($level); } - // Contains first char of all log levels and avoids using strtoupper() which may have + // Contains chars 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(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1)); - if (defined(Level::class.'::'.$upper)) { - return constant(Level::class . '::' . $upper); + $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY'); + if (defined(__CLASS__.'::'.$upper)) { + return constant(__CLASS__ . '::' . $upper); } - throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES)); + throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', 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)); + 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)); } - return $levelEnum; + return $level; } /** * Checks whether the Logger has a handler that listens on the given level * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level $level */ - public function isHandling(int|string|Level $level): bool + public function isHandling(int $level): bool { - $record = new LogRecord( - datetime: new DateTimeImmutable($this->microsecondTimestamps, $this->timezone), - channel: $this->name, - message: '', - level: self::toMonologLevel($level), - ); + $record = [ + 'level' => $level, + ]; foreach ($this->handlers as $handler) { if ($handler->isHandling($record)) { @@ -535,18 +545,16 @@ public function isHandling(int|string|Level $level): bool /** * Set a custom exception handler that will be called if adding a new record fails * - * The Closure will receive an exception object and the record that failed to be logged - * - * @return $this + * The callable will receive an exception object and the record that failed to be logged */ - public function setExceptionHandler(Closure|null $callback): self + public function setExceptionHandler(?callable $callback): self { $this->exceptionHandler = $callback; return $this; } - public function getExceptionHandler(): Closure|null + public function getExceptionHandler(): ?callable { return $this->exceptionHandler; } @@ -560,22 +568,20 @@ public function getExceptionHandler(): Closure|null * @param string|Stringable $message The log message * @param mixed[] $context The log context * - * @phpstan-param Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function log($level, string|\Stringable $message, array $context = []): void + public function log($level, $message, array $context = []): void { - 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 (!is_int($level) && !is_string($level)) { + throw new \InvalidArgumentException('$level is expected to be a string or int'); + } - $level = static::toMonologLevel($level); + if (isset(self::RFC_5424_LEVELS[$level])) { + $level = self::RFC_5424_LEVELS[$level]; } + $level = static::toMonologLevel($level); + $this->addRecord($level, (string) $message, $context); } @@ -587,9 +593,9 @@ public function log($level, string|\Stringable $message, array $context = []): v * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function debug(string|\Stringable $message, array $context = []): void + public function debug($message, array $context = []): void { - $this->addRecord(Level::Debug, (string) $message, $context); + $this->addRecord(static::DEBUG, (string) $message, $context); } /** @@ -600,9 +606,9 @@ public function debug(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function info(string|\Stringable $message, array $context = []): void + public function info($message, array $context = []): void { - $this->addRecord(Level::Info, (string) $message, $context); + $this->addRecord(static::INFO, (string) $message, $context); } /** @@ -613,9 +619,9 @@ public function info(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function notice(string|\Stringable $message, array $context = []): void + public function notice($message, array $context = []): void { - $this->addRecord(Level::Notice, (string) $message, $context); + $this->addRecord(static::NOTICE, (string) $message, $context); } /** @@ -626,9 +632,9 @@ public function notice(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function warning(string|\Stringable $message, array $context = []): void + public function warning($message, array $context = []): void { - $this->addRecord(Level::Warning, (string) $message, $context); + $this->addRecord(static::WARNING, (string) $message, $context); } /** @@ -639,9 +645,9 @@ public function warning(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function error(string|\Stringable $message, array $context = []): void + public function error($message, array $context = []): void { - $this->addRecord(Level::Error, (string) $message, $context); + $this->addRecord(static::ERROR, (string) $message, $context); } /** @@ -652,9 +658,9 @@ public function error(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function critical(string|\Stringable $message, array $context = []): void + public function critical($message, array $context = []): void { - $this->addRecord(Level::Critical, (string) $message, $context); + $this->addRecord(static::CRITICAL, (string) $message, $context); } /** @@ -665,9 +671,9 @@ public function critical(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function alert(string|\Stringable $message, array $context = []): void + public function alert($message, array $context = []): void { - $this->addRecord(Level::Alert, (string) $message, $context); + $this->addRecord(static::ALERT, (string) $message, $context); } /** @@ -678,15 +684,13 @@ public function alert(string|\Stringable $message, array $context = []): void * @param string|Stringable $message The log message * @param mixed[] $context The log context */ - public function emergency(string|\Stringable $message, array $context = []): void + public function emergency($message, array $context = []): void { - $this->addRecord(Level::Emergency, (string) $message, $context); + $this->addRecord(static::EMERGENCY, (string) $message, $context); } /** * Sets the timezone to be used for the timestamp of log records. - * - * @return $this */ public function setTimezone(DateTimeZone $tz): self { @@ -706,10 +710,13 @@ 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, LogRecord $record): void + protected function handleException(Throwable $e, array $record): void { - if (null === $this->exceptionHandler) { + if (!$this->exceptionHandler) { throw $e; } @@ -744,6 +751,11 @@ public function __unserialize(array $data): void } } - $this->fiberLogDepth = new \WeakMap(); + 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; + } } } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php index 5a70ac2e2..8166bdca2 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/GitProcessor.php @@ -11,44 +11,46 @@ 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 { - private Level $level; + /** @var int */ + private $level; /** @var array{branch: string, commit: string}|array|null */ private static $cache = null; /** - * @param int|string|Level|LogLevel::* $level The minimum logging level at which this Processor will be triggered + * @param string|int $level The minimum logging level at which this Processor will be triggered * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function __construct(int|string|Level $level = Level::Debug) + public function __construct($level = Logger::DEBUG) { $this->level = Logger::toMonologLevel($level); } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { // return if the level is not high enough - if ($record->level->isLowerThan($this->level)) { + if ($record['level'] < $this->level) { return $record; } - $record->extra['git'] = self::getGitInfo(); + $record['extra']['git'] = self::getGitInfo(); return $record; } @@ -58,12 +60,12 @@ public function __invoke(LogRecord $record): LogRecord */ private static function getGitInfo(): array { - if (self::$cache !== null) { + if (self::$cache) { return self::$cache; } - $branches = shell_exec('git branch -v --no-abbrev'); - if (is_string($branches) && 1 === preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { + $branches = `git branch -v --no-abbrev`; + if ($branches && preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) { return self::$cache = [ 'branch' => $matches[1], 'commit' => $matches[2], diff --git a/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php index cba6e0963..91fda7d6d 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/HostnameProcessor.php @@ -11,14 +11,13 @@ namespace Monolog\Processor; -use Monolog\LogRecord; - /** * Injects value of gethostname in all records */ class HostnameProcessor implements ProcessorInterface { - private static string $host; + /** @var string */ + private static $host; public function __construct() { @@ -26,11 +25,11 @@ public function __construct() } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { - $record->extra['hostname'] = self::$host; + $record['extra']['hostname'] = self::$host; return $record; } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php index 3a6fbfbef..a32e76b21 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/IntrospectionProcessor.php @@ -11,10 +11,8 @@ 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 @@ -26,28 +24,31 @@ * triggered the FingersCrossedHandler. * * @author Jordi Boggiano + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger */ class IntrospectionProcessor implements ProcessorInterface { - private Level $level; - + /** @var int */ + private $level; /** @var string[] */ - private array $skipClassesPartials; - - private int $skipStackFramesCount; - - private const SKIP_FUNCTIONS = [ + private $skipClassesPartials; + /** @var int */ + private $skipStackFramesCount; + /** @var string[] */ + private $skipFunctions = [ 'call_user_func', 'call_user_func_array', ]; /** - * @param string|int|Level $level The minimum logging level at which this Processor will be triggered - * @param string[] $skipClassesPartials + * @param string|int $level The minimum logging level at which this Processor will be triggered + * @param string[] $skipClassesPartials * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function __construct(int|string|Level $level = Level::Debug, array $skipClassesPartials = [], int $skipStackFramesCount = 0) + public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], int $skipStackFramesCount = 0) { $this->level = Logger::toMonologLevel($level); $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials); @@ -55,12 +56,12 @@ public function __construct(int|string|Level $level = Level::Debug, array $skipC } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { // return if the level is not high enough - if ($record->level->isLowerThan($this->level)) { + if ($record['level'] < $this->level) { return $record; } @@ -82,7 +83,7 @@ public function __invoke(LogRecord $record): LogRecord continue 2; } } - } elseif (in_array($trace[$i]['function'], self::SKIP_FUNCTIONS, true)) { + } elseif (in_array($trace[$i]['function'], $this->skipFunctions)) { $i++; continue; @@ -94,14 +95,14 @@ public function __invoke(LogRecord $record): LogRecord $i += $this->skipStackFramesCount; // we should have the call source now - $record->extra = array_merge( - $record->extra, + $record['extra'] = array_merge( + $record['extra'], [ - '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, + '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, ] ); @@ -109,7 +110,7 @@ public function __invoke(LogRecord $record): LogRecord } /** - * @param array $trace + * @param array[] $trace */ private function isTraceClassOrSkippedFunction(array $trace, int $index): bool { @@ -117,6 +118,6 @@ private function isTraceClassOrSkippedFunction(array $trace, int $index): bool return false; } - return isset($trace[$index]['class']) || in_array($trace[$index]['function'], self::SKIP_FUNCTIONS, true); + return isset($trace[$index]['class']) || in_array($trace[$index]['function'], $this->skipFunctions); } } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php index adc32c65d..37c756fcb 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryPeakUsageProcessor.php @@ -11,8 +11,6 @@ namespace Monolog\Processor; -use Monolog\LogRecord; - /** * Injects memory_get_peak_usage in all records * @@ -22,9 +20,9 @@ class MemoryPeakUsageProcessor extends MemoryProcessor { /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { $usage = memory_get_peak_usage($this->realUsage); @@ -32,7 +30,7 @@ public function __invoke(LogRecord $record): LogRecord $usage = $this->formatBytes($usage); } - $record->extra['memory_peak_usage'] = $usage; + $record['extra']['memory_peak_usage'] = $usage; return $record; } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php index f808e51b4..227deb7c8 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/MemoryProcessor.php +++ b/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 bool $realUsage; + protected $realUsage; /** * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size) */ - protected bool $useFormatting; + protected $useFormatting; /** * @param bool $realUsage Set this to true to get the real size of memory allocated from system. @@ -41,6 +41,7 @@ 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/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php index a814b1df3..e141921e9 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/MemoryUsageProcessor.php @@ -11,8 +11,6 @@ namespace Monolog\Processor; -use Monolog\LogRecord; - /** * Injects memory_get_usage in all records * @@ -22,9 +20,9 @@ class MemoryUsageProcessor extends MemoryProcessor { /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { $usage = memory_get_usage($this->realUsage); @@ -32,7 +30,7 @@ public function __invoke(LogRecord $record): LogRecord $usage = $this->formatBytes($usage); } - $record->extra['memory_usage'] = $usage; + $record['extra']['memory_usage'] = $usage; return $record; } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php index 47b1e64ff..d4a628f55 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/MercurialProcessor.php @@ -11,43 +11,45 @@ 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 { - private Level $level; + /** @var Level */ + private $level; /** @var array{branch: string, revision: string}|array|null */ private static $cache = null; /** - * @param int|string|Level $level The minimum logging level at which this Processor will be triggered + * @param int|string $level The minimum logging level at which this Processor will be triggered * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function __construct(int|string|Level $level = Level::Debug) + public function __construct($level = Logger::DEBUG) { $this->level = Logger::toMonologLevel($level); } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { // return if the level is not high enough - if ($record->level->isLowerThan($this->level)) { + if ($record['level'] < $this->level) { return $record; } - $record->extra['hg'] = self::getMercurialInfo(); + $record['extra']['hg'] = self::getMercurialInfo(); return $record; } @@ -57,11 +59,11 @@ public function __invoke(LogRecord $record): LogRecord */ private static function getMercurialInfo(): array { - if (self::$cache !== null) { + if (self::$cache) { return self::$cache; } - $result = explode(' ', trim((string) shell_exec('hg id -nb'))); + $result = explode(' ', trim(`hg id -nb`)); if (count($result) >= 3) { return self::$cache = [ diff --git a/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php index bb9a52243..3b939a951 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/ProcessIdProcessor.php @@ -11,8 +11,6 @@ namespace Monolog\Processor; -use Monolog\LogRecord; - /** * Adds value of getmypid into records * @@ -21,11 +19,11 @@ class ProcessIdProcessor implements ProcessorInterface { /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { - $record->extra['process_id'] = getmypid(); + $record['extra']['process_id'] = getmypid(); return $record; } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php b/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php index ebe41fc20..5defb7eb4 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/ProcessorInterface.php @@ -11,17 +11,20 @@ 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 LogRecord The processed record + * @return array The processed record + * + * @phpstan-param Record $record + * @phpstan-return Record */ - public function __invoke(LogRecord $record); + public function __invoke(array $record); } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php index aad2aad2f..e7c12176a 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/PsrLogMessageProcessor.php @@ -12,7 +12,6 @@ namespace Monolog\Processor; use Monolog\Utils; -use Monolog\LogRecord; /** * Processes a record's message according to PSR-3 rules @@ -25,9 +24,11 @@ class PsrLogMessageProcessor implements ProcessorInterface { public const SIMPLE_DATE = "Y-m-d\TH:i:s.uP"; - private ?string $dateFormat; + /** @var string|null */ + private $dateFormat; - private bool $removeUsedContextFields; + /** @var bool */ + private $removeUsedContextFields; /** * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format @@ -40,32 +41,30 @@ public function __construct(?string $dateFormat = null, bool $removeUsedContextF } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { - if (false === strpos($record->message, '{')) { + if (false === strpos($record['message'], '{')) { return $record; } $replacements = []; - $context = $record->context; - - foreach ($context as $key => $val) { + foreach ($record['context'] as $key => $val) { $placeholder = '{' . $key . '}'; - if (strpos($record->message, $placeholder) === false) { + if (strpos($record['message'], $placeholder) === false) { continue; } - if (null === $val || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { + if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) { $replacements[$placeholder] = $val; } elseif ($val instanceof \DateTimeInterface) { - if (null === $this->dateFormat && $val instanceof \Monolog\DateTimeImmutable) { + if (!$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; @@ -78,10 +77,12 @@ public function __invoke(LogRecord $record): LogRecord } if ($this->removeUsedContextFields) { - unset($context[$key]); + unset($record['context'][$key]); } } - return $record->with(message: strtr($record->message, $replacements), context: $context); + $record['message'] = strtr($record['message'], $replacements); + + return $record; } } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php index 10ed1cea3..80f18747a 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/TagProcessor.php @@ -11,8 +11,6 @@ namespace Monolog\Processor; -use Monolog\LogRecord; - /** * Adds a tags array into record * @@ -21,7 +19,7 @@ class TagProcessor implements ProcessorInterface { /** @var string[] */ - private array $tags; + private $tags; /** * @param string[] $tags @@ -33,7 +31,6 @@ public function __construct(array $tags = []) /** * @param string[] $tags - * @return $this */ public function addTags(array $tags = []): self { @@ -44,7 +41,6 @@ public function addTags(array $tags = []): self /** * @param string[] $tags - * @return $this */ public function setTags(array $tags = []): self { @@ -54,11 +50,11 @@ public function setTags(array $tags = []): self } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { - $record->extra['tags'] = $this->tags; + $record['extra']['tags'] = $this->tags; return $record; } diff --git a/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php index 3a0c128c2..a27b74dbf 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/UidProcessor.php @@ -12,7 +12,6 @@ namespace Monolog\Processor; use Monolog\ResettableInterface; -use Monolog\LogRecord; /** * Adds a unique identifier into records @@ -21,12 +20,9 @@ */ class UidProcessor implements ProcessorInterface, ResettableInterface { - /** @var non-empty-string */ - private string $uid; + /** @var string */ + private $uid; - /** - * @param int<1, 32> $length - */ public function __construct(int $length = 7) { if ($length > 32 || $length < 1) { @@ -37,11 +33,11 @@ public function __construct(int $length = 7) } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { - $record->extra['uid'] = $this->uid; + $record['extra']['uid'] = $this->uid; return $record; } @@ -51,15 +47,11 @@ public function getUid(): string return $this->uid; } - public function reset(): void + public function reset() { $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/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php b/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php index 1abb8400c..51850e17f 100644 --- a/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php +++ b/vendor/monolog/monolog/src/Monolog/Processor/WebProcessor.php @@ -11,9 +11,6 @@ namespace Monolog\Processor; -use ArrayAccess; -use Monolog\LogRecord; - /** * Injects url/method and remote IP of the current web request in all records * @@ -22,9 +19,9 @@ class WebProcessor implements ProcessorInterface { /** - * @var array|ArrayAccess + * @var array|\ArrayAccess */ - protected array|ArrayAccess $serverData; + protected $serverData; /** * Default fields @@ -33,7 +30,7 @@ class WebProcessor implements ProcessorInterface * * @var array */ - protected array $extraFields = [ + protected $extraFields = [ 'url' => 'REQUEST_URI', 'ip' => 'REMOTE_ADDR', 'http_method' => 'REQUEST_METHOD', @@ -43,15 +40,17 @@ 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(array|ArrayAccess|null $serverData = null, array|null $extraFields = null) + public function __construct($serverData = null, array $extraFields = null) { if (null === $serverData) { $this->serverData = &$_SERVER; - } else { + } elseif (is_array($serverData) || $serverData instanceof \ArrayAccess) { $this->serverData = $serverData; + } else { + throw new \UnexpectedValueException('$serverData must be an array or object implementing ArrayAccess.'); } $defaultEnabled = ['url', 'ip', 'http_method', 'server', 'referrer']; @@ -65,7 +64,7 @@ public function __construct(array|ArrayAccess|null $serverData = null, array|nul } if (isset($extraFields[0])) { foreach (array_keys($this->extraFields) as $fieldName) { - if (!in_array($fieldName, $extraFields, true)) { + if (!in_array($fieldName, $extraFields)) { unset($this->extraFields[$fieldName]); } } @@ -75,9 +74,9 @@ public function __construct(array|ArrayAccess|null $serverData = null, array|nul } /** - * @inheritDoc + * {@inheritDoc} */ - public function __invoke(LogRecord $record): LogRecord + public function __invoke(array $record): array { // skip processing if for some reason request data // is not present (CLI or wonky SAPIs) @@ -85,14 +84,11 @@ public function __invoke(LogRecord $record): LogRecord return $record; } - $record->extra = $this->appendExtraFields($record->extra); + $record['extra'] = $this->appendExtraFields($record['extra']); return $record; } - /** - * @return $this - */ public function addExtraField(string $extraName, string $serverName): self { $this->extraFields[$extraName] = $serverName; diff --git a/vendor/monolog/monolog/src/Monolog/Registry.php b/vendor/monolog/monolog/src/Monolog/Registry.php index 2ef2edceb..ae94ae6cc 100644 --- a/vendor/monolog/monolog/src/Monolog/Registry.php +++ b/vendor/monolog/monolog/src/Monolog/Registry.php @@ -42,7 +42,7 @@ class Registry * * @var Logger[] */ - private static array $loggers = []; + private static $loggers = []; /** * Adds new logging channel to the registry @@ -51,10 +51,11 @@ 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): void + public static function addLogger(Logger $logger, ?string $name = null, bool $overwrite = false) { - $name = $name ?? $logger->getName(); + $name = $name ?: $logger->getName(); if (isset(self::$loggers[$name]) && !$overwrite) { throw new InvalidArgumentException('Logger with the given name already exists'); @@ -109,7 +110,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(string $name): Logger + public static function getInstance($name): Logger { if (!isset(self::$loggers[$name])) { throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name)); @@ -126,7 +127,7 @@ public static function getInstance(string $name): Logger * @throws \InvalidArgumentException If named Logger instance is not in the registry * @return Logger Requested instance of Logger */ - public static function __callStatic(string $name, array $arguments): Logger + public static function __callStatic($name, $arguments) { return self::getInstance($name); } diff --git a/vendor/monolog/monolog/src/Monolog/ResettableInterface.php b/vendor/monolog/monolog/src/Monolog/ResettableInterface.php index 4983a6b35..2c5fd7851 100644 --- a/vendor/monolog/monolog/src/Monolog/ResettableInterface.php +++ b/vendor/monolog/monolog/src/Monolog/ResettableInterface.php @@ -27,5 +27,8 @@ */ interface ResettableInterface { - public function reset(): void; + /** + * @return void + */ + public function reset(); } diff --git a/vendor/monolog/monolog/src/Monolog/SignalHandler.php b/vendor/monolog/monolog/src/Monolog/SignalHandler.php index b930ca439..d730eea3a 100644 --- a/vendor/monolog/monolog/src/Monolog/SignalHandler.php +++ b/vendor/monolog/monolog/src/Monolog/SignalHandler.php @@ -19,17 +19,21 @@ * Monolog POSIX signal handler * * @author Robert Gust-Bardon + * + * @phpstan-import-type Level from \Monolog\Logger + * @phpstan-import-type LevelName from \Monolog\Logger */ class SignalHandler { - private LoggerInterface $logger; + /** @var LoggerInterface */ + private $logger; /** @var array SIG_DFL, SIG_IGN or previous callable */ - private array $previousSignalHandler = []; - /** @var array */ - private array $signalLevelMap = []; + private $previousSignalHandler = []; + /** @var array */ + private $signalLevelMap = []; /** @var array */ - private array $signalRestartSyscalls = []; + private $signalRestartSyscalls = []; public function __construct(LoggerInterface $logger) { @@ -37,18 +41,21 @@ public function __construct(LoggerInterface $logger) } /** - * @param int|string|Level $level Level or level name + * @param int|string $level Level or level name + * @param bool $callPrevious + * @param bool $restartSyscalls + * @param bool|null $async * @return $this * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level|LevelName|LogLevel::* $level */ - public function registerSignalHandler(int $signo, int|string|Level $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self + public function registerSignalHandler(int $signo, $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)->toPsrLogLevel(); + $level = Logger::toMonologLevel($level); if ($callPrevious) { $handler = pcntl_signal_get_handler($signo); @@ -73,12 +80,12 @@ public function registerSignalHandler(int $signo, int|string|Level $level = LogL */ public function handleSignal(int $signo, $siginfo = null): void { - /** @var array $signals */ static $signals = []; - if (\count($signals) === 0 && extension_loaded('pcntl')) { + if (!$signals && extension_loaded('pcntl')) { $pcntl = new ReflectionExtension('pcntl'); - foreach ($pcntl->getConstants() as $name => $value) { + // HHVM 3.24.2 returns an empty array. + foreach ($pcntl->getConstants() ?: get_defined_constants(true)['Core'] as $name => $value) { if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && is_int($value)) { $signals[$value] = $name; } diff --git a/vendor/monolog/monolog/src/Monolog/Test/TestCase.php b/vendor/monolog/monolog/src/Monolog/Test/TestCase.php index 29ec7c96e..bc0b425ea 100644 --- a/vendor/monolog/monolog/src/Monolog/Test/TestCase.php +++ b/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,45 +37,48 @@ public function tearDown(): void } /** - * @param array $context - * @param array $extra + * @param mixed[] $context + * + * @return array Record * - * @phpstan-param value-of|value-of|Level|LogLevel::* $level + * @phpstan-param Level $level + * @phpstan-return Record */ - 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 + protected function getRecord(int $level = Logger::WARNING, string $message = 'test', array $context = []): array { - return new LogRecord( - message: (string) $message, - context: $context, - level: Logger::toMonologLevel($level), - channel: $channel, - datetime: $datetime, - extra: $extra, - ); + return [ + 'message' => (string) $message, + 'context' => $context, + 'level' => $level, + 'level_name' => Logger::getLevelName($level), + 'channel' => 'test', + 'datetime' => new DateTimeImmutable(true), + 'extra' => [], + ]; } /** - * @phpstan-return list + * @phpstan-return Record[] */ protected function getMultipleRecords(): array { return [ - $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'), + $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'), ]; } protected function getIdentityFormatter(): FormatterInterface { $formatter = $this->createMock(FormatterInterface::class); - $formatter->expects(self::any()) + $formatter->expects($this->any()) ->method('format') - ->willReturnCallback(function ($record) { - return $record->message; - }); + ->will($this->returnCallback(function ($record) { + return $record['message']; + })); return $formatter; } diff --git a/vendor/monolog/monolog/src/Monolog/Utils.php b/vendor/monolog/monolog/src/Monolog/Utils.php index 7848f0ecd..360c42199 100644 --- a/vendor/monolog/monolog/src/Monolog/Utils.php +++ b/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, ['Monolog\Utils', 'detectAndCleanUtf8']); + array_walk_recursive($data, array('Monolog\Utils', 'detectAndCleanUtf8')); } else { self::throwEncodeError($code, $data); } @@ -165,16 +165,27 @@ 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): never + private static function throwEncodeError(int $code, $data): void { - $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', - }; + 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'; + } throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true)); } @@ -196,17 +207,16 @@ private static function throwEncodeError(int $code, $data): never */ private static function detectAndCleanUtf8(&$data): void { - if (is_string($data) && preg_match('//u', $data) !== 1) { + if (is_string($data) && !preg_match('//u', $data)) { $data = preg_replace_callback( '/[\x80-\xFF]+/', - function (array $m): string { + function ($m) { return function_exists('mb_convert_encoding') ? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1') : utf8_encode($m[0]); }, $data ); if (!is_string($data)) { $pcreErrorCode = preg_last_error(); - throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . self::pcreLastErrorMessage($pcreErrorCode)); } $data = str_replace( @@ -220,8 +230,8 @@ function (array $m): string { /** * 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) { @@ -234,7 +244,7 @@ public static function expandIniShorthandBytes($val) return (int) $val; } - if (preg_match('/^\s*(?\d+)(?:\.\d+)?\s*(?[gmk]?)\s*$/i', $val, $match) !== 1) { + if (!preg_match('/^\s*(?\d+)(?:\.\d+)?\s*(?[gmk]?)\s*$/i', $val, $match)) { return false; } @@ -242,10 +252,8 @@ 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; } @@ -253,22 +261,24 @@ public static function expandIniShorthandBytes($val) return $val; } - public static function getRecordMessageForException(LogRecord $record): string + /** + * @param array $record + */ + public static function getRecordMessageForException(array $record): string { $context = ''; $extra = ''; - try { - if (\count($record->context) > 0) { - $context = "\nContext: " . json_encode($record->context, JSON_THROW_ON_ERROR); + if ($record['context']) { + $context = "\nContext: " . json_encode($record['context']); } - if (\count($record->extra) > 0) { - $extra = "\nExtra: " . json_encode($record->extra, JSON_THROW_ON_ERROR); + if ($record['extra']) { + $extra = "\nExtra: " . json_encode($record['extra']); } } 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/vendor/psr/log/composer.json b/vendor/psr/log/composer.json index 879fc6f53..ca0569537 100644 --- a/vendor/psr/log/composer.json +++ b/vendor/psr/log/composer.json @@ -11,16 +11,16 @@ } ], "require": { - "php": ">=8.0.0" + "php": ">=5.3.0" }, "autoload": { "psr-4": { - "Psr\\Log\\": "src" + "Psr\\Log\\": "Psr/Log/" } }, "extra": { "branch-alias": { - "dev-master": "3.x-dev" + "dev-master": "1.1.x-dev" } } } diff --git a/vendor/ramsey/collection/composer.json b/vendor/ramsey/collection/composer.json index 56709015a..f09106a15 100644 --- a/vendor/ramsey/collection/composer.json +++ b/vendor/ramsey/collection/composer.json @@ -19,7 +19,8 @@ } ], "require": { - "php": "^8.1" + "php": "^7.4 || ^8.0", + "symfony/polyfill-php81": "^1.23" }, "require-dev": { "captainhook/plugin-composer": "^5.3", diff --git a/vendor/ramsey/collection/src/AbstractArray.php b/vendor/ramsey/collection/src/AbstractArray.php index 5ce622aa7..9b39dd0cb 100644 --- a/vendor/ramsey/collection/src/AbstractArray.php +++ b/vendor/ramsey/collection/src/AbstractArray.php @@ -18,6 +18,8 @@ use Traversable; use function count; +use function serialize; +use function unserialize; /** * This class provides a basic implementation of `ArrayInterface`, to minimize @@ -68,7 +70,7 @@ public function getIterator(): Traversable * * @param array-key $offset The offset to check. */ - public function offsetExists(mixed $offset): bool + public function offsetExists($offset): bool { return isset($this->data[$offset]); } @@ -80,12 +82,13 @@ public function offsetExists(mixed $offset): bool * * @param array-key $offset The offset for which a value should be returned. * - * @return T the value stored at the offset, or null if the offset + * @return T|null the value stored at the offset, or null if the offset * does not exist. */ - public function offsetGet(mixed $offset): mixed + #[\ReturnTypeWillChange] // phpcs:ignore + public function offsetGet($offset) { - return $this->data[$offset]; + return $this->data[$offset] ?? null; } /** @@ -93,11 +96,12 @@ public function offsetGet(mixed $offset): mixed * * @link http://php.net/manual/en/arrayaccess.offsetset.php ArrayAccess::offsetSet() * - * @param array-key | null $offset The offset to set. If `null`, the value - * may be set at a numerically-indexed offset. + * @param array-key|null $offset The offset to set. If `null`, the value may be + * set at a numerically-indexed offset. * @param T $value The value to set at the given offset. */ - public function offsetSet(mixed $offset, mixed $value): void + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function offsetSet($offset, $value): void { if ($offset === null) { $this->data[] = $value; @@ -113,11 +117,25 @@ public function offsetSet(mixed $offset, mixed $value): void * * @param array-key $offset The offset to remove from the array. */ - public function offsetUnset(mixed $offset): void + public function offsetUnset($offset): void { unset($this->data[$offset]); } + /** + * Returns a serialized string representation of this array object. + * + * @deprecated The Serializable interface will go away in PHP 9. + * + * @link http://php.net/manual/en/serializable.serialize.php Serializable::serialize() + * + * @return string a PHP serialized string. + */ + public function serialize(): string + { + return serialize($this->data); + } + /** * Returns data suitable for PHP serialization. * @@ -131,6 +149,25 @@ public function __serialize(): array return $this->data; } + /** + * Converts a serialized string representation into an instance object. + * + * @deprecated The Serializable interface will go away in PHP 9. + * + * @link http://php.net/manual/en/serializable.unserialize.php Serializable::unserialize() + * + * @param string $serialized A PHP serialized string to unserialize. + * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + */ + public function unserialize($serialized): void + { + /** @var array $data */ + $data = unserialize($serialized, ['allowed_classes' => false]); + + $this->data = $data; + } + /** * Adds unserialized data to the object. * @@ -166,6 +203,6 @@ public function toArray(): array public function isEmpty(): bool { - return $this->data === []; + return count($this->data) === 0; } } diff --git a/vendor/ramsey/collection/src/AbstractCollection.php b/vendor/ramsey/collection/src/AbstractCollection.php index 8cb21ec02..38ef7144c 100644 --- a/vendor/ramsey/collection/src/AbstractCollection.php +++ b/vendor/ramsey/collection/src/AbstractCollection.php @@ -17,27 +17,27 @@ use Closure; use Ramsey\Collection\Exception\CollectionMismatchException; use Ramsey\Collection\Exception\InvalidArgumentException; -use Ramsey\Collection\Exception\InvalidPropertyOrMethod; -use Ramsey\Collection\Exception\NoSuchElementException; -use Ramsey\Collection\Exception\UnsupportedOperationException; +use Ramsey\Collection\Exception\InvalidSortOrderException; +use Ramsey\Collection\Exception\OutOfBoundsException; use Ramsey\Collection\Tool\TypeTrait; use Ramsey\Collection\Tool\ValueExtractorTrait; use Ramsey\Collection\Tool\ValueToStringTrait; use function array_filter; -use function array_key_first; -use function array_key_last; use function array_map; use function array_merge; -use function array_reduce; use function array_search; use function array_udiff; use function array_uintersect; +use function current; +use function end; use function in_array; use function is_int; use function is_object; +use function reset; use function spl_object_id; use function sprintf; +use function unserialize; use function usort; /** @@ -55,24 +55,27 @@ abstract class AbstractCollection extends AbstractArray implements CollectionInt use ValueExtractorTrait; /** - * @throws InvalidArgumentException if $element is of the wrong type. + * @inheritDoc */ - public function add(mixed $element): bool + public function add($element): bool { $this[] = $element; return true; } - public function contains(mixed $element, bool $strict = true): bool + /** + * @inheritDoc + */ + public function contains($element, bool $strict = true): bool { return in_array($element, $this->data, $strict); } /** - * @throws InvalidArgumentException if $element is of the wrong type. + * @inheritDoc */ - public function offsetSet(mixed $offset, mixed $value): void + public function offsetSet($offset, $value): void { if ($this->checkType($this->getType(), $value) === false) { throw new InvalidArgumentException( @@ -88,7 +91,10 @@ public function offsetSet(mixed $offset, mixed $value): void } } - public function remove(mixed $element): bool + /** + * @inheritDoc + */ + public function remove($element): bool { if (($position = array_search($element, $this->data, true)) !== false) { unset($this[$position]); @@ -100,11 +106,6 @@ public function remove(mixed $element): bool } /** - * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist - * on the elements in this collection. - * @throws UnsupportedOperationException if unable to call column() on this - * collection. - * * @inheritDoc */ public function column(string $propertyOrMethod): array @@ -112,55 +113,55 @@ public function column(string $propertyOrMethod): array $temp = []; foreach ($this->data as $item) { + /** @var mixed $value */ + $value = $this->extractValue($item, $propertyOrMethod); + /** @psalm-suppress MixedAssignment */ - $temp[] = $this->extractValue($item, $propertyOrMethod); + $temp[] = $value; } return $temp; } /** - * @return T - * - * @throws NoSuchElementException if this collection is empty. + * @inheritDoc */ - public function first(): mixed + public function first() { - $firstIndex = array_key_first($this->data); - - if ($firstIndex === null) { - throw new NoSuchElementException('Can\'t determine first item. Collection is empty'); + if ($this->isEmpty()) { + throw new OutOfBoundsException('Can\'t determine first item. Collection is empty'); } - return $this->data[$firstIndex]; + reset($this->data); + + /** @var T $first */ + $first = current($this->data); + + return $first; } /** - * @return T - * - * @throws NoSuchElementException if this collection is empty. + * @inheritDoc */ - public function last(): mixed + public function last() { - $lastIndex = array_key_last($this->data); - - if ($lastIndex === null) { - throw new NoSuchElementException('Can\'t determine last item. Collection is empty'); + if ($this->isEmpty()) { + throw new OutOfBoundsException('Can\'t determine last item. Collection is empty'); } - return $this->data[$lastIndex]; + /** @var T $item */ + $item = end($this->data); + reset($this->data); + + return $item; } - /** - * @return CollectionInterface - * - * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist - * on the elements in this collection. - * @throws UnsupportedOperationException if unable to call sort() on this - * collection. - */ - public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascending): CollectionInterface + public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): CollectionInterface { + if (!in_array($order, [self::SORT_ASC, self::SORT_DESC], true)) { + throw new InvalidSortOrderException('Invalid sort order given: ' . $order); + } + $collection = clone $this; usort( @@ -169,25 +170,20 @@ public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascen * @param T $a * @param T $b */ - function (mixed $a, mixed $b) use ($propertyOrMethod, $order): int { + function ($a, $b) use ($propertyOrMethod, $order): int { /** @var mixed $aValue */ $aValue = $this->extractValue($a, $propertyOrMethod); /** @var mixed $bValue */ $bValue = $this->extractValue($b, $propertyOrMethod); - return ($aValue <=> $bValue) * ($order === Sort::Descending ? -1 : 1); + return ($aValue <=> $bValue) * ($order === self::SORT_DESC ? -1 : 1); }, ); return $collection; } - /** - * @param callable(T): bool $callback A callable to use for filtering elements. - * - * @return CollectionInterface - */ public function filter(callable $callback): CollectionInterface { $collection = clone $this; @@ -197,66 +193,23 @@ public function filter(callable $callback): CollectionInterface } /** - * @return CollectionInterface - * - * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist - * on the elements in this collection. - * @throws UnsupportedOperationException if unable to call where() on this - * collection. + * {@inheritdoc} */ - public function where(?string $propertyOrMethod, mixed $value): CollectionInterface + public function where(string $propertyOrMethod, $value): CollectionInterface { - return $this->filter( - /** - * @param T $item - */ - function (mixed $item) use ($propertyOrMethod, $value): bool { - /** @var mixed $accessorValue */ - $accessorValue = $this->extractValue($item, $propertyOrMethod); + return $this->filter(function ($item) use ($propertyOrMethod, $value) { + /** @var mixed $accessorValue */ + $accessorValue = $this->extractValue($item, $propertyOrMethod); - return $accessorValue === $value; - }, - ); + return $accessorValue === $value; + }); } - /** - * @param callable(T): TCallbackReturn $callback A callable to apply to each - * item of the collection. - * - * @return CollectionInterface - * - * @template TCallbackReturn - */ public function map(callable $callback): CollectionInterface { - /** @var Collection */ return new Collection('mixed', array_map($callback, $this->data)); } - /** - * @param callable(TCarry, T): TCarry $callback A callable to apply to each - * item of the collection to reduce it to a single value. - * @param TCarry $initial This is the initial value provided to the callback. - * - * @return TCarry - * - * @template TCarry - */ - public function reduce(callable $callback, mixed $initial): mixed - { - /** @var TCarry */ - return array_reduce($this->data, $callback, $initial); - } - - /** - * @param CollectionInterface $other The collection to check for divergent - * items. - * - * @return CollectionInterface - * - * @throws CollectionMismatchException if the compared collections are of - * differing types. - */ public function diff(CollectionInterface $other): CollectionInterface { $this->compareCollectionTypes($other); @@ -273,15 +226,6 @@ public function diff(CollectionInterface $other): CollectionInterface return $collection; } - /** - * @param CollectionInterface $other The collection to check for - * intersecting items. - * - * @return CollectionInterface - * - * @throws CollectionMismatchException if the compared collections are of - * differing types. - */ public function intersect(CollectionInterface $other): CollectionInterface { $this->compareCollectionTypes($other); @@ -295,15 +239,6 @@ public function intersect(CollectionInterface $other): CollectionInterface return $collection; } - /** - * @param CollectionInterface ...$collections The collections to merge. - * - * @return CollectionInterface - * - * @throws CollectionMismatchException if unable to merge any of the given - * collections or items within the given collections due to type - * mismatch errors. - */ public function merge(CollectionInterface ...$collections): CollectionInterface { $mergedCollection = clone $this; @@ -339,10 +274,19 @@ public function merge(CollectionInterface ...$collections): CollectionInterface return $mergedCollection; } + /** + * @inheritDoc + */ + public function unserialize($serialized): void + { + /** @var array $data */ + $data = unserialize($serialized, ['allowed_classes' => [$this->getType()]]); + + $this->data = $data; + } + /** * @param CollectionInterface $other - * - * @throws CollectionMismatchException */ private function compareCollectionTypes(CollectionInterface $other): void { @@ -363,7 +307,7 @@ private function getComparator(): Closure * @param T $a * @param T $b */ - function (mixed $a, mixed $b): int { + function ($a, $b): int { // If the two values are object, we convert them to unique scalars. // If the collection contains mixed values (unlikely) where some are objects // and some are not, we leave them as they are. @@ -383,11 +327,15 @@ function (mixed $a, mixed $b): int { */ private function getUniformType(CollectionInterface $collection): string { - return match ($collection->getType()) { - 'integer' => 'int', - 'boolean' => 'bool', - 'double' => 'float', - default => $collection->getType(), - }; + switch ($collection->getType()) { + case 'integer': + return 'int'; + case 'boolean': + return 'bool'; + case 'double': + return 'float'; + default: + return $collection->getType(); + } } } diff --git a/vendor/ramsey/collection/src/AbstractSet.php b/vendor/ramsey/collection/src/AbstractSet.php index 7186939d7..1126ccb0a 100644 --- a/vendor/ramsey/collection/src/AbstractSet.php +++ b/vendor/ramsey/collection/src/AbstractSet.php @@ -24,7 +24,10 @@ */ abstract class AbstractSet extends AbstractCollection { - public function add(mixed $element): bool + /** + * @inheritDoc + */ + public function add($element): bool { if ($this->contains($element)) { return false; @@ -33,7 +36,10 @@ public function add(mixed $element): bool return parent::add($element); } - public function offsetSet(mixed $offset, mixed $value): void + /** + * @inheritDoc + */ + public function offsetSet($offset, $value): void { if ($this->contains($value)) { return; diff --git a/vendor/ramsey/collection/src/ArrayInterface.php b/vendor/ramsey/collection/src/ArrayInterface.php index bc7f6f424..27af6102b 100644 --- a/vendor/ramsey/collection/src/ArrayInterface.php +++ b/vendor/ramsey/collection/src/ArrayInterface.php @@ -17,6 +17,7 @@ use ArrayAccess; use Countable; use IteratorAggregate; +use Serializable; /** * `ArrayInterface` provides traversable array functionality to data types. @@ -28,7 +29,8 @@ interface ArrayInterface extends ArrayAccess, Countable, - IteratorAggregate + IteratorAggregate, + Serializable { /** * Removes all items from this array. diff --git a/vendor/ramsey/collection/src/Collection.php b/vendor/ramsey/collection/src/Collection.php index 44d26bf2e..532b971b6 100644 --- a/vendor/ramsey/collection/src/Collection.php +++ b/vendor/ramsey/collection/src/Collection.php @@ -75,16 +75,25 @@ */ class Collection extends AbstractCollection { + /** + * The type of elements stored in this collection. + * + * A collection's type is immutable once it is set. For this reason, this + * property is set private. + */ + private string $collectionType; + /** * Constructs a collection object of the specified type, optionally with the * specified data. * - * @param string $collectionType The type or class name associated with this + * @param string $collectionType The type (FQCN) associated with this * collection. * @param array $data The initial items to store in the collection. */ - public function __construct(private readonly string $collectionType, array $data = []) + public function __construct(string $collectionType, array $data = []) { + $this->collectionType = $collectionType; parent::__construct($data); } diff --git a/vendor/ramsey/collection/src/CollectionInterface.php b/vendor/ramsey/collection/src/CollectionInterface.php index e3ad01470..9f86a2837 100644 --- a/vendor/ramsey/collection/src/CollectionInterface.php +++ b/vendor/ramsey/collection/src/CollectionInterface.php @@ -14,14 +14,8 @@ namespace Ramsey\Collection; -use Ramsey\Collection\Exception\CollectionMismatchException; -use Ramsey\Collection\Exception\InvalidArgumentException; -use Ramsey\Collection\Exception\InvalidPropertyOrMethod; -use Ramsey\Collection\Exception\NoSuchElementException; -use Ramsey\Collection\Exception\UnsupportedOperationException; - /** - * A collection represents a group of values, known as its elements. + * A collection represents a group of objects, known as its elements. * * Some collections allow duplicate elements and others do not. Some are ordered * and others unordered. @@ -31,6 +25,16 @@ */ interface CollectionInterface extends ArrayInterface { + /** + * Ascending sort type. + */ + public const SORT_ASC = 'asc'; + + /** + * Descending sort type. + */ + public const SORT_DESC = 'desc'; + /** * Ensures that this collection contains the specified element (optional * operation). @@ -54,11 +58,9 @@ interface CollectionInterface extends ArrayInterface * @param T $element The element to add to the collection. * * @return bool `true` if this collection changed as a result of the call. - * - * @throws InvalidArgumentException if the collection refuses to add the - * $element for any reason other than that it already contains the element. */ - public function add(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function add($element): bool; /** * Returns `true` if this collection contains the specified element. @@ -66,7 +68,8 @@ public function add(mixed $element): bool; * @param T $element The element to check whether the collection contains. * @param bool $strict Whether to perform a strict type check on the value. */ - public function contains(mixed $element, bool $strict = true): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function contains($element, bool $strict = true): bool; /** * Returns the type associated with this collection. @@ -81,20 +84,15 @@ public function getType(): string; * * @return bool `true` if an element was removed as a result of this call. */ - public function remove(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function remove($element): bool; /** - * Returns the values from the given property, method, or array key. - * - * @param string $propertyOrMethod The name of the property, method, or - * array key to evaluate and return. + * Returns the values from the given property or method. * - * @return array + * @param string $propertyOrMethod The property or method name to filter by. * - * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist - * on the elements in this collection. - * @throws UnsupportedOperationException if unable to call column() on this - * collection. + * @return list */ public function column(string $propertyOrMethod): array; @@ -102,41 +100,29 @@ public function column(string $propertyOrMethod): array; * Returns the first item of the collection. * * @return T - * - * @throws NoSuchElementException if this collection is empty. */ - public function first(): mixed; + public function first(); /** * Returns the last item of the collection. * * @return T - * - * @throws NoSuchElementException if this collection is empty. */ - public function last(): mixed; + public function last(); /** - * Sort the collection by a property, method, or array key with the given - * sort order. - * - * If $propertyOrMethod is `null`, this will sort by comparing each element. + * Sort the collection by a property or method with the given sort order. * * This will always leave the original collection untouched and will return * a new one. * - * @param string | null $propertyOrMethod The property, method, or array key - * to sort by. - * @param Sort $order The sort order for the resulting collection. + * @param string $propertyOrMethod The property or method to sort by. + * @param string $order The sort order for the resulting collection (one of + * this interface's `SORT_*` constants). * * @return CollectionInterface - * - * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist - * on the elements in this collection. - * @throws UnsupportedOperationException if unable to call sort() on this - * collection. */ - public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascending): self; + public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): self; /** * Filter out items of the collection which don't match the criteria of @@ -148,31 +134,25 @@ public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascen * See the {@link http://php.net/manual/en/function.array-filter.php PHP array_filter() documentation} * for examples of how the `$callback` parameter works. * - * @param callable(T): bool $callback A callable to use for filtering elements. + * @param callable(T):bool $callback A callable to use for filtering elements. * * @return CollectionInterface */ public function filter(callable $callback): self; /** - * Create a new collection where the result of the given property, method, - * or array key of each item in the collection equals the given value. + * Create a new collection where items match the criteria of given callback. * * This will always leave the original collection untouched and will return * a new one. * - * @param string | null $propertyOrMethod The property, method, or array key - * to evaluate. If `null`, the element itself is compared to $value. + * @param string $propertyOrMethod The property or method to evaluate. * @param mixed $value The value to match. * * @return CollectionInterface - * - * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist - * on the elements in this collection. - * @throws UnsupportedOperationException if unable to call where() on this - * collection. */ - public function where(?string $propertyOrMethod, mixed $value): self; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function where(string $propertyOrMethod, $value): self; /** * Apply a given callback method on each item of the collection. @@ -184,7 +164,7 @@ public function where(?string $propertyOrMethod, mixed $value): self; * See the {@link http://php.net/manual/en/function.array-map.php PHP array_map() documentation} * for examples of how the `$callback` parameter works. * - * @param callable(T): TCallbackReturn $callback A callable to apply to each + * @param callable(T):TCallbackReturn $callback A callable to apply to each * item of the collection. * * @return CollectionInterface @@ -193,23 +173,6 @@ public function where(?string $propertyOrMethod, mixed $value): self; */ public function map(callable $callback): self; - /** - * Apply a given callback method on each item of the collection - * to reduce it to a single value. - * - * See the {@link http://php.net/manual/en/function.array-reduce.php PHP array_reduce() documentation} - * for examples of how the `$callback` and `$initial` parameters work. - * - * @param callable(TCarry, T): TCarry $callback A callable to apply to each - * item of the collection to reduce it to a single value. - * @param TCarry $initial This is the initial value provided to the callback. - * - * @return TCarry - * - * @template TCarry - */ - public function reduce(callable $callback, mixed $initial): mixed; - /** * Create a new collection with divergent items between current and given * collection. @@ -218,9 +181,6 @@ public function reduce(callable $callback, mixed $initial): mixed; * items. * * @return CollectionInterface - * - * @throws CollectionMismatchException if the compared collections are of - * differing types. */ public function diff(CollectionInterface $other): self; @@ -232,9 +192,6 @@ public function diff(CollectionInterface $other): self; * intersecting items. * * @return CollectionInterface - * - * @throws CollectionMismatchException if the compared collections are of - * differing types. */ public function intersect(CollectionInterface $other): self; @@ -244,10 +201,6 @@ public function intersect(CollectionInterface $other): self; * @param CollectionInterface ...$collections The collections to merge. * * @return CollectionInterface - * - * @throws CollectionMismatchException if unable to merge any of the given - * collections or items within the given collections due to type - * mismatch errors. */ public function merge(CollectionInterface ...$collections): self; } diff --git a/vendor/ramsey/collection/src/DoubleEndedQueue.php b/vendor/ramsey/collection/src/DoubleEndedQueue.php index 62947a24f..4d1f71ea4 100644 --- a/vendor/ramsey/collection/src/DoubleEndedQueue.php +++ b/vendor/ramsey/collection/src/DoubleEndedQueue.php @@ -17,10 +17,6 @@ use Ramsey\Collection\Exception\InvalidArgumentException; use Ramsey\Collection\Exception\NoSuchElementException; -use function array_key_last; -use function array_pop; -use function array_unshift; - /** * This class provides a basic implementation of `DoubleEndedQueueInterface`, to * minimize the effort required to implement this interface. @@ -32,21 +28,33 @@ class DoubleEndedQueue extends Queue implements DoubleEndedQueueInterface { /** - * Constructs a double-ended queue (dequeue) object of the specified type, - * optionally with the specified data. - * - * @param string $queueType The type or class name associated with this dequeue. - * @param array $data The initial items to store in the dequeue. + * Index of the last element in the queue. + */ + private int $tail = -1; + + /** + * @inheritDoc */ - public function __construct(private readonly string $queueType, array $data = []) + public function offsetSet($offset, $value): void { - parent::__construct($this->queueType, $data); + if ($this->checkType($this->getType(), $value) === false) { + throw new InvalidArgumentException( + 'Value must be of type ' . $this->getType() . '; value is ' + . $this->toolValueToString($value), + ); + } + + $this->tail++; + + $this->data[$this->tail] = $value; } /** * @throws InvalidArgumentException if $element is of the wrong type + * + * @inheritDoc */ - public function addFirst(mixed $element): bool + public function addFirst($element): bool { if ($this->checkType($this->getType(), $element) === false) { throw new InvalidArgumentException( @@ -55,112 +63,125 @@ public function addFirst(mixed $element): bool ); } - array_unshift($this->data, $element); + $this->index--; + + $this->data[$this->index] = $element; return true; } /** - * @throws InvalidArgumentException if $element is of the wrong type + * @inheritDoc */ - public function addLast(mixed $element): bool + public function addLast($element): bool { return $this->add($element); } - public function offerFirst(mixed $element): bool + /** + * @inheritDoc + */ + public function offerFirst($element): bool { try { return $this->addFirst($element); - } catch (InvalidArgumentException) { + } catch (InvalidArgumentException $e) { return false; } } - public function offerLast(mixed $element): bool + /** + * @inheritDoc + */ + public function offerLast($element): bool { return $this->offer($element); } /** - * @return T the first element in this queue. - * - * @throws NoSuchElementException if the queue is empty + * @inheritDoc */ - public function removeFirst(): mixed + public function removeFirst() { return $this->remove(); } /** - * @return T the last element in this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ - public function removeLast(): mixed + public function removeLast() { - return $this->pollLast() ?? throw new NoSuchElementException( - 'Can\'t return element from Queue. Queue is empty.', - ); + $tail = $this->pollLast(); + + if ($tail === null) { + throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.'); + } + + return $tail; } /** - * @return T | null the head of this queue, or `null` if this queue is empty. + * @inheritDoc */ - public function pollFirst(): mixed + public function pollFirst() { return $this->poll(); } /** - * @return T | null the tail of this queue, or `null` if this queue is empty. + * @inheritDoc */ - public function pollLast(): mixed + public function pollLast() { - return array_pop($this->data); + if ($this->count() === 0) { + return null; + } + + $tail = $this[$this->tail]; + + unset($this[$this->tail]); + $this->tail--; + + return $tail; } /** - * @return T the head of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ - public function firstElement(): mixed + public function firstElement() { return $this->element(); } /** - * @return T the tail of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ - public function lastElement(): mixed + public function lastElement() { - return $this->peekLast() ?? throw new NoSuchElementException( - 'Can\'t return element from Queue. Queue is empty.', - ); + if ($this->count() === 0) { + throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.'); + } + + return $this->data[$this->tail]; } /** - * @return T | null the head of this queue, or `null` if this queue is empty. + * @inheritDoc */ - public function peekFirst(): mixed + public function peekFirst() { return $this->peek(); } /** - * @return T | null the tail of this queue, or `null` if this queue is empty. + * @inheritDoc */ - public function peekLast(): mixed + public function peekLast() { - $lastIndex = array_key_last($this->data); - - if ($lastIndex === null) { + if ($this->count() === 0) { return null; } - return $this->data[$lastIndex]; + return $this->data[$this->tail]; } } diff --git a/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php b/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php index 15cc0e97b..3fa4ecab8 100644 --- a/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php +++ b/vendor/ramsey/collection/src/DoubleEndedQueueInterface.php @@ -181,7 +181,8 @@ interface DoubleEndedQueueInterface extends QueueInterface * Implementations should use a more-specific exception that extends * `\RuntimeException`. */ - public function addFirst(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function addFirst($element): bool; /** * Inserts the specified element at the end of this queue if it is possible @@ -201,7 +202,8 @@ public function addFirst(mixed $element): bool; * Implementations should use a more-specific exception that extends * `\RuntimeException`. */ - public function addLast(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function addLast($element): bool; /** * Inserts the specified element at the front of this queue if it is @@ -215,7 +217,8 @@ public function addLast(mixed $element): bool; * * @return bool `true` if the element was added to this queue, else `false`. */ - public function offerFirst(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function offerFirst($element): bool; /** * Inserts the specified element at the end of this queue if it is possible @@ -229,7 +232,8 @@ public function offerFirst(mixed $element): bool; * * @return bool `true` if the element was added to this queue, else `false`. */ - public function offerLast(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function offerLast($element): bool; /** * Retrieves and removes the head of this queue. @@ -241,7 +245,7 @@ public function offerLast(mixed $element): bool; * * @throws NoSuchElementException if this queue is empty. */ - public function removeFirst(): mixed; + public function removeFirst(); /** * Retrieves and removes the tail of this queue. @@ -253,23 +257,23 @@ public function removeFirst(): mixed; * * @throws NoSuchElementException if this queue is empty. */ - public function removeLast(): mixed; + public function removeLast(); /** * Retrieves and removes the head of this queue, or returns `null` if this * queue is empty. * - * @return T | null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ - public function pollFirst(): mixed; + public function pollFirst(); /** * Retrieves and removes the tail of this queue, or returns `null` if this * queue is empty. * - * @return T | null the tail of this queue, or `null` if this queue is empty. + * @return T|null the tail of this queue, or `null` if this queue is empty. */ - public function pollLast(): mixed; + public function pollLast(); /** * Retrieves, but does not remove, the head of this queue. @@ -281,7 +285,7 @@ public function pollLast(): mixed; * * @throws NoSuchElementException if this queue is empty. */ - public function firstElement(): mixed; + public function firstElement(); /** * Retrieves, but does not remove, the tail of this queue. @@ -293,21 +297,21 @@ public function firstElement(): mixed; * * @throws NoSuchElementException if this queue is empty. */ - public function lastElement(): mixed; + public function lastElement(); /** * Retrieves, but does not remove, the head of this queue, or returns `null` * if this queue is empty. * - * @return T | null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ - public function peekFirst(): mixed; + public function peekFirst(); /** * Retrieves, but does not remove, the tail of this queue, or returns `null` * if this queue is empty. * - * @return T | null the tail of this queue, or `null` if this queue is empty. + * @return T|null the tail of this queue, or `null` if this queue is empty. */ - public function peekLast(): mixed; + public function peekLast(); } diff --git a/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php b/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php index 42f5be2df..7058bcf6e 100644 --- a/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php +++ b/vendor/ramsey/collection/src/Exception/CollectionMismatchException.php @@ -19,6 +19,6 @@ /** * Thrown when attempting to operate on collections of differing types. */ -class CollectionMismatchException extends RuntimeException implements CollectionException +class CollectionMismatchException extends RuntimeException { } diff --git a/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php b/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php index 7b41b4a7c..dcc3eac60 100644 --- a/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php +++ b/vendor/ramsey/collection/src/Exception/InvalidArgumentException.php @@ -14,11 +14,9 @@ namespace Ramsey\Collection\Exception; -use InvalidArgumentException as PhpInvalidArgumentException; - /** * Thrown to indicate an argument is not of the expected type. */ -class InvalidArgumentException extends PhpInvalidArgumentException implements CollectionException +class InvalidArgumentException extends \InvalidArgumentException { } diff --git a/vendor/ramsey/collection/src/Exception/NoSuchElementException.php b/vendor/ramsey/collection/src/Exception/NoSuchElementException.php index cd98f0c0f..cabcb9d88 100644 --- a/vendor/ramsey/collection/src/Exception/NoSuchElementException.php +++ b/vendor/ramsey/collection/src/Exception/NoSuchElementException.php @@ -19,6 +19,6 @@ /** * Thrown when attempting to access an element that does not exist. */ -class NoSuchElementException extends RuntimeException implements CollectionException +class NoSuchElementException extends RuntimeException { } diff --git a/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php b/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php index c75294e53..4e9d16fa3 100644 --- a/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php +++ b/vendor/ramsey/collection/src/Exception/OutOfBoundsException.php @@ -14,11 +14,9 @@ namespace Ramsey\Collection\Exception; -use OutOfBoundsException as PhpOutOfBoundsException; - /** * Thrown when attempting to access an element out of the range of the collection. */ -class OutOfBoundsException extends PhpOutOfBoundsException implements CollectionException +class OutOfBoundsException extends \OutOfBoundsException { } diff --git a/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php b/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php index d074f45fd..9b6228971 100644 --- a/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php +++ b/vendor/ramsey/collection/src/Exception/UnsupportedOperationException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that the requested operation is not supported. */ -class UnsupportedOperationException extends RuntimeException implements CollectionException +class UnsupportedOperationException extends RuntimeException { } diff --git a/vendor/ramsey/collection/src/Map/AbstractMap.php b/vendor/ramsey/collection/src/Map/AbstractMap.php index 7a851a80f..378807289 100644 --- a/vendor/ramsey/collection/src/Map/AbstractMap.php +++ b/vendor/ramsey/collection/src/Map/AbstractMap.php @@ -16,7 +16,6 @@ use Ramsey\Collection\AbstractArray; use Ramsey\Collection\Exception\InvalidArgumentException; -use Traversable; use function array_key_exists; use function array_keys; @@ -27,37 +26,16 @@ * This class provides a basic implementation of `MapInterface`, to minimize the * effort required to implement this interface. * - * @template K of array-key * @template T * @extends AbstractArray - * @implements MapInterface + * @implements MapInterface */ abstract class AbstractMap extends AbstractArray implements MapInterface { /** - * @param array $data The initial items to add to this map. - */ - public function __construct(array $data = []) - { - parent::__construct($data); - } - - /** - * @return Traversable - */ - public function getIterator(): Traversable - { - return parent::getIterator(); - } - - /** - * @param K $offset The offset to set - * @param T $value The value to set at the given offset. - * * @inheritDoc - * @psalm-suppress MoreSpecificImplementedParamType,DocblockTypeContradiction */ - public function offsetSet(mixed $offset, mixed $value): void + public function offsetSet($offset, $value): void { if ($offset === null) { throw new InvalidArgumentException( @@ -69,12 +47,18 @@ public function offsetSet(mixed $offset, mixed $value): void $this->data[$offset] = $value; } - public function containsKey(int | string $key): bool + /** + * @inheritDoc + */ + public function containsKey($key): bool { return array_key_exists($key, $this->data); } - public function containsValue(mixed $value): bool + /** + * @inheritDoc + */ + public function containsValue($value): bool { return in_array($value, $this->data, true); } @@ -88,24 +72,21 @@ public function keys(): array } /** - * @param K $key The key to return from the map. - * @param T | null $defaultValue The default value to use if `$key` is not found. - * - * @return T | null the value or `null` if the key could not be found. + * @inheritDoc */ - public function get(int | string $key, mixed $defaultValue = null): mixed + public function get($key, $defaultValue = null) { - return $this[$key] ?? $defaultValue; + if (!$this->containsKey($key)) { + return $defaultValue; + } + + return $this[$key]; } /** - * @param K $key The key to put or replace in the map. - * @param T $value The value to store at `$key`. - * - * @return T | null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ - public function put(int | string $key, mixed $value): mixed + public function put($key, $value) { $previousValue = $this->get($key); $this[$key] = $value; @@ -114,13 +95,9 @@ public function put(int | string $key, mixed $value): mixed } /** - * @param K $key The key to put in the map. - * @param T $value The value to store at `$key`. - * - * @return T | null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ - public function putIfAbsent(int | string $key, mixed $value): mixed + public function putIfAbsent($key, $value) { $currentValue = $this->get($key); @@ -132,12 +109,9 @@ public function putIfAbsent(int | string $key, mixed $value): mixed } /** - * @param K $key The key to remove from the map. - * - * @return T | null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ - public function remove(int | string $key): mixed + public function remove($key) { $previousValue = $this->get($key); unset($this[$key]); @@ -145,7 +119,10 @@ public function remove(int | string $key): mixed return $previousValue; } - public function removeIf(int | string $key, mixed $value): bool + /** + * @inheritDoc + */ + public function removeIf($key, $value): bool { if ($this->get($key) === $value) { unset($this[$key]); @@ -157,13 +134,9 @@ public function removeIf(int | string $key, mixed $value): bool } /** - * @param K $key The key to replace. - * @param T $value The value to set at `$key`. - * - * @return T | null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ - public function replace(int | string $key, mixed $value): mixed + public function replace($key, $value) { $currentValue = $this->get($key); @@ -174,7 +147,10 @@ public function replace(int | string $key, mixed $value): mixed return $currentValue; } - public function replaceIf(int | string $key, mixed $oldValue, mixed $newValue): bool + /** + * @inheritDoc + */ + public function replaceIf($key, $oldValue, $newValue): bool { if ($this->get($key) === $oldValue) { $this[$key] = $newValue; @@ -184,20 +160,4 @@ public function replaceIf(int | string $key, mixed $oldValue, mixed $newValue): return false; } - - /** - * @return array - */ - public function __serialize(): array - { - return parent::__serialize(); - } - - /** - * @return array - */ - public function toArray(): array - { - return parent::toArray(); - } } diff --git a/vendor/ramsey/collection/src/Map/AbstractTypedMap.php b/vendor/ramsey/collection/src/Map/AbstractTypedMap.php index 92fdcd54c..486dc2e29 100644 --- a/vendor/ramsey/collection/src/Map/AbstractTypedMap.php +++ b/vendor/ramsey/collection/src/Map/AbstractTypedMap.php @@ -18,14 +18,16 @@ use Ramsey\Collection\Tool\TypeTrait; use Ramsey\Collection\Tool\ValueToStringTrait; +use function var_export; + /** * This class provides a basic implementation of `TypedMapInterface`, to * minimize the effort required to implement this interface. * * @template K of array-key * @template T - * @extends AbstractMap - * @implements TypedMapInterface + * @extends AbstractMap + * @implements TypedMapInterface */ abstract class AbstractTypedMap extends AbstractMap implements TypedMapInterface { @@ -33,14 +35,20 @@ abstract class AbstractTypedMap extends AbstractMap implements TypedMapInterface use ValueToStringTrait; /** - * @param K $offset + * @param K|null $offset * @param T $value * * @inheritDoc - * @psalm-suppress MoreSpecificImplementedParamType */ - public function offsetSet(mixed $offset, mixed $value): void + public function offsetSet($offset, $value): void { + if ($offset === null) { + throw new InvalidArgumentException( + 'Map elements are key/value pairs; a key must be provided for ' + . 'value ' . var_export($value, true), + ); + } + if ($this->checkType($this->getKeyType(), $offset) === false) { throw new InvalidArgumentException( 'Key must be of type ' . $this->getKeyType() . '; key is ' diff --git a/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php b/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php index 34e4e853b..79a314d96 100644 --- a/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php +++ b/vendor/ramsey/collection/src/Map/AssociativeArrayMap.php @@ -17,7 +17,8 @@ /** * `AssociativeArrayMap` represents a standard associative array object. * - * @extends AbstractMap + * @template T + * @extends AbstractMap */ class AssociativeArrayMap extends AbstractMap { diff --git a/vendor/ramsey/collection/src/Map/MapInterface.php b/vendor/ramsey/collection/src/Map/MapInterface.php index 22ba1bdd1..6ed0b2967 100644 --- a/vendor/ramsey/collection/src/Map/MapInterface.php +++ b/vendor/ramsey/collection/src/Map/MapInterface.php @@ -21,7 +21,6 @@ * * A map cannot contain duplicate keys; each key can map to at most one value. * - * @template K of array-key * @template T * @extends ArrayInterface */ @@ -30,9 +29,9 @@ interface MapInterface extends ArrayInterface /** * Returns `true` if this map contains a mapping for the specified key. * - * @param K $key The key to check in the map. + * @param array-key $key The key to check in the map. */ - public function containsKey(int | string $key): bool; + public function containsKey($key): bool; /** * Returns `true` if this map maps one or more keys to the specified value. @@ -41,12 +40,13 @@ public function containsKey(int | string $key): bool; * * @param T $value The value to check in the map. */ - public function containsValue(mixed $value): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function containsValue($value): bool; /** * Return an array of the keys contained in this map. * - * @return list + * @return list */ public function keys(): array; @@ -55,12 +55,13 @@ public function keys(): array; * map contains no mapping for the key, or (optionally) `$defaultValue` if * this map contains no mapping for the key. * - * @param K $key The key to return from the map. - * @param T | null $defaultValue The default value to use if `$key` is not found. + * @param array-key $key The key to return from the map. + * @param T|null $defaultValue The default value to use if `$key` is not found. * - * @return T | null the value or `null` if the key could not be found. + * @return T|null the value or `null` if the key could not be found. */ - public function get(int | string $key, mixed $defaultValue = null): mixed; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function get($key, $defaultValue = null); /** * Associates the specified value with the specified key in this map. @@ -68,13 +69,14 @@ public function get(int | string $key, mixed $defaultValue = null): mixed; * If the map previously contained a mapping for the key, the old value is * replaced by the specified value. * - * @param K $key The key to put or replace in the map. + * @param array-key $key The key to put or replace in the map. * @param T $value The value to store at `$key`. * - * @return T | null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ - public function put(int | string $key, mixed $value): mixed; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function put($key, $value); /** * Associates the specified value with the specified key in this map only if @@ -83,23 +85,25 @@ public function put(int | string $key, mixed $value): mixed; * If there is already a value associated with `$key`, this returns that * value without replacing it. * - * @param K $key The key to put in the map. + * @param array-key $key The key to put in the map. * @param T $value The value to store at `$key`. * - * @return T | null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ - public function putIfAbsent(int | string $key, mixed $value): mixed; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function putIfAbsent($key, $value); /** * Removes the mapping for a key from this map if it is present. * - * @param K $key The key to remove from the map. + * @param array-key $key The key to remove from the map. * - * @return T | null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ - public function remove(int | string $key): mixed; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function remove($key); /** * Removes the entry for the specified key only if it is currently mapped to @@ -107,24 +111,26 @@ public function remove(int | string $key): mixed; * * This performs a strict type check on the value. * - * @param K $key The key to remove from the map. + * @param array-key $key The key to remove from the map. * @param T $value The value to match. * * @return bool true if the value was removed. */ - public function removeIf(int | string $key, mixed $value): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function removeIf($key, $value): bool; /** * Replaces the entry for the specified key only if it is currently mapped * to some value. * - * @param K $key The key to replace. + * @param array-key $key The key to replace. * @param T $value The value to set at `$key`. * - * @return T | null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ - public function replace(int | string $key, mixed $value): mixed; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function replace($key, $value); /** * Replaces the entry for the specified key only if currently mapped to the @@ -132,11 +138,12 @@ public function replace(int | string $key, mixed $value): mixed; * * This performs a strict type check on the value. * - * @param K $key The key to remove from the map. + * @param array-key $key The key to remove from the map. * @param T $oldValue The value to match. * @param T $newValue The value to use as a replacement. * * @return bool true if the value was replaced. */ - public function replaceIf(int | string $key, mixed $oldValue, mixed $newValue): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function replaceIf($key, $oldValue, $newValue): bool; } diff --git a/vendor/ramsey/collection/src/Map/NamedParameterMap.php b/vendor/ramsey/collection/src/Map/NamedParameterMap.php index f948e476c..6e391e970 100644 --- a/vendor/ramsey/collection/src/Map/NamedParameterMap.php +++ b/vendor/ramsey/collection/src/Map/NamedParameterMap.php @@ -21,12 +21,13 @@ use function array_combine; use function array_key_exists; use function is_int; +use function var_export; /** * `NamedParameterMap` represents a mapping of values to a set of named keys * that may optionally be typed * - * @extends AbstractMap + * @extends AbstractMap */ class NamedParameterMap extends AbstractMap { @@ -38,13 +39,13 @@ class NamedParameterMap extends AbstractMap * * @var array */ - private readonly array $namedParameters; + protected array $namedParameters; /** * Constructs a new `NamedParameterMap`. * * @param array $namedParameters The named parameters defined for this map. - * @param array $data An initial set of data to set on this map. + * @param array $data An initial set of data to set on this map. */ public function __construct(array $namedParameters, array $data = []) { @@ -62,12 +63,22 @@ public function getNamedParameters(): array return $this->namedParameters; } - public function offsetSet(mixed $offset, mixed $value): void + /** + * @inheritDoc + */ + public function offsetSet($offset, $value): void { + if ($offset === null) { + throw new InvalidArgumentException( + 'Map elements are key/value pairs; a key must be provided for ' + . 'value ' . var_export($value, true), + ); + } + if (!array_key_exists($offset, $this->namedParameters)) { throw new InvalidArgumentException( 'Attempting to set value for unconfigured parameter \'' - . $this->toolValueToString($offset) . '\'', + . $offset . '\'', ); } diff --git a/vendor/ramsey/collection/src/Map/TypedMap.php b/vendor/ramsey/collection/src/Map/TypedMap.php index f914d9c70..77ef8d314 100644 --- a/vendor/ramsey/collection/src/Map/TypedMap.php +++ b/vendor/ramsey/collection/src/Map/TypedMap.php @@ -14,6 +14,8 @@ namespace Ramsey\Collection\Map; +use Ramsey\Collection\Tool\TypeTrait; + /** * A `TypedMap` represents a map of elements where key and value are typed. * @@ -84,6 +86,24 @@ */ class TypedMap extends AbstractTypedMap { + use TypeTrait; + + /** + * The data type of keys stored in this collection. + * + * A map key's type is immutable once it is set. For this reason, this + * property is set private. + */ + private string $keyType; + + /** + * The data type of values stored in this collection. + * + * A map value's type is immutable once it is set. For this reason, this + * property is set private. + */ + private string $valueType; + /** * Constructs a map object of the specified key and value types, * optionally with the specified data. @@ -92,11 +112,11 @@ class TypedMap extends AbstractTypedMap * @param string $valueType The data type of the map's values. * @param array $data The initial data to set for this map. */ - public function __construct( - private readonly string $keyType, - private readonly string $valueType, - array $data = [], - ) { + public function __construct(string $keyType, string $valueType, array $data = []) + { + $this->keyType = $keyType; + $this->valueType = $valueType; + parent::__construct($data); } diff --git a/vendor/ramsey/collection/src/Map/TypedMapInterface.php b/vendor/ramsey/collection/src/Map/TypedMapInterface.php index 5a44f0647..0308109cc 100644 --- a/vendor/ramsey/collection/src/Map/TypedMapInterface.php +++ b/vendor/ramsey/collection/src/Map/TypedMapInterface.php @@ -18,9 +18,8 @@ * A `TypedMapInterface` represents a map of elements where key and value are * typed. * - * @template K of array-key * @template T - * @extends MapInterface + * @extends MapInterface */ interface TypedMapInterface extends MapInterface { diff --git a/vendor/ramsey/collection/src/Queue.php b/vendor/ramsey/collection/src/Queue.php index 0f5b33740..bc8c24e1c 100644 --- a/vendor/ramsey/collection/src/Queue.php +++ b/vendor/ramsey/collection/src/Queue.php @@ -19,8 +19,6 @@ use Ramsey\Collection\Tool\TypeTrait; use Ramsey\Collection\Tool\ValueToStringTrait; -use function array_key_first; - /** * This class provides a basic implementation of `QueueInterface`, to minimize * the effort required to implement this interface. @@ -34,15 +32,29 @@ class Queue extends AbstractArray implements QueueInterface use TypeTrait; use ValueToStringTrait; + /** + * The type of elements stored in this queue. + * + * A queue's type is immutable once it is set. For this reason, this + * property is set private. + */ + private string $queueType; + + /** + * The index of the head of the queue. + */ + protected int $index = 0; + /** * Constructs a queue object of the specified type, optionally with the * specified data. * - * @param string $queueType The type or class name associated with this queue. - * @param array $data The initial items to store in the queue. + * @param string $queueType The type (FQCN) associated with this queue. + * @param array $data The initial items to store in the collection. */ - public function __construct(private readonly string $queueType, array $data = []) + public function __construct(string $queueType, array $data = []) { + $this->queueType = $queueType; parent::__construct($data); } @@ -53,9 +65,9 @@ public function __construct(private readonly string $queueType, array $data = [] * serves only to fulfill the `ArrayAccess` interface requirements. It is * invoked by other operations when adding values to the queue. * - * @throws InvalidArgumentException if $value is of the wrong type. + * @throws InvalidArgumentException if $value is of the wrong type */ - public function offsetSet(mixed $offset, mixed $value): void + public function offsetSet($offset, $value): void { if ($this->checkType($this->getType(), $value) === false) { throw new InvalidArgumentException( @@ -68,9 +80,11 @@ public function offsetSet(mixed $offset, mixed $value): void } /** - * @throws InvalidArgumentException if $value is of the wrong type. + * @throws InvalidArgumentException if $value is of the wrong type + * + * @inheritDoc */ - public function add(mixed $element): bool + public function add($element): bool { $this[] = $element; @@ -78,67 +92,74 @@ public function add(mixed $element): bool } /** - * @return T - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ - public function element(): mixed + public function element() { - return $this->peek() ?? throw new NoSuchElementException( - 'Can\'t return element from Queue. Queue is empty.', - ); + $element = $this->peek(); + + if ($element === null) { + throw new NoSuchElementException( + 'Can\'t return element from Queue. Queue is empty.', + ); + } + + return $element; } - public function offer(mixed $element): bool + /** + * @inheritDoc + */ + public function offer($element): bool { try { return $this->add($element); - } catch (InvalidArgumentException) { + } catch (InvalidArgumentException $e) { return false; } } /** - * @return T | null + * @inheritDoc */ - public function peek(): mixed + public function peek() { - $index = array_key_first($this->data); - - if ($index === null) { + if ($this->count() === 0) { return null; } - return $this[$index]; + return $this[$this->index]; } /** - * @return T | null + * @inheritDoc */ - public function poll(): mixed + public function poll() { - $index = array_key_first($this->data); - - if ($index === null) { + if ($this->count() === 0) { return null; } - $head = $this[$index]; - unset($this[$index]); + $head = $this[$this->index]; + + unset($this[$this->index]); + $this->index++; return $head; } /** - * @return T - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ - public function remove(): mixed + public function remove() { - return $this->poll() ?? throw new NoSuchElementException( - 'Can\'t return element from Queue. Queue is empty.', - ); + $head = $this->poll(); + + if ($head === null) { + throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.'); + } + + return $head; } public function getType(): string diff --git a/vendor/ramsey/collection/src/QueueInterface.php b/vendor/ramsey/collection/src/QueueInterface.php index f29ce43ab..4f91487fa 100644 --- a/vendor/ramsey/collection/src/QueueInterface.php +++ b/vendor/ramsey/collection/src/QueueInterface.php @@ -129,7 +129,8 @@ interface QueueInterface extends ArrayInterface * Implementations should use a more-specific exception that extends * `\RuntimeException`. */ - public function add(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function add($element): bool; /** * Retrieves, but does not remove, the head of this queue. @@ -143,7 +144,7 @@ public function add(mixed $element): bool; * * @throws NoSuchElementException if this queue is empty. */ - public function element(): mixed; + public function element(); /** * Inserts the specified element into this queue if it is possible to do so @@ -159,7 +160,8 @@ public function element(): mixed; * * @return bool `true` if the element was added to this queue, else `false`. */ - public function offer(mixed $element): bool; + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + public function offer($element): bool; /** * Retrieves, but does not remove, the head of this queue, or returns `null` @@ -167,9 +169,9 @@ public function offer(mixed $element): bool; * * @see self::element() * - * @return T | null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ - public function peek(): mixed; + public function peek(); /** * Retrieves and removes the head of this queue, or returns `null` @@ -177,9 +179,9 @@ public function peek(): mixed; * * @see self::remove() * - * @return T | null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ - public function poll(): mixed; + public function poll(); /** * Retrieves and removes the head of this queue. @@ -193,7 +195,7 @@ public function poll(): mixed; * * @throws NoSuchElementException if this queue is empty. */ - public function remove(): mixed; + public function remove(); /** * Returns the type associated with this queue. diff --git a/vendor/ramsey/collection/src/Set.php b/vendor/ramsey/collection/src/Set.php index aa93351c4..c1d37ccca 100644 --- a/vendor/ramsey/collection/src/Set.php +++ b/vendor/ramsey/collection/src/Set.php @@ -28,7 +28,7 @@ * $foo = new \My\Foo(); * $set = new Set(\My\Foo::class); * - * $set->add($foo); // returns TRUE, the element doesn't exist + * $set->add($foo); // returns TRUE, the element don't exists * $set->add($foo); // returns FALSE, the element already exists * * $bar = new \My\Foo(); @@ -40,15 +40,23 @@ */ class Set extends AbstractSet { + /** + * The type of elements stored in this set + * + * A set's type is immutable. For this reason, this property is private. + */ + private string $setType; + /** * Constructs a set object of the specified type, optionally with the * specified data. * - * @param string $setType The type or class name associated with this set. + * @param string $setType The type (FQCN) associated with this set. * @param array $data The initial items to store in the set. */ - public function __construct(private readonly string $setType, array $data = []) + public function __construct(string $setType, array $data = []) { + $this->setType = $setType; parent::__construct($data); } diff --git a/vendor/ramsey/collection/src/Tool/TypeTrait.php b/vendor/ramsey/collection/src/Tool/TypeTrait.php index ac51b7f10..728d44b65 100644 --- a/vendor/ramsey/collection/src/Tool/TypeTrait.php +++ b/vendor/ramsey/collection/src/Tool/TypeTrait.php @@ -36,22 +36,39 @@ trait TypeTrait * @param string $type The type to check the value against. * @param mixed $value The value to check. */ - protected function checkType(string $type, mixed $value): bool + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + protected function checkType(string $type, $value): bool { - return match ($type) { - 'array' => is_array($value), - 'bool', 'boolean' => is_bool($value), - 'callable' => is_callable($value), - 'float', 'double' => is_float($value), - 'int', 'integer' => is_int($value), - 'null' => $value === null, - 'numeric' => is_numeric($value), - 'object' => is_object($value), - 'resource' => is_resource($value), - 'scalar' => is_scalar($value), - 'string' => is_string($value), - 'mixed' => true, - default => $value instanceof $type, - }; + switch ($type) { + case 'array': + return is_array($value); + case 'bool': + case 'boolean': + return is_bool($value); + case 'callable': + return is_callable($value); + case 'float': + case 'double': + return is_float($value); + case 'int': + case 'integer': + return is_int($value); + case 'null': + return $value === null; + case 'numeric': + return is_numeric($value); + case 'object': + return is_object($value); + case 'resource': + return is_resource($value); + case 'scalar': + return is_scalar($value); + case 'string': + return is_string($value); + case 'mixed': + return true; + default: + return $value instanceof $type; + } } } diff --git a/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php b/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php index 44c422252..e10824283 100644 --- a/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php +++ b/vendor/ramsey/collection/src/Tool/ValueExtractorTrait.php @@ -14,10 +14,9 @@ namespace Ramsey\Collection\Tool; -use Ramsey\Collection\Exception\InvalidPropertyOrMethod; -use Ramsey\Collection\Exception\UnsupportedOperationException; +use Ramsey\Collection\Exception\ValueExtractionException; -use function is_array; +use function get_class; use function is_object; use function method_exists; use function property_exists; @@ -29,53 +28,34 @@ trait ValueExtractorTrait { /** - * Extracts the value of the given property, method, or array key from the - * element. + * Extracts the value of the given property or method from the object. * - * If `$propertyOrMethod` is `null`, we return the element as-is. - * - * @param mixed $element The element to extract the value from. - * @param string | null $propertyOrMethod The property or method for which the + * @param mixed $object The object to extract the value from. + * @param string $propertyOrMethod The property or method for which the * value should be extracted. * - * @return mixed the value extracted from the specified property, method, - * or array key, or the element itself. + * @return mixed the value extracted from the specified property or method. * - * @throws InvalidPropertyOrMethod - * @throws UnsupportedOperationException + * @throws ValueExtractionException if the method or property is not defined. */ - protected function extractValue(mixed $element, ?string $propertyOrMethod): mixed + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + protected function extractValue($object, string $propertyOrMethod) { - if ($propertyOrMethod === null) { - return $element; - } - - if (!is_object($element) && !is_array($element)) { - throw new UnsupportedOperationException(sprintf( - 'The collection type "%s" does not support the $propertyOrMethod parameter', - $this->getType(), - )); - } - - if (is_array($element)) { - return $element[$propertyOrMethod] ?? throw new InvalidPropertyOrMethod(sprintf( - 'Key or index "%s" not found in collection elements', - $propertyOrMethod, - )); + if (!is_object($object)) { + throw new ValueExtractionException('Unable to extract a value from a non-object'); } - if (property_exists($element, $propertyOrMethod)) { - return $element->$propertyOrMethod; + if (property_exists($object, $propertyOrMethod)) { + return $object->$propertyOrMethod; } - if (method_exists($element, $propertyOrMethod)) { - return $element->{$propertyOrMethod}(); + if (method_exists($object, $propertyOrMethod)) { + return $object->{$propertyOrMethod}(); } - throw new InvalidPropertyOrMethod(sprintf( - 'Method or property "%s" not defined in %s', - $propertyOrMethod, - $element::class, - )); + throw new ValueExtractionException( + // phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall + sprintf('Method or property "%s" not defined in %s', $propertyOrMethod, get_class($object)), + ); } } diff --git a/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php b/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php index 64fc5fa42..cacefc8b6 100644 --- a/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php +++ b/vendor/ramsey/collection/src/Tool/ValueToStringTrait.php @@ -16,7 +16,7 @@ use DateTimeInterface; -use function assert; +use function get_class; use function get_resource_type; use function is_array; use function is_bool; @@ -24,6 +24,7 @@ use function is_object; use function is_resource; use function is_scalar; +use function var_export; /** * Provides functionality to express a value as string @@ -45,7 +46,8 @@ trait ValueToStringTrait * * @param mixed $value the value to return as a string. */ - protected function toolValueToString(mixed $value): string + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + protected function toolValueToString($value): string { // null if ($value === null) { @@ -72,8 +74,12 @@ protected function toolValueToString(mixed $value): string return '(' . get_resource_type($value) . ' resource #' . (int) $value . ')'; } + // If we don't know what it is, use var_export(). + if (!is_object($value)) { + return '(' . var_export($value, true) . ')'; + } + // From here, $value should be an object. - assert(is_object($value)); // __toString() is implemented if (is_callable([$value, '__toString'])) { @@ -86,6 +92,7 @@ protected function toolValueToString(mixed $value): string } // unknown type - return '(' . $value::class . ' Object)'; + // phpcs:ignore SlevomatCodingStandard.Classes.ModernClassNameReference.ClassNameReferencedViaFunctionCall + return '(' . get_class($value) . ' Object)'; } } diff --git a/vendor/ramsey/uuid/LICENSE b/vendor/ramsey/uuid/LICENSE index 5b2acc5b7..5e06cf43b 100644 --- a/vendor/ramsey/uuid/LICENSE +++ b/vendor/ramsey/uuid/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012-2023 Ben Ramsey +Copyright (c) 2012-2021 Ben Ramsey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/ramsey/uuid/README.md b/vendor/ramsey/uuid/README.md index 0db814959..97e81a501 100644 --- a/vendor/ramsey/uuid/README.md +++ b/vendor/ramsey/uuid/README.md @@ -8,9 +8,9 @@ Source Code Download Package PHP Programming Language - Read License - Build Status - Codecov Code Coverage + Read License + Build Status + Codecov Code Coverage Psalm Type Coverage

@@ -38,7 +38,7 @@ composer require ramsey/uuid See the documentation for a thorough upgrade guide: -* [Upgrading ramsey/uuid Version 3 to 4](https://uuid.ramsey.dev/en/stable/upgrading/3-to-4.html) +* [Upgrading ramsey/uuid Version 3 to 4](https://uuid.ramsey.dev/en/latest/upgrading/3-to-4.html) ## Documentation @@ -74,10 +74,10 @@ licensed for use under the MIT License (MIT). Please see [LICENSE][] for more information. [rfc4122]: http://tools.ietf.org/html/rfc4122 -[conduct]: https://github.com/ramsey/uuid/blob/4.x/CODE_OF_CONDUCT.md +[conduct]: https://github.com/ramsey/uuid/blob/main/CODE_OF_CONDUCT.md [javauuid]: http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html [pyuuid]: http://docs.python.org/3/library/uuid.html [composer]: http://getcomposer.org/ -[contributing.md]: https://github.com/ramsey/uuid/blob/4.x/CONTRIBUTING.md -[security.md]: https://github.com/ramsey/uuid/blob/4.x/SECURITY.md -[license]: https://github.com/ramsey/uuid/blob/4.x/LICENSE +[contributing.md]: https://github.com/ramsey/uuid/blob/main/CONTRIBUTING.md +[security.md]: https://github.com/ramsey/uuid/blob/main/SECURITY.md +[license]: https://github.com/ramsey/uuid/blob/main/LICENSE diff --git a/vendor/ramsey/uuid/composer.json b/vendor/ramsey/uuid/composer.json index 9ea4e06b3..3f3b5ac42 100644 --- a/vendor/ramsey/uuid/composer.json +++ b/vendor/ramsey/uuid/composer.json @@ -1,18 +1,23 @@ { "name": "ramsey/uuid", - "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", - "license": "MIT", "type": "library", + "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", "keywords": [ "uuid", "identifier", "guid" ], + "license": "MIT", "require": { - "php": "^8.0", + "php": "^7.2 || ^8.0", "ext-json": "*", - "brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11", - "ramsey/collection": "^1.2 || ^2.0" + "brick/math": "^0.8 || ^0.9", + "ramsey/collection": "^1.0", + "symfony/polyfill-ctype": "^1.8", + "symfony/polyfill-php80": "^1.14" + }, + "replace": { + "rhumsaa/uuid": "self.version" }, "require-dev": { "captainhook/captainhook": "^5.10", @@ -21,33 +26,40 @@ "doctrine/annotations": "^1.8", "ergebnis/composer-normalize": "^2.15", "mockery/mockery": "^1.3", + "moontoast/math": "^1.1", "paragonie/random-lib": "^2", "php-mock/php-mock": "^2.2", "php-mock/php-mock-mockery": "^1.3", "php-parallel-lint/php-parallel-lint": "^1.1", "phpbench/phpbench": "^1.0", - "phpstan/extension-installer": "^1.1", - "phpstan/phpstan": "^1.8", - "phpstan/phpstan-mockery": "^1.1", - "phpstan/phpstan-phpunit": "^1.1", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-mockery": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", "phpunit/phpunit": "^8.5 || ^9", - "ramsey/composer-repl": "^1.4", - "slevomat/coding-standard": "^8.4", + "slevomat/coding-standard": "^7.0", "squizlabs/php_codesniffer": "^3.5", "vimeo/psalm": "^4.9" }, - "replace": { - "rhumsaa/uuid": "self.version" - }, "suggest": { "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", + "ext-ctype": "Enables faster processing of character classification using ctype functions.", "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." }, - "minimum-stability": "dev", - "prefer-stable": true, + "config": { + "sort-packages": true + }, + "extra": { + "branch-alias": { + "dev-main": "4.x-dev" + }, + "captainhook": { + "force-install": true + } + }, "autoload": { "psr-4": { "Ramsey\\Uuid\\": "src/" @@ -63,21 +75,8 @@ "Ramsey\\Uuid\\Test\\": "tests/" } }, - "config": { - "allow-plugins": { - "captainhook/plugin-composer": true, - "ergebnis/composer-normalize": true, - "phpstan/extension-installer": true, - "dealerdirect/phpcodesniffer-composer-installer": true, - "ramsey/composer-repl": true - }, - "sort-packages": true - }, - "extra": { - "captainhook": { - "force-install": true - } - }, + "minimum-stability": "dev", + "prefer-stable": true, "scripts": { "analyze": [ "@phpstan", @@ -90,8 +89,8 @@ "phpcbf": "phpcbf -vpw --cache=build/cache/phpcs.cache", "phpcs": "phpcs --cache=build/cache/phpcs.cache", "phpstan": [ - "phpstan analyse --no-progress --memory-limit=1G", - "phpstan analyse -c phpstan-tests.neon --no-progress --memory-limit=1G" + "phpstan analyse --no-progress", + "phpstan analyse -c phpstan-tests.neon --no-progress" ], "phpunit": "phpunit --verbose --colors=always", "phpunit-coverage": "phpunit --verbose --colors=always --coverage-html build/coverage", diff --git a/vendor/ramsey/uuid/src/Builder/BuilderCollection.php b/vendor/ramsey/uuid/src/Builder/BuilderCollection.php index 9df3110fd..89fa1e3c8 100644 --- a/vendor/ramsey/uuid/src/Builder/BuilderCollection.php +++ b/vendor/ramsey/uuid/src/Builder/BuilderCollection.php @@ -27,11 +27,6 @@ /** * A collection of UuidBuilderInterface objects * - * @deprecated this class has been deprecated, and will be removed in 5.0.0. The use-case for this class comes from - * a pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced - * at runtime: that is no longer necessary, now that you can safely verify your code to be correct, and use - * more generic types like `iterable` instead. - * * @extends AbstractCollection */ class BuilderCollection extends AbstractCollection diff --git a/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php b/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php index 20b384212..23931e416 100644 --- a/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php +++ b/vendor/ramsey/uuid/src/Builder/DegradedUuidBuilder.php @@ -30,7 +30,15 @@ */ class DegradedUuidBuilder implements UuidBuilderInterface { - private TimeConverterInterface $timeConverter; + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; /** * @param NumberConverterInterface $numberConverter The number converter to @@ -39,9 +47,10 @@ class DegradedUuidBuilder implements UuidBuilderInterface * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - private NumberConverterInterface $numberConverter, + NumberConverterInterface $numberConverter, ?TimeConverterInterface $timeConverter = null ) { + $this->numberConverter = $numberConverter; $this->timeConverter = $timeConverter ?: new DegradedTimeConverter(); } diff --git a/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php b/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php index ba5f31fbe..470d2f755 100644 --- a/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php +++ b/vendor/ramsey/uuid/src/Builder/FallbackBuilder.php @@ -28,10 +28,16 @@ class FallbackBuilder implements UuidBuilderInterface { /** - * @param iterable $builders An array of UUID builders + * @var BuilderCollection */ - public function __construct(private iterable $builders) + private $builders; + + /** + * @param BuilderCollection $builders An array of UUID builders + */ + public function __construct(BuilderCollection $builders) { + $this->builders = $builders; } /** diff --git a/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php b/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php index 04872e0bc..f11e9d50a 100644 --- a/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php +++ b/vendor/ramsey/uuid/src/Codec/GuidStringCodec.php @@ -18,7 +18,6 @@ use Ramsey\Uuid\UuidInterface; use function bin2hex; -use function sprintf; use function substr; /** @@ -30,26 +29,6 @@ */ class GuidStringCodec extends StringCodec { - public function encode(UuidInterface $uuid): string - { - $hex = bin2hex($uuid->getFields()->getBytes()); - - /** @var non-empty-string */ - return sprintf( - '%02s%02s%02s%02s-%02s%02s-%02s%02s-%04s-%012s', - substr($hex, 6, 2), - substr($hex, 4, 2), - substr($hex, 2, 2), - substr($hex, 0, 2), - substr($hex, 10, 2), - substr($hex, 8, 2), - substr($hex, 14, 2), - substr($hex, 12, 2), - substr($hex, 16, 4), - substr($hex, 20), - ); - } - public function decode(string $encodedUuid): UuidInterface { $bytes = $this->getBytes($encodedUuid); diff --git a/vendor/ramsey/uuid/src/Codec/StringCodec.php b/vendor/ramsey/uuid/src/Codec/StringCodec.php index 95f38d2e8..58c9f5806 100644 --- a/vendor/ramsey/uuid/src/Codec/StringCodec.php +++ b/vendor/ramsey/uuid/src/Codec/StringCodec.php @@ -17,13 +17,12 @@ use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Exception\InvalidUuidStringException; +use Ramsey\Uuid\Rfc4122\FieldsInterface; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; -use function bin2hex; use function hex2bin; use function implode; -use function sprintf; use function str_replace; use function strlen; use function substr; @@ -37,28 +36,36 @@ */ class StringCodec implements CodecInterface { + /** + * @var UuidBuilderInterface + */ + private $builder; + /** * Constructs a StringCodec * * @param UuidBuilderInterface $builder The builder to use when encoding UUIDs */ - public function __construct(private UuidBuilderInterface $builder) + public function __construct(UuidBuilderInterface $builder) { + $this->builder = $builder; } public function encode(UuidInterface $uuid): string { - $hex = bin2hex($uuid->getFields()->getBytes()); - - /** @var non-empty-string */ - return sprintf( - '%08s-%04s-%04s-%04s-%012s', - substr($hex, 0, 8), - substr($hex, 8, 4), - substr($hex, 12, 4), - substr($hex, 16, 4), - substr($hex, 20), - ); + /** @var FieldsInterface $fields */ + $fields = $uuid->getFields(); + + return $fields->getTimeLow()->toString() + . '-' + . $fields->getTimeMid()->toString() + . '-' + . $fields->getTimeHiAndVersion()->toString() + . '-' + . $fields->getClockSeqHiAndReserved()->toString() + . $fields->getClockSeqLow()->toString() + . '-' + . $fields->getNode()->toString(); } /** diff --git a/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php b/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php index 99b88b3bf..fef63fd00 100644 --- a/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php +++ b/vendor/ramsey/uuid/src/Converter/Number/BigNumberConverter.php @@ -27,7 +27,10 @@ */ class BigNumberConverter implements NumberConverterInterface { - private NumberConverterInterface $converter; + /** + * @var NumberConverterInterface + */ + private $converter; public function __construct() { diff --git a/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php b/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php index 043c3c43d..501eac0fa 100644 --- a/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php +++ b/vendor/ramsey/uuid/src/Converter/Number/GenericNumberConverter.php @@ -26,8 +26,14 @@ */ class GenericNumberConverter implements NumberConverterInterface { - public function __construct(private CalculatorInterface $calculator) + /** + * @var CalculatorInterface + */ + private $calculator; + + public function __construct(CalculatorInterface $calculator) { + $this->calculator = $calculator; } /** diff --git a/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php b/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php index b6bca9ee2..7390dad83 100644 --- a/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php +++ b/vendor/ramsey/uuid/src/Converter/Time/BigNumberTimeConverter.php @@ -29,7 +29,10 @@ */ class BigNumberTimeConverter implements TimeConverterInterface { - private TimeConverterInterface $converter; + /** + * @var TimeConverterInterface + */ + private $converter; public function __construct() { diff --git a/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php b/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php index f6b60abbe..a8aa64b73 100644 --- a/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php +++ b/vendor/ramsey/uuid/src/Converter/Time/GenericTimeConverter.php @@ -50,8 +50,14 @@ class GenericTimeConverter implements TimeConverterInterface */ private const MICROSECOND_INTERVALS = '10'; - public function __construct(private CalculatorInterface $calculator) + /** + * @var CalculatorInterface + */ + private $calculator; + + public function __construct(CalculatorInterface $calculator) { + $this->calculator = $calculator; } public function calculateTime(string $seconds, string $microseconds): Hexadecimal diff --git a/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php b/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php index 66009f14d..538d2f2f6 100644 --- a/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php +++ b/vendor/ramsey/uuid/src/Converter/Time/PhpTimeConverter.php @@ -58,9 +58,20 @@ class PhpTimeConverter implements TimeConverterInterface */ private const MICROSECOND_INTERVALS = 10; - private int $phpPrecision; - private CalculatorInterface $calculator; - private TimeConverterInterface $fallbackConverter; + /** + * @var CalculatorInterface + */ + private $calculator; + + /** + * @var TimeConverterInterface + */ + private $fallbackConverter; + + /** + * @var int + */ + private $phpPrecision; public function __construct( ?CalculatorInterface $calculator = null, @@ -121,11 +132,11 @@ public function convertTime(Hexadecimal $uuidTimestamp): Time } /** - * @param float|int $time The time to split into seconds and microseconds + * @param int|float $time The time to split into seconds and microseconds * * @return string[] */ - private function splitTime(float | int $time): array + private function splitTime($time): array { $split = explode('.', (string) $time, 2); diff --git a/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php b/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php index ac01a79cf..ed6d9dec8 100644 --- a/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php +++ b/vendor/ramsey/uuid/src/DeprecatedUuidInterface.php @@ -18,7 +18,8 @@ use Ramsey\Uuid\Converter\NumberConverterInterface; /** - * This interface encapsulates deprecated methods for ramsey/uuid + * This interface encapsulates deprecated methods for ramsey/uuid; this + * interface and its methods will be removed in ramsey/uuid 5.0.0. * * @psalm-immutable */ @@ -122,6 +123,12 @@ public function getTimeMidHex(): string; */ public function getTimestampHex(): string; + /** + * @deprecated In ramsey/uuid version 5.0.0, this will be removed from this + * interface. It has moved to {@see \Ramsey\Uuid\Rfc4122\UuidInterface::getUrn()}. + */ + public function getUrn(): string; + /** * @deprecated Use {@see UuidInterface::getFields()} to get a * {@see FieldsInterface} instance. If it is a diff --git a/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php b/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php index d3fbb0ccb..342829523 100644 --- a/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php +++ b/vendor/ramsey/uuid/src/DeprecatedUuidMethodsTrait.php @@ -17,8 +17,10 @@ use DateTimeImmutable; use DateTimeInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\DateTimeException; use Ramsey\Uuid\Exception\UnsupportedOperationException; +use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Throwable; use function str_pad; @@ -30,17 +32,29 @@ * This trait encapsulates deprecated methods for ramsey/uuid; this trait and * its methods will be removed in ramsey/uuid 5.0.0. * - * @deprecated This trait and its methods will be removed in ramsey/uuid 5.0.0. - * * @psalm-immutable */ trait DeprecatedUuidMethodsTrait { + /** + * @var Rfc4122FieldsInterface + */ + protected $fields; + + /** + * @var NumberConverterInterface + */ + protected $numberConverter; + + /** + * @var TimeConverterInterface + */ + protected $timeConverter; + /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()} + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeqHiAndReserved()} * and use the arbitrary-precision math library of your choice to * convert it to a string integer. */ @@ -51,9 +65,8 @@ public function getClockSeqHiAndReserved(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqHiAndReserved()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeqHiAndReserved()}. */ public function getClockSeqHiAndReservedHex(): string { @@ -62,9 +75,8 @@ public function getClockSeqHiAndReservedHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()} + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeqLow()} * and use the arbitrary-precision math library of your choice to * convert it to a string integer. */ @@ -75,9 +87,8 @@ public function getClockSeqLow(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeqLow()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeqLow()}. */ public function getClockSeqLowHex(): string { @@ -86,9 +97,8 @@ public function getClockSeqLowHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()} + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeq()} * and use the arbitrary-precision math library of your choice to * convert it to a string integer. */ @@ -99,9 +109,8 @@ public function getClockSequence(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getClockSeq()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getClockSeq()}. */ public function getClockSequenceHex(): string { @@ -148,7 +157,7 @@ public function getDateTime(): DateTimeInterface /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. + * {@see FieldsInterface} instance. * * @return string[] */ @@ -210,11 +219,10 @@ public function getMostSignificantBitsHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()} and use the - * arbitrary-precision math library of your choice to convert it to a - * string integer. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getNode()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. */ public function getNode(): string { @@ -223,9 +231,8 @@ public function getNode(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getNode()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getNode()}. */ public function getNodeHex(): string { @@ -234,9 +241,8 @@ public function getNodeHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()} + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeHiAndVersion()} * and use the arbitrary-precision math library of your choice to * convert it to a string integer. */ @@ -247,9 +253,8 @@ public function getTimeHiAndVersion(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeHiAndVersion()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeHiAndVersion()}. */ public function getTimeHiAndVersionHex(): string { @@ -258,11 +263,10 @@ public function getTimeHiAndVersionHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()} and use the - * arbitrary-precision math library of your choice to convert it to a - * string integer. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeLow()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. */ public function getTimeLow(): string { @@ -271,9 +275,8 @@ public function getTimeLow(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeLow()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeLow()}. */ public function getTimeLowHex(): string { @@ -282,11 +285,10 @@ public function getTimeLowHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()} and use the - * arbitrary-precision math library of your choice to convert it to a - * string integer. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeMid()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. */ public function getTimeMid(): string { @@ -295,9 +297,8 @@ public function getTimeMid(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimeMid()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimeMid()}. */ public function getTimeMidHex(): string { @@ -306,11 +307,10 @@ public function getTimeMidHex(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()} and use - * the arbitrary-precision math library of your choice to convert it to - * a string integer. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimestamp()} + * and use the arbitrary-precision math library of your choice to + * convert it to a string integer. */ public function getTimestamp(): string { @@ -323,9 +323,8 @@ public function getTimestamp(): string /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call - * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getTimestamp()}. + * {@see FieldsInterface} instance. If it is a {@see Rfc4122FieldsInterface} + * instance, you may call {@see Rfc4122FieldsInterface::getTimestamp()}. */ public function getTimestampHex(): string { @@ -336,9 +335,20 @@ public function getTimestampHex(): string return $this->fields->getTimestamp()->toString(); } + /** + * @deprecated This has moved to {@see Rfc4122FieldsInterface::getUrn()} and + * is available on {@see \Ramsey\Uuid\Rfc4122\UuidV1}, + * {@see \Ramsey\Uuid\Rfc4122\UuidV3}, {@see \Ramsey\Uuid\Rfc4122\UuidV4}, + * and {@see \Ramsey\Uuid\Rfc4122\UuidV5}. + */ + public function getUrn(): string + { + return 'urn:uuid:' . $this->toString(); + } + /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVariant()}. */ @@ -349,7 +359,7 @@ public function getVariant(): ?int /** * @deprecated Use {@see UuidInterface::getFields()} to get a - * {@see \Ramsey\Uuid\Fields\FieldsInterface} instance. If it is a + * {@see FieldsInterface} instance. If it is a * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface} instance, you may call * {@see \Ramsey\Uuid\Rfc4122\FieldsInterface::getVersion()}. */ diff --git a/vendor/ramsey/uuid/src/FeatureSet.php b/vendor/ramsey/uuid/src/FeatureSet.php index b9af869f9..a8ab2fdbb 100644 --- a/vendor/ramsey/uuid/src/FeatureSet.php +++ b/vendor/ramsey/uuid/src/FeatureSet.php @@ -14,6 +14,7 @@ namespace Ramsey\Uuid; +use Ramsey\Uuid\Builder\BuilderCollection; use Ramsey\Uuid\Builder\FallbackBuilder; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; @@ -35,7 +36,6 @@ use Ramsey\Uuid\Generator\RandomGeneratorInterface; use Ramsey\Uuid\Generator\TimeGeneratorFactory; use Ramsey\Uuid\Generator\TimeGeneratorInterface; -use Ramsey\Uuid\Generator\UnixTimeGenerator; use Ramsey\Uuid\Guid\GuidBuilder; use Ramsey\Uuid\Math\BrickMathCalculator; use Ramsey\Uuid\Math\CalculatorInterface; @@ -43,6 +43,7 @@ use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider; use Ramsey\Uuid\Provider\DceSecurityProviderInterface; use Ramsey\Uuid\Provider\Node\FallbackNodeProvider; +use Ramsey\Uuid\Provider\Node\NodeProviderCollection; use Ramsey\Uuid\Provider\Node\RandomNodeProvider; use Ramsey\Uuid\Provider\Node\SystemNodeProvider; use Ramsey\Uuid\Provider\NodeProviderInterface; @@ -62,25 +63,92 @@ */ class FeatureSet { - private ?TimeProviderInterface $timeProvider = null; - private CalculatorInterface $calculator; - private CodecInterface $codec; - private DceSecurityGeneratorInterface $dceSecurityGenerator; - private NameGeneratorInterface $nameGenerator; - private NodeProviderInterface $nodeProvider; - private NumberConverterInterface $numberConverter; - private RandomGeneratorInterface $randomGenerator; - private TimeConverterInterface $timeConverter; - private TimeGeneratorInterface $timeGenerator; - private TimeGeneratorInterface $unixTimeGenerator; - private UuidBuilderInterface $builder; - private ValidatorInterface $validator; + /** + * @var bool + */ + private $disableBigNumber = false; + + /** + * @var bool + */ + private $disable64Bit = false; + + /** + * @var bool + */ + private $ignoreSystemNode = false; + + /** + * @var bool + */ + private $enablePecl = false; + + /** + * @var UuidBuilderInterface + */ + private $builder; + + /** + * @var CodecInterface + */ + private $codec; + + /** + * @var DceSecurityGeneratorInterface + */ + private $dceSecurityGenerator; + + /** + * @var NameGeneratorInterface + */ + private $nameGenerator; + + /** + * @var NodeProviderInterface + */ + private $nodeProvider; + + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; + + /** + * @var RandomGeneratorInterface + */ + private $randomGenerator; + + /** + * @var TimeGeneratorInterface + */ + private $timeGenerator; + + /** + * @var TimeProviderInterface + */ + private $timeProvider; + + /** + * @var ValidatorInterface + */ + private $validator; + + /** + * @var CalculatorInterface + */ + private $calculator; /** * @param bool $useGuids True build UUIDs using the GuidStringCodec * @param bool $force32Bit True to force the use of 32-bit functionality * (primarily for testing purposes) - * @param bool $forceNoBigNumber (obsolete) + * @param bool $forceNoBigNumber True to disable the use of moontoast/math + * (primarily for testing purposes) * @param bool $ignoreSystemNode True to disable attempts to check for the * system node ID (primarily for testing purposes) * @param bool $enablePecl True to enable the use of the PeclUuidTimeGenerator @@ -88,23 +156,25 @@ class FeatureSet */ public function __construct( bool $useGuids = false, - private bool $force32Bit = false, + bool $force32Bit = false, bool $forceNoBigNumber = false, - private bool $ignoreSystemNode = false, - private bool $enablePecl = false + bool $ignoreSystemNode = false, + bool $enablePecl = false ) { - $this->randomGenerator = $this->buildRandomGenerator(); + $this->disableBigNumber = $forceNoBigNumber; + $this->disable64Bit = $force32Bit; + $this->ignoreSystemNode = $ignoreSystemNode; + $this->enablePecl = $enablePecl; + $this->setCalculator(new BrickMathCalculator()); $this->builder = $this->buildUuidBuilder($useGuids); $this->codec = $this->buildCodec($useGuids); $this->nodeProvider = $this->buildNodeProvider(); $this->nameGenerator = $this->buildNameGenerator(); + $this->randomGenerator = $this->buildRandomGenerator(); $this->setTimeProvider(new SystemTimeProvider()); $this->setDceSecurityProvider(new SystemDceSecurityProvider()); $this->validator = new GenericValidator(); - - assert($this->timeProvider !== null); - $this->unixTimeGenerator = $this->buildUnixTimeGenerator(); } /** @@ -187,14 +257,6 @@ public function getTimeGenerator(): TimeGeneratorInterface return $this->timeGenerator; } - /** - * Returns the Unix Epoch time generator configured for this environment - */ - public function getUnixTimeGenerator(): TimeGeneratorInterface - { - return $this->unixTimeGenerator; - } - /** * Returns the validator configured for this environment */ @@ -232,10 +294,7 @@ public function setDceSecurityProvider(DceSecurityProviderInterface $dceSecurity public function setNodeProvider(NodeProviderInterface $nodeProvider): void { $this->nodeProvider = $nodeProvider; - - if (isset($this->timeProvider)) { - $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); - } + $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); } /** @@ -291,10 +350,10 @@ private function buildNodeProvider(): NodeProviderInterface return new RandomNodeProvider(); } - return new FallbackNodeProvider([ + return new FallbackNodeProvider(new NodeProviderCollection([ new SystemNodeProvider(), new RandomNodeProvider(), - ]); + ])); } /** @@ -336,14 +395,6 @@ private function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGe ))->getGenerator(); } - /** - * Returns a Unix Epoch time generator configured for this environment - */ - private function buildUnixTimeGenerator(): TimeGeneratorInterface - { - return new UnixTimeGenerator($this->randomGenerator); - } - /** * Returns a name generator configured for this environment */ @@ -381,10 +432,11 @@ private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface return new GuidBuilder($this->numberConverter, $this->timeConverter); } - return new FallbackBuilder([ + /** @psalm-suppress ImpureArgument */ + return new FallbackBuilder(new BuilderCollection([ new Rfc4122UuidBuilder($this->numberConverter, $this->timeConverter), new NonstandardUuidBuilder($this->numberConverter, $this->timeConverter), - ]); + ])); } /** @@ -392,6 +444,6 @@ private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface */ private function is64BitSystem(): bool { - return PHP_INT_SIZE === 8 && !$this->force32Bit; + return PHP_INT_SIZE === 8 && !$this->disable64Bit; } } diff --git a/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php b/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php index 3d36b6f12..16e6525da 100644 --- a/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php +++ b/vendor/ramsey/uuid/src/Fields/SerializableFieldsTrait.php @@ -56,23 +56,22 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $data The serialized string representation of the object + * @param string $serialized The serialized string representation of the object * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - if (strlen($data) === 16) { - $this->__construct($data); + if (strlen($serialized) === 16) { + $this->__construct($serialized); } else { - $this->__construct(base64_decode($data)); + $this->__construct(base64_decode($serialized)); } } /** - * @param array{bytes?: string} $data - * - * @psalm-suppress UnusedMethodCall + * @param array{bytes: string} $data */ public function __unserialize(array $data): void { diff --git a/vendor/ramsey/uuid/src/Generator/CombGenerator.php b/vendor/ramsey/uuid/src/Generator/CombGenerator.php index 0e8870608..49b09381d 100644 --- a/vendor/ramsey/uuid/src/Generator/CombGenerator.php +++ b/vendor/ramsey/uuid/src/Generator/CombGenerator.php @@ -61,10 +61,22 @@ class CombGenerator implements RandomGeneratorInterface { public const TIMESTAMP_BYTES = 6; + /** + * @var RandomGeneratorInterface + */ + private $randomGenerator; + + /** + * @var NumberConverterInterface + */ + private $converter; + public function __construct( - private RandomGeneratorInterface $generator, - private NumberConverterInterface $numberConverter + RandomGeneratorInterface $generator, + NumberConverterInterface $numberConverter ) { + $this->converter = $numberConverter; + $this->randomGenerator = $generator; } /** @@ -75,7 +87,7 @@ public function __construct( */ public function generate(int $length): string { - if ($length < self::TIMESTAMP_BYTES) { + if ($length < self::TIMESTAMP_BYTES || $length < 0) { throw new InvalidArgumentException( 'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES ); @@ -83,11 +95,11 @@ public function generate(int $length): string $hash = ''; if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) { - $hash = $this->generator->generate($length - self::TIMESTAMP_BYTES); + $hash = $this->randomGenerator->generate($length - self::TIMESTAMP_BYTES); } $lsbTime = str_pad( - $this->numberConverter->toHex($this->timestamp()), + $this->converter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT diff --git a/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php b/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php index 37ba78131..aca8c5db7 100644 --- a/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php +++ b/vendor/ramsey/uuid/src/Generator/DceSecurityGenerator.php @@ -52,11 +52,29 @@ class DceSecurityGenerator implements DceSecurityGeneratorInterface */ private const CLOCK_SEQ_LOW = 0; + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var TimeGeneratorInterface + */ + private $timeGenerator; + + /** + * @var DceSecurityProviderInterface + */ + private $dceSecurityProvider; + public function __construct( - private NumberConverterInterface $numberConverter, - private TimeGeneratorInterface $timeGenerator, - private DceSecurityProviderInterface $dceSecurityProvider + NumberConverterInterface $numberConverter, + TimeGeneratorInterface $timeGenerator, + DceSecurityProviderInterface $dceSecurityProvider ) { + $this->numberConverter = $numberConverter; + $this->timeGenerator = $timeGenerator; + $this->dceSecurityProvider = $dceSecurityProvider; } public function generate( @@ -135,7 +153,8 @@ public function generate( // Replace bytes in the time-based UUID with DCE Security values. $bytes = substr_replace($bytes, $identifierBytes, 0, 4); + $bytes = substr_replace($bytes, $domainByte, 9, 1); - return substr_replace($bytes, $domainByte, 9, 1); + return $bytes; } } diff --git a/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php b/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php index ea1e2a6ff..d245c7bcc 100644 --- a/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php +++ b/vendor/ramsey/uuid/src/Generator/DefaultTimeGenerator.php @@ -23,11 +23,11 @@ use Ramsey\Uuid\Type\Hexadecimal; use Throwable; +use function ctype_xdigit; use function dechex; use function hex2bin; use function is_int; use function pack; -use function preg_match; use function sprintf; use function str_pad; use function strlen; @@ -40,11 +40,29 @@ */ class DefaultTimeGenerator implements TimeGeneratorInterface { + /** + * @var NodeProviderInterface + */ + private $nodeProvider; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; + + /** + * @var TimeProviderInterface + */ + private $timeProvider; + public function __construct( - private NodeProviderInterface $nodeProvider, - private TimeConverterInterface $timeConverter, - private TimeProviderInterface $timeProvider + NodeProviderInterface $nodeProvider, + TimeConverterInterface $timeConverter, + TimeProviderInterface $timeProvider ) { + $this->nodeProvider = $nodeProvider; + $this->timeConverter = $timeConverter; + $this->timeProvider = $timeProvider; } /** @@ -103,13 +121,13 @@ public function generate($node = null, ?int $clockSeq = null): string * Uses the node provider given when constructing this instance to get * the node ID (usually a MAC address) * - * @param int|string|null $node A node value that may be used to override the node provider + * @param string|int|null $node A node value that may be used to override the node provider * * @return string 6-byte binary string representation of the node * * @throws InvalidArgumentException */ - private function getValidNode(int | string | null $node): string + private function getValidNode($node): string { if ($node === null) { $node = $this->nodeProvider->getNode(); @@ -120,7 +138,7 @@ private function getValidNode(int | string | null $node): string $node = dechex($node); } - if (!preg_match('/^[A-Fa-f0-9]+$/', (string) $node) || strlen((string) $node) > 12) { + if (!ctype_xdigit((string) $node) || strlen((string) $node) > 12) { throw new InvalidArgumentException('Invalid node value'); } diff --git a/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php b/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php index 6a6d1aec3..3780c5c60 100644 --- a/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php +++ b/vendor/ramsey/uuid/src/Generator/PeclUuidNameGenerator.php @@ -33,16 +33,21 @@ class PeclUuidNameGenerator implements NameGeneratorInterface /** @psalm-pure */ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string { - $uuid = match ($hashAlgorithm) { - 'md5' => uuid_generate_md5($ns->toString(), $name), - 'sha1' => uuid_generate_sha1($ns->toString(), $name), - default => throw new NameException( - sprintf( + switch ($hashAlgorithm) { + case 'md5': + $uuid = uuid_generate_md5($ns->toString(), $name); + + break; + case 'sha1': + $uuid = uuid_generate_sha1($ns->toString(), $name); + + break; + default: + throw new NameException(sprintf( 'Unable to hash namespace and name with algorithm \'%s\'', $hashAlgorithm - ) - ), - }; + )); + } return uuid_parse($uuid); } diff --git a/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php b/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php index 1180b9764..5c83cb4d8 100644 --- a/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php +++ b/vendor/ramsey/uuid/src/Generator/RandomGeneratorInterface.php @@ -22,7 +22,7 @@ interface RandomGeneratorInterface /** * Generates a string of randomized binary data * - * @param int<1, max> $length The number of bytes of random binary data to generate + * @param int $length The number of bytes of random binary data to generate * * @return string A binary string */ diff --git a/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php b/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php index fd0ccc8aa..24ed56920 100644 --- a/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php +++ b/vendor/ramsey/uuid/src/Generator/RandomLibAdapter.php @@ -21,15 +21,14 @@ * RandomLibAdapter generates strings of random binary data using the * paragonie/random-lib library * - * @deprecated This class will be removed in 5.0.0. Use the default - * RandomBytesGenerator or implement your own generator that implements - * RandomGeneratorInterface. - * * @link https://packagist.org/packages/paragonie/random-lib paragonie/random-lib */ class RandomLibAdapter implements RandomGeneratorInterface { - private Generator $generator; + /** + * @var Generator + */ + private $generator; /** * Constructs a RandomLibAdapter diff --git a/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php b/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php index 8d06fc3ae..3d55fc4d6 100644 --- a/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php +++ b/vendor/ramsey/uuid/src/Generator/TimeGeneratorFactory.php @@ -24,11 +24,29 @@ */ class TimeGeneratorFactory { + /** + * @var NodeProviderInterface + */ + private $nodeProvider; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; + + /** + * @var TimeProviderInterface + */ + private $timeProvider; + public function __construct( - private NodeProviderInterface $nodeProvider, - private TimeConverterInterface $timeConverter, - private TimeProviderInterface $timeProvider + NodeProviderInterface $nodeProvider, + TimeConverterInterface $timeConverter, + TimeProviderInterface $timeProvider ) { + $this->nodeProvider = $nodeProvider; + $this->timeConverter = $timeConverter; + $this->timeProvider = $timeProvider; } /** diff --git a/vendor/ramsey/uuid/src/Guid/Fields.php b/vendor/ramsey/uuid/src/Guid/Fields.php index 0fc5d1c9b..d8a1a2b10 100644 --- a/vendor/ramsey/uuid/src/Guid/Fields.php +++ b/vendor/ramsey/uuid/src/Guid/Fields.php @@ -17,7 +17,6 @@ use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Fields\SerializableFieldsTrait; use Ramsey\Uuid\Rfc4122\FieldsInterface; -use Ramsey\Uuid\Rfc4122\MaxTrait; use Ramsey\Uuid\Rfc4122\NilTrait; use Ramsey\Uuid\Rfc4122\VariantTrait; use Ramsey\Uuid\Rfc4122\VersionTrait; @@ -45,12 +44,16 @@ */ final class Fields implements FieldsInterface { - use MaxTrait; use NilTrait; use SerializableFieldsTrait; use VariantTrait; use VersionTrait; + /** + * @var string + */ + private $bytes; + /** * @param string $bytes A 16-byte binary string representation of a UUID * @@ -58,15 +61,17 @@ final class Fields implements FieldsInterface * @throws InvalidArgumentException if the byte string does not represent a GUID * @throws InvalidArgumentException if the byte string does not contain a valid version */ - public function __construct(private string $bytes) + public function __construct(string $bytes) { - if (strlen($this->bytes) !== 16) { + if (strlen($bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' - . 'received ' . strlen($this->bytes) . ' bytes' + . 'received ' . strlen($bytes) . ' bytes' ); } + $this->bytes = $bytes; + if (!$this->isCorrectVariant()) { throw new InvalidArgumentException( 'The byte string received does not conform to the RFC ' @@ -144,13 +149,7 @@ public function getTimestamp(): Hexadecimal public function getClockSeq(): Hexadecimal { - if ($this->isMax()) { - $clockSeq = 0xffff; - } elseif ($this->isNil()) { - $clockSeq = 0x0000; - } else { - $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; - } + $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); } @@ -172,7 +171,7 @@ public function getNode(): Hexadecimal public function getVersion(): ?int { - if ($this->isNil() || $this->isMax()) { + if ($this->isNil()) { return null; } @@ -184,7 +183,7 @@ public function getVersion(): ?int private function isCorrectVariant(): bool { - if ($this->isNil() || $this->isMax()) { + if ($this->isNil()) { return true; } diff --git a/vendor/ramsey/uuid/src/Guid/GuidBuilder.php b/vendor/ramsey/uuid/src/Guid/GuidBuilder.php index c036bb20b..758dd6b7f 100644 --- a/vendor/ramsey/uuid/src/Guid/GuidBuilder.php +++ b/vendor/ramsey/uuid/src/Guid/GuidBuilder.php @@ -31,6 +31,16 @@ */ class GuidBuilder implements UuidBuilderInterface { + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; + /** * @param NumberConverterInterface $numberConverter The number converter to * use when constructing the Guid @@ -38,9 +48,11 @@ class GuidBuilder implements UuidBuilderInterface * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - private NumberConverterInterface $numberConverter, - private TimeConverterInterface $timeConverter + NumberConverterInterface $numberConverter, + TimeConverterInterface $timeConverter ) { + $this->numberConverter = $numberConverter; + $this->timeConverter = $timeConverter; } /** diff --git a/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php b/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php index c0b47bbf2..8ba757964 100644 --- a/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php +++ b/vendor/ramsey/uuid/src/Lazy/LazyUuidFromString.php @@ -18,8 +18,8 @@ use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Fields\FieldsInterface; +use Ramsey\Uuid\Nonstandard\UuidV6; use Ramsey\Uuid\Rfc4122\UuidV1; -use Ramsey\Uuid\Rfc4122\UuidV6; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\UuidFactory; @@ -55,14 +55,18 @@ final class LazyUuidFromString implements UuidInterface { public const VALID_REGEX = '/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ms'; - - private ?UuidInterface $unwrapped = null; - /** - * @psalm-param non-empty-string $uuid + * @var string + * @psalm-var non-empty-string */ - public function __construct(private string $uuid) + private $uuid; + /** @var UuidInterface|null */ + private $unwrapped; + + /** @psalm-param non-empty-string $uuid */ + public function __construct(string $uuid) { + $this->uuid = $uuid; } /** @psalm-pure */ @@ -101,20 +105,19 @@ public function __serialize(): array /** * {@inheritDoc} * - * @param string $data + * @param string $serialized * - * @psalm-param non-empty-string $data + * @psalm-param non-empty-string $serialized */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - $this->uuid = $data; + $this->uuid = $serialized; } /** - * @param array{string?: string} $data + * @param array{string: string} $data * - * @psalm-param array{string?: non-empty-string} $data - * @psalm-suppress UnusedMethodCall + * @psalm-param array{string: non-empty-string} $data */ public function __unserialize(array $data): void { diff --git a/vendor/ramsey/uuid/src/Nonstandard/Fields.php b/vendor/ramsey/uuid/src/Nonstandard/Fields.php index 5dfe61076..927bc6a26 100644 --- a/vendor/ramsey/uuid/src/Nonstandard/Fields.php +++ b/vendor/ramsey/uuid/src/Nonstandard/Fields.php @@ -47,19 +47,26 @@ final class Fields implements FieldsInterface use SerializableFieldsTrait; use VariantTrait; + /** + * @var string + */ + private $bytes; + /** * @param string $bytes A 16-byte binary string representation of a UUID * * @throws InvalidArgumentException if the byte string is not exactly 16 bytes */ - public function __construct(private string $bytes) + public function __construct(string $bytes) { - if (strlen($this->bytes) !== 16) { + if (strlen($bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' - . 'received ' . strlen($this->bytes) . ' bytes' + . 'received ' . strlen($bytes) . ' bytes' ); } + + $this->bytes = $bytes; } public function getBytes(): string @@ -123,9 +130,4 @@ public function isNil(): bool { return false; } - - public function isMax(): bool - { - return false; - } } diff --git a/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php b/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php index 82efd402f..0c8927738 100644 --- a/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php +++ b/vendor/ramsey/uuid/src/Nonstandard/UuidBuilder.php @@ -29,6 +29,16 @@ */ class UuidBuilder implements UuidBuilderInterface { + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; + /** * @param NumberConverterInterface $numberConverter The number converter to * use when constructing the Nonstandard\Uuid @@ -36,9 +46,11 @@ class UuidBuilder implements UuidBuilderInterface * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - private NumberConverterInterface $numberConverter, - private TimeConverterInterface $timeConverter + NumberConverterInterface $numberConverter, + TimeConverterInterface $timeConverter ) { + $this->numberConverter = $numberConverter; + $this->timeConverter = $timeConverter; } /** diff --git a/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php b/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php index 7497dd101..05586b3eb 100644 --- a/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php +++ b/vendor/ramsey/uuid/src/Nonstandard/UuidV6.php @@ -14,34 +14,39 @@ namespace Ramsey\Uuid\Nonstandard; +use DateTimeImmutable; +use DateTimeInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\DateTimeException; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; -use Ramsey\Uuid\Rfc4122\TimeTrait; use Ramsey\Uuid\Rfc4122\UuidInterface; use Ramsey\Uuid\Rfc4122\UuidV1; -use Ramsey\Uuid\Uuid as BaseUuid; +use Ramsey\Uuid\Uuid; +use Throwable; + +use function hex2bin; +use function str_pad; +use function substr; + +use const STR_PAD_LEFT; /** - * Reordered time, or version 6, UUIDs include timestamp, clock sequence, and - * node values that are combined into a 128-bit unsigned integer - * - * @deprecated Use {@see \Ramsey\Uuid\Rfc4122\UuidV6} instead. + * Ordered-time, or version 6, UUIDs include timestamp, clock sequence, and node + * values that are combined into a 128-bit unsigned integer * * @link https://github.com/uuid6/uuid6-ietf-draft UUID version 6 IETF draft * @link http://gh.peabody.io/uuidv6/ "Version 6" UUIDs * * @psalm-immutable */ -class UuidV6 extends BaseUuid implements UuidInterface +final class UuidV6 extends Uuid implements UuidInterface { - use TimeTrait; - /** - * Creates a version 6 (reordered time) UUID + * Creates a version 6 (time-based) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use @@ -57,16 +62,39 @@ public function __construct( CodecInterface $codec, TimeConverterInterface $timeConverter ) { - if ($fields->getVersion() !== Uuid::UUID_TYPE_REORDERED_TIME) { + if ($fields->getVersion() !== Uuid::UUID_TYPE_PEABODY) { throw new InvalidArgumentException( 'Fields used to create a UuidV6 must represent a ' - . 'version 6 (reordered time) UUID' + . 'version 6 (ordered-time) UUID' ); } parent::__construct($fields, $numberConverter, $codec, $timeConverter); } + /** + * Returns a DateTimeInterface object representing the timestamp associated + * with the UUID + * + * @return DateTimeImmutable A PHP DateTimeImmutable instance representing + * the timestamp of a version 6 UUID + */ + public function getDateTime(): DateTimeInterface + { + $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); + + try { + return new DateTimeImmutable( + '@' + . $time->getSeconds()->toString() + . '.' + . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) + ); + } catch (Throwable $e) { + throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); + } + } + /** * Converts this UUID into an instance of a version 1 UUID */ @@ -88,7 +116,7 @@ public function toUuidV1(): UuidV1 /** * Converts a version 1 UUID into an instance of a version 6 UUID */ - public static function fromUuidV1(UuidV1 $uuidV1): \Ramsey\Uuid\Rfc4122\UuidV6 + public static function fromUuidV1(UuidV1 $uuidV1): UuidV6 { $hex = $uuidV1->getHex()->toString(); $hex = substr($hex, 13, 3) diff --git a/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php b/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php index d5b6cf0c0..6d6240b7a 100644 --- a/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php +++ b/vendor/ramsey/uuid/src/Provider/Dce/SystemDceSecurityProvider.php @@ -21,6 +21,7 @@ use function escapeshellarg; use function preg_split; use function str_getcsv; +use function strpos; use function strrpos; use function strtolower; use function strtoupper; @@ -41,7 +42,6 @@ class SystemDceSecurityProvider implements DceSecurityProviderInterface */ public function getUid(): IntegerObject { - /** @var int|float|string|IntegerObject|null $uid */ static $uid = null; if ($uid instanceof IntegerObject) { @@ -72,7 +72,6 @@ public function getUid(): IntegerObject */ public function getGid(): IntegerObject { - /** @var int|float|string|IntegerObject|null $gid */ static $gid = null; if ($gid instanceof IntegerObject) { @@ -105,10 +104,15 @@ private function getSystemUid(): string return ''; } - return match ($this->getOs()) { - 'WIN' => $this->getWindowsUid(), - default => trim((string) shell_exec('id -u')), - }; + switch ($this->getOs()) { + case 'WIN': + return $this->getWindowsUid(); + case 'DAR': + case 'FRE': + case 'LIN': + default: + return trim((string) shell_exec('id -u')); + } } /** @@ -120,10 +124,15 @@ private function getSystemGid(): string return ''; } - return match ($this->getOs()) { - 'WIN' => $this->getWindowsGid(), - default => trim((string) shell_exec('id -g')), - }; + switch ($this->getOs()) { + case 'WIN': + return $this->getWindowsGid(); + case 'DAR': + case 'FRE': + case 'LIN': + default: + return trim((string) shell_exec('id -g')); + } } /** @@ -133,7 +142,7 @@ private function hasShellExec(): bool { $disabledFunctions = strtolower((string) ini_get('disable_functions')); - return !str_contains($disabledFunctions, 'shell_exec'); + return strpos($disabledFunctions, 'shell_exec') === false; } /** @@ -141,13 +150,7 @@ private function hasShellExec(): bool */ private function getOs(): string { - /** - * @psalm-suppress UnnecessaryVarAnnotation - * @var string $phpOs - */ - $phpOs = constant('PHP_OS'); - - return strtoupper(substr($phpOs, 0, 3)); + return strtoupper(substr(constant('PHP_OS'), 0, 3)); } /** @@ -226,6 +229,6 @@ private function getWindowsGid(): string return ''; } - return trim(substr($sid, $lastHyphen + 1)); + return trim((string) substr($sid, $lastHyphen + 1)); } } diff --git a/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php b/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php index d2eb20b70..cad01045c 100644 --- a/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php +++ b/vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php @@ -25,17 +25,23 @@ class FallbackNodeProvider implements NodeProviderInterface { /** - * @param iterable $providers Array of node providers + * @var NodeProviderCollection */ - public function __construct(private iterable $providers) + private $nodeProviders; + + /** + * @param NodeProviderCollection $providers Array of node providers + */ + public function __construct(NodeProviderCollection $providers) { + $this->nodeProviders = $providers; } public function getNode(): Hexadecimal { $lastProviderException = null; - foreach ($this->providers as $provider) { + foreach ($this->nodeProviders as $provider) { try { return $provider->getNode(); } catch (NodeException $exception) { diff --git a/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php b/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php index 1b979faee..536cb6034 100644 --- a/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php +++ b/vendor/ramsey/uuid/src/Provider/Node/NodeProviderCollection.php @@ -21,11 +21,6 @@ /** * A collection of NodeProviderInterface objects * - * @deprecated this class has been deprecated, and will be removed in 5.0.0. The use-case for this class comes from - * a pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced - * at runtime: that is no longer necessary, now that you can safely verify your code to be correct, and use - * more generic types like `iterable` instead. - * * @extends AbstractCollection */ class NodeProviderCollection extends AbstractCollection diff --git a/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php b/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php index 0f7536a82..51f1b02ea 100644 --- a/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php +++ b/vendor/ramsey/uuid/src/Provider/Node/StaticNodeProvider.php @@ -32,7 +32,10 @@ */ class StaticNodeProvider implements NodeProviderInterface { - private Hexadecimal $node; + /** + * @var Hexadecimal + */ + private $node; /** * @param Hexadecimal $node The static node value to use diff --git a/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php b/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php index a03c93b4d..d512f22aa 100644 --- a/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php +++ b/vendor/ramsey/uuid/src/Provider/Node/SystemNodeProvider.php @@ -27,8 +27,8 @@ use function preg_match; use function preg_match_all; use function reset; -use function str_contains; use function str_replace; +use function strpos; use function strtolower; use function strtoupper; use function substr; @@ -100,18 +100,12 @@ protected function getIfconfig(): string { $disabledFunctions = strtolower((string) ini_get('disable_functions')); - if (str_contains($disabledFunctions, 'passthru')) { + if (strpos($disabledFunctions, 'passthru') !== false) { return ''; } - /** - * @psalm-suppress UnnecessaryVarAnnotation - * @var string $phpOs - */ - $phpOs = constant('PHP_OS'); - ob_start(); - switch (strtoupper(substr($phpOs, 0, 3))) { + switch (strtoupper(substr(constant('PHP_OS'), 0, 3))) { case 'WIN': passthru('ipconfig /all 2>&1'); @@ -133,15 +127,12 @@ protected function getIfconfig(): string $ifconfig = (string) ob_get_clean(); + $node = ''; if (preg_match_all(self::IFCONFIG_PATTERN, $ifconfig, $matches, PREG_PATTERN_ORDER)) { - foreach ($matches[1] as $iface) { - if ($iface !== '00:00:00:00:00:00' && $iface !== '00-00-00-00-00-00') { - return $iface; - } - } + $node = $matches[1][0] ?? ''; } - return ''; + return $node; } /** @@ -151,20 +142,13 @@ protected function getSysfs(): string { $mac = ''; - /** - * @psalm-suppress UnnecessaryVarAnnotation - * @var string $phpOs - */ - $phpOs = constant('PHP_OS'); - - if (strtoupper($phpOs) === 'LINUX') { + if (strtoupper(constant('PHP_OS')) === 'LINUX') { $addressPaths = glob('/sys/class/net/*/address', GLOB_NOSORT); if ($addressPaths === false || count($addressPaths) === 0) { return ''; } - /** @var array $macs */ $macs = []; array_walk($addressPaths, function (string $addressPath) use (&$macs): void { @@ -173,10 +157,7 @@ protected function getSysfs(): string } }); - /** @var callable $trim */ - $trim = 'trim'; - - $macs = array_map($trim, $macs); + $macs = array_map('trim', $macs); // Remove invalid entries. $macs = array_filter($macs, function (string $address) { @@ -184,7 +165,6 @@ protected function getSysfs(): string && preg_match(self::SYSFS_PATTERN, $address); }); - /** @var string|bool $mac */ $mac = reset($macs); } diff --git a/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php b/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php index 526c8ff46..b8bfd7215 100644 --- a/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php +++ b/vendor/ramsey/uuid/src/Provider/Time/FixedTimeProvider.php @@ -19,15 +19,21 @@ use Ramsey\Uuid\Type\Time; /** - * FixedTimeProvider uses a known time to provide the time + * FixedTimeProvider uses an known time to provide the time * * This provider allows the use of a previously-generated, or known, time * when generating time-based UUIDs. */ class FixedTimeProvider implements TimeProviderInterface { - public function __construct(private Time $time) + /** + * @var Time + */ + private $fixedTime; + + public function __construct(Time $time) { + $this->fixedTime = $time; } /** @@ -37,7 +43,7 @@ public function __construct(private Time $time) */ public function setUsec($value): void { - $this->time = new Time($this->time->getSeconds(), $value); + $this->fixedTime = new Time($this->fixedTime->getSeconds(), $value); } /** @@ -47,11 +53,11 @@ public function setUsec($value): void */ public function setSec($value): void { - $this->time = new Time($value, $this->time->getMicroseconds()); + $this->fixedTime = new Time($value, $this->fixedTime->getMicroseconds()); } public function getTime(): Time { - return $this->time; + return $this->fixedTime; } } diff --git a/vendor/ramsey/uuid/src/Rfc4122/Fields.php b/vendor/ramsey/uuid/src/Rfc4122/Fields.php index 9acf810c2..2ccc20bb6 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/Fields.php +++ b/vendor/ramsey/uuid/src/Rfc4122/Fields.php @@ -40,12 +40,16 @@ */ final class Fields implements FieldsInterface { - use MaxTrait; use NilTrait; use SerializableFieldsTrait; use VariantTrait; use VersionTrait; + /** + * @var string + */ + private $bytes; + /** * @param string $bytes A 16-byte binary string representation of a UUID * @@ -53,15 +57,17 @@ final class Fields implements FieldsInterface * @throws InvalidArgumentException if the byte string does not represent an RFC 4122 UUID * @throws InvalidArgumentException if the byte string does not contain a valid version */ - public function __construct(private string $bytes) + public function __construct(string $bytes) { - if (strlen($this->bytes) !== 16) { + if (strlen($bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' - . 'received ' . strlen($this->bytes) . ' bytes' + . 'received ' . strlen($bytes) . ' bytes' ); } + $this->bytes = $bytes; + if (!$this->isCorrectVariant()) { throw new InvalidArgumentException( 'The byte string received does not conform to the RFC 4122 variant' @@ -82,13 +88,7 @@ public function getBytes(): string public function getClockSeq(): Hexadecimal { - if ($this->isMax()) { - $clockSeq = 0xffff; - } elseif ($this->isNil()) { - $clockSeq = 0x0000; - } else { - $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; - } + $clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff; return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT)); } @@ -140,53 +140,52 @@ public function getTimeMid(): Hexadecimal */ public function getTimestamp(): Hexadecimal { - $timestamp = match ($this->getVersion()) { - Uuid::UUID_TYPE_DCE_SECURITY => sprintf( - '%03x%04s%08s', - hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, - $this->getTimeMid()->toString(), - '' - ), - Uuid::UUID_TYPE_REORDERED_TIME => sprintf( - '%08s%04s%03x', - $this->getTimeLow()->toString(), - $this->getTimeMid()->toString(), - hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff - ), - // The Unix timestamp in version 7 UUIDs is a 48-bit number, - // but for consistency, we will return a 60-bit number, padded - // to the left with zeros. - Uuid::UUID_TYPE_UNIX_TIME => sprintf( - '%011s%04s', - $this->getTimeLow()->toString(), - $this->getTimeMid()->toString(), - ), - default => sprintf( - '%03x%04s%08s', - hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, - $this->getTimeMid()->toString(), - $this->getTimeLow()->toString() - ), - }; + switch ($this->getVersion()) { + case Uuid::UUID_TYPE_DCE_SECURITY: + $timestamp = sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + '' + ); + + break; + case Uuid::UUID_TYPE_PEABODY: + $timestamp = sprintf( + '%08s%04s%03x', + $this->getTimeLow()->toString(), + $this->getTimeMid()->toString(), + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff + ); + + break; + default: + $timestamp = sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + $this->getTimeLow()->toString() + ); + } return new Hexadecimal($timestamp); } public function getVersion(): ?int { - if ($this->isNil() || $this->isMax()) { + if ($this->isNil()) { return null; } - /** @var int[] $parts */ + /** @var array $parts */ $parts = unpack('n*', $this->bytes); - return $parts[4] >> 12; + return (int) $parts[4] >> 12; } private function isCorrectVariant(): bool { - if ($this->isNil() || $this->isMax()) { + if ($this->isNil()) { return true; } diff --git a/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php b/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php index 2241cf574..a303525d6 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php +++ b/vendor/ramsey/uuid/src/Rfc4122/FieldsInterface.php @@ -103,13 +103,11 @@ public function getVariant(): int; * The version number describes how the UUID was generated and has the * following meaning: * - * 1. Gregorian time UUID + * 1. Time-based UUID * 2. DCE security UUID * 3. Name-based UUID hashed with MD5 * 4. Randomly generated UUID * 5. Name-based UUID hashed with SHA-1 - * 6. Reordered time UUID - * 7. Unix Epoch time UUID * * This returns `null` if the UUID is not an RFC 4122 variant, since version * is only meaningful for this variant. diff --git a/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php b/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php index 2c2677db7..736931af2 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php +++ b/vendor/ramsey/uuid/src/Rfc4122/UuidBuilder.php @@ -17,13 +17,11 @@ use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; -use Ramsey\Uuid\Converter\Time\UnixTimeConverter; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Exception\UnableToBuildUuidException; use Ramsey\Uuid\Exception\UnsupportedOperationException; -use Ramsey\Uuid\Math\BrickMathCalculator; +use Ramsey\Uuid\Nonstandard\UuidV6; use Ramsey\Uuid\Rfc4122\UuidInterface as Rfc4122UuidInterface; -use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Throwable; @@ -34,7 +32,15 @@ */ class UuidBuilder implements UuidBuilderInterface { - private TimeConverterInterface $unixTimeConverter; + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; /** * Constructs the DefaultUuidBuilder @@ -42,18 +48,14 @@ class UuidBuilder implements UuidBuilderInterface * @param NumberConverterInterface $numberConverter The number converter to * use when constructing the Uuid * @param TimeConverterInterface $timeConverter The time converter to use - * for converting Gregorian time extracted from version 1, 2, and 6 - * UUIDs to Unix timestamps - * @param TimeConverterInterface|null $unixTimeConverter The time converter - * to use for converter Unix Epoch time extracted from version 7 UUIDs - * to Unix timestamps + * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - private NumberConverterInterface $numberConverter, - private TimeConverterInterface $timeConverter, - ?TimeConverterInterface $unixTimeConverter = null + NumberConverterInterface $numberConverter, + TimeConverterInterface $timeConverter ) { - $this->unixTimeConverter = $unixTimeConverter ?? new UnixTimeConverter(new BrickMathCalculator()); + $this->numberConverter = $numberConverter; + $this->timeConverter = $timeConverter; } /** @@ -69,34 +71,25 @@ public function __construct( public function build(CodecInterface $codec, string $bytes): UuidInterface { try { - /** @var Fields $fields */ $fields = $this->buildFields($bytes); if ($fields->isNil()) { return new NilUuid($fields, $this->numberConverter, $codec, $this->timeConverter); } - if ($fields->isMax()) { - return new MaxUuid($fields, $this->numberConverter, $codec, $this->timeConverter); - } - switch ($fields->getVersion()) { - case Uuid::UUID_TYPE_TIME: + case 1: return new UuidV1($fields, $this->numberConverter, $codec, $this->timeConverter); - case Uuid::UUID_TYPE_DCE_SECURITY: + case 2: return new UuidV2($fields, $this->numberConverter, $codec, $this->timeConverter); - case Uuid::UUID_TYPE_HASH_MD5: + case 3: return new UuidV3($fields, $this->numberConverter, $codec, $this->timeConverter); - case Uuid::UUID_TYPE_RANDOM: + case 4: return new UuidV4($fields, $this->numberConverter, $codec, $this->timeConverter); - case Uuid::UUID_TYPE_HASH_SHA1: + case 5: return new UuidV5($fields, $this->numberConverter, $codec, $this->timeConverter); - case Uuid::UUID_TYPE_REORDERED_TIME: + case 6: return new UuidV6($fields, $this->numberConverter, $codec, $this->timeConverter); - case Uuid::UUID_TYPE_UNIX_TIME: - return new UuidV7($fields, $this->numberConverter, $codec, $this->unixTimeConverter); - case Uuid::UUID_TYPE_CUSTOM: - return new UuidV8($fields, $this->numberConverter, $codec, $this->timeConverter); } throw new UnsupportedOperationException( diff --git a/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php b/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php index e80f33bef..3e4d9faee 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php +++ b/vendor/ramsey/uuid/src/Rfc4122/UuidInterface.php @@ -26,4 +26,11 @@ */ interface UuidInterface extends BaseUuidInterface { + /** + * Returns the string standard representation of the UUID as a URN + * + * @link http://en.wikipedia.org/wiki/Uniform_Resource_Name Uniform Resource Name + * @link https://tools.ietf.org/html/rfc4122#section-3 RFC 4122, § 3: Namespace Registration Template + */ + public function getUrn(): string; } diff --git a/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php b/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php index 515c038d9..764e42f84 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php +++ b/vendor/ramsey/uuid/src/Rfc4122/UuidV1.php @@ -14,25 +14,31 @@ namespace Ramsey\Uuid\Rfc4122; +use DateTimeImmutable; +use DateTimeInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\DateTimeException; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Uuid; +use Throwable; + +use function str_pad; + +use const STR_PAD_LEFT; /** - * Gregorian time, or version 1, UUIDs include timestamp, clock sequence, and node + * Time-based, or version 1, UUIDs include timestamp, clock sequence, and node * values that are combined into a 128-bit unsigned integer * * @psalm-immutable */ final class UuidV1 extends Uuid implements UuidInterface { - use TimeTrait; - /** - * Creates a version 1 (Gregorian time) UUID + * Creates a version 1 (time-based) UUID * * @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID * @param NumberConverterInterface $numberConverter The number converter to use @@ -57,4 +63,30 @@ public function __construct( parent::__construct($fields, $numberConverter, $codec, $timeConverter); } + + /** + * Returns a DateTimeInterface object representing the timestamp associated + * with the UUID + * + * The timestamp value is only meaningful in a time-based UUID, which + * has version type 1. + * + * @return DateTimeImmutable A PHP DateTimeImmutable instance representing + * the timestamp of a version 1 UUID + */ + public function getDateTime(): DateTimeInterface + { + $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); + + try { + return new DateTimeImmutable( + '@' + . $time->getSeconds()->toString() + . '.' + . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) + ); + } catch (Throwable $e) { + throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); + } + } } diff --git a/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php b/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php index c8ccbe422..74906f050 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php +++ b/vendor/ramsey/uuid/src/Rfc4122/UuidV2.php @@ -14,33 +14,28 @@ namespace Ramsey\Uuid\Rfc4122; +use DateTimeImmutable; +use DateTimeInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Exception\DateTimeException; use Ramsey\Uuid\Exception\InvalidArgumentException; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\Uuid; +use Throwable; use function hexdec; +use function str_pad; + +use const STR_PAD_LEFT; /** * DCE Security version, or version 2, UUIDs include local domain identifier, * local ID for the specified domain, and node values that are combined into a * 128-bit unsigned integer * - * It is important to note that a version 2 UUID suffers from some loss of - * fidelity of the timestamp, due to replacing the time_low field with the - * local identifier. When constructing the timestamp value for date - * purposes, we replace the local identifier bits with zeros. As a result, - * the timestamp can be off by a range of 0 to 429.4967295 seconds (or 7 - * minutes, 9 seconds, and 496730 microseconds). - * - * Astute observers might note this value directly corresponds to 2^32 - 1, - * or 0xffffffff. The local identifier is 32-bits, and we have set each of - * these bits to 0, so the maximum range of timestamp drift is 0x00000000 - * to 0xffffffff (counted in 100-nanosecond intervals). - * * @link https://publications.opengroup.org/c311 DCE 1.1: Authentication and Security Services * @link https://publications.opengroup.org/c706 DCE 1.1: Remote Procedure Call * @link https://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01 DCE 1.1: Auth & Sec, §5.2.1.1 @@ -52,8 +47,6 @@ */ final class UuidV2 extends Uuid implements UuidInterface { - use TimeTrait; - /** * Creates a version 2 (DCE Security) UUID * @@ -81,6 +74,41 @@ public function __construct( parent::__construct($fields, $numberConverter, $codec, $timeConverter); } + /** + * Returns a DateTimeInterface object representing the timestamp associated + * with the UUID + * + * It is important to note that a version 2 UUID suffers from some loss of + * fidelity of the timestamp, due to replacing the time_low field with the + * local identifier. When constructing the timestamp value for date + * purposes, we replace the local identifier bits with zeros. As a result, + * the timestamp can be off by a range of 0 to 429.4967295 seconds (or 7 + * minutes, 9 seconds, and 496730 microseconds). + * + * Astute observers might note this value directly corresponds to 2^32 - 1, + * or 0xffffffff. The local identifier is 32-bits, and we have set each of + * these bits to 0, so the maximum range of timestamp drift is 0x00000000 + * to 0xffffffff (counted in 100-nanosecond intervals). + * + * @return DateTimeImmutable A PHP DateTimeImmutable instance representing + * the timestamp of a version 2 UUID + */ + public function getDateTime(): DateTimeInterface + { + $time = $this->timeConverter->convertTime($this->fields->getTimestamp()); + + try { + return new DateTimeImmutable( + '@' + . $time->getSeconds()->toString() + . '.' + . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT) + ); + } catch (Throwable $e) { + throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e); + } + } + /** * Returns the local domain used to create this version 2 UUID */ diff --git a/vendor/ramsey/uuid/src/Rfc4122/Validator.php b/vendor/ramsey/uuid/src/Rfc4122/Validator.php index e82a11e6e..ed43c982f 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/Validator.php +++ b/vendor/ramsey/uuid/src/Rfc4122/Validator.php @@ -28,7 +28,7 @@ final class Validator implements ValidatorInterface { private const VALID_PATTERN = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-' - . '[1-8][0-9A-Fa-f]{3}-[ABab89][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}\z'; + . '[1-5]{1}[0-9A-Fa-f]{3}-[ABab89]{1}[0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}\z'; /** * @psalm-return non-empty-string @@ -43,8 +43,7 @@ public function getPattern(): string public function validate(string $uuid): bool { $uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid); - $uuid = strtolower($uuid); - return $uuid === Uuid::NIL || $uuid === Uuid::MAX || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid); + return $uuid === Uuid::NIL || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid); } } diff --git a/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php b/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php index 1041de51e..4c981658f 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php +++ b/vendor/ramsey/uuid/src/Rfc4122/VariantTrait.php @@ -19,8 +19,8 @@ use function decbin; use function str_pad; -use function str_starts_with; use function strlen; +use function strpos; use function substr; use function unpack; @@ -58,13 +58,7 @@ public function getVariant(): int throw new InvalidBytesException('Invalid number of bytes'); } - if ($this->isMax() || $this->isNil()) { - // RFC 4122 defines these special types of UUID, so we will consider - // them as belonging to the RFC 4122 variant. - return Uuid::RFC_4122; - } - - /** @var int[] $parts */ + /** @var array $parts */ $parts = unpack('n*', $this->getBytes()); // $parts[5] is a 16-bit, unsigned integer containing the variant bits @@ -73,7 +67,7 @@ public function getVariant(): int // three characters (three most-significant bits) to determine the // variant. $binary = str_pad( - decbin($parts[5]), + decbin((int) $parts[5]), 16, '0', STR_PAD_LEFT @@ -82,13 +76,15 @@ public function getVariant(): int $msb = substr($binary, 0, 3); if ($msb === '111') { - return Uuid::RESERVED_FUTURE; + $variant = Uuid::RESERVED_FUTURE; } elseif ($msb === '110') { - return Uuid::RESERVED_MICROSOFT; - } elseif (str_starts_with($msb, '10')) { - return Uuid::RFC_4122; + $variant = Uuid::RESERVED_MICROSOFT; + } elseif (strpos($msb, '10') === 0) { + $variant = Uuid::RFC_4122; + } else { + $variant = Uuid::RESERVED_NCS; } - return Uuid::RESERVED_NCS; + return $variant; } } diff --git a/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php b/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php index 0195e46c7..cee55fbef 100644 --- a/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php +++ b/vendor/ramsey/uuid/src/Rfc4122/VersionTrait.php @@ -14,8 +14,6 @@ namespace Ramsey\Uuid\Rfc4122; -use Ramsey\Uuid\Uuid; - /** * Provides common functionality for handling the version, as defined by RFC 4122 * @@ -28,11 +26,6 @@ trait VersionTrait */ abstract public function getVersion(): ?int; - /** - * Returns true if these fields represent a max UUID - */ - abstract public function isMax(): bool; - /** * Returns true if these fields represent a nil UUID */ @@ -45,16 +38,20 @@ abstract public function isNil(): bool; */ private function isCorrectVersion(): bool { - if ($this->isNil() || $this->isMax()) { + if ($this->isNil()) { return true; } - return match ($this->getVersion()) { - Uuid::UUID_TYPE_TIME, Uuid::UUID_TYPE_DCE_SECURITY, - Uuid::UUID_TYPE_HASH_MD5, Uuid::UUID_TYPE_RANDOM, - Uuid::UUID_TYPE_HASH_SHA1, Uuid::UUID_TYPE_REORDERED_TIME, - Uuid::UUID_TYPE_UNIX_TIME, Uuid::UUID_TYPE_CUSTOM => true, - default => false, - }; + switch ($this->getVersion()) { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + return true; + } + + return false; } } diff --git a/vendor/ramsey/uuid/src/Type/Decimal.php b/vendor/ramsey/uuid/src/Type/Decimal.php index acc5e754b..10f93845b 100644 --- a/vendor/ramsey/uuid/src/Type/Decimal.php +++ b/vendor/ramsey/uuid/src/Type/Decimal.php @@ -19,7 +19,6 @@ use function is_numeric; use function sprintf; -use function str_starts_with; /** * A value object representing a decimal @@ -35,10 +34,20 @@ */ final class Decimal implements NumberInterface { - private string $value; - private bool $isNegative = false; + /** + * @var string + */ + private $value; + + /** + * @var bool + */ + private $isNegative = false; - public function __construct(float | int | string | self $value) + /** + * @param mixed $value The decimal value to store + */ + public function __construct($value) { $value = (string) $value; @@ -50,7 +59,7 @@ public function __construct(float | int | string | self $value) } // Remove the leading +-symbol. - if (str_starts_with($value, '+')) { + if (strpos($value, '+') === 0) { $value = substr($value, 1); } @@ -59,7 +68,7 @@ public function __construct(float | int | string | self $value) $value = '0'; } - if (str_starts_with($value, '-')) { + if (strpos($value, '-') === 0) { $this->isNegative = true; } @@ -102,19 +111,18 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $data The serialized string representation of the object + * @param string $serialized The serialized string representation of the object * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - $this->__construct($data); + $this->__construct($serialized); } /** - * @param array{string?: string} $data - * - * @psalm-suppress UnusedMethodCall + * @param array{string: string} $data */ public function __unserialize(array $data): void { diff --git a/vendor/ramsey/uuid/src/Type/Hexadecimal.php b/vendor/ramsey/uuid/src/Type/Hexadecimal.php index bf71ec4b1..88adc2e7e 100644 --- a/vendor/ramsey/uuid/src/Type/Hexadecimal.php +++ b/vendor/ramsey/uuid/src/Type/Hexadecimal.php @@ -17,8 +17,10 @@ use Ramsey\Uuid\Exception\InvalidArgumentException; use ValueError; -use function preg_match; +use function ctype_xdigit; use function sprintf; +use function strpos; +use function strtolower; use function substr; /** @@ -32,14 +34,29 @@ */ final class Hexadecimal implements TypeInterface { - private string $value; + /** + * @var string + */ + private $value; /** - * @param self|string $value The hexadecimal value to store + * @param string $value The hexadecimal value to store */ - public function __construct(self | string $value) + public function __construct(string $value) { - $this->value = $value instanceof self ? (string) $value : $this->prepareValue($value); + $value = strtolower($value); + + if (strpos($value, '0x') === 0) { + $value = substr($value, 2); + } + + if (!ctype_xdigit($value)) { + throw new InvalidArgumentException( + 'Value must be a hexadecimal number' + ); + } + + $this->value = $value; } public function toString(): string @@ -73,17 +90,18 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $data The serialized string representation of the object + * @param string $serialized The serialized string representation of the object * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - $this->__construct($data); + $this->__construct($serialized); } /** - * @param array{string?: string} $data + * @param array{string: string} $data */ public function __unserialize(array $data): void { @@ -95,21 +113,4 @@ public function __unserialize(array $data): void $this->unserialize($data['string']); } - - private function prepareValue(string $value): string - { - $value = strtolower($value); - - if (str_starts_with($value, '0x')) { - $value = substr($value, 2); - } - - if (!preg_match('/^[A-Fa-f0-9]+$/', $value)) { - throw new InvalidArgumentException( - 'Value must be a hexadecimal number' - ); - } - - return $value; - } } diff --git a/vendor/ramsey/uuid/src/Type/Integer.php b/vendor/ramsey/uuid/src/Type/Integer.php index 50dac9934..7690f6cd8 100644 --- a/vendor/ramsey/uuid/src/Type/Integer.php +++ b/vendor/ramsey/uuid/src/Type/Integer.php @@ -17,10 +17,10 @@ use Ramsey\Uuid\Exception\InvalidArgumentException; use ValueError; -use function assert; -use function is_numeric; -use function preg_match; +use function ctype_digit; +use function ltrim; use function sprintf; +use function strpos; use function substr; /** @@ -40,13 +40,52 @@ final class Integer implements NumberInterface /** * @psalm-var numeric-string */ - private string $value; + private $value; - private bool $isNegative = false; + /** + * @var bool + */ + private $isNegative = false; - public function __construct(float | int | string | self $value) + /** + * @param mixed $value The integer value to store + */ + public function __construct($value) { - $this->value = $value instanceof self ? (string) $value : $this->prepareValue($value); + $value = (string) $value; + $sign = '+'; + + // If the value contains a sign, remove it for ctype_digit() check. + if (strpos($value, '-') === 0 || strpos($value, '+') === 0) { + $sign = substr($value, 0, 1); + $value = substr($value, 1); + } + + if (!ctype_digit($value)) { + throw new InvalidArgumentException( + 'Value must be a signed integer or a string containing only ' + . 'digits 0-9 and, optionally, a sign (+ or -)' + ); + } + + // Trim any leading zeros. + $value = ltrim($value, '0'); + + // Set to zero if the string is empty after trimming zeros. + if ($value === '') { + $value = '0'; + } + + // Add the negative sign back to the value. + if ($sign === '-' && $value !== '0') { + $value = $sign . $value; + $this->isNegative = true; + } + + /** @psalm-var numeric-string $numericValue */ + $numericValue = $value; + + $this->value = $numericValue; } public function isNegative(): bool @@ -62,9 +101,6 @@ public function toString(): string return $this->value; } - /** - * @psalm-return numeric-string - */ public function __toString(): string { return $this->toString(); @@ -91,17 +127,18 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $data The serialized string representation of the object + * @param string $serialized The serialized string representation of the object * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - $this->__construct($data); + $this->__construct($serialized); } /** - * @param array{string?: string} $data + * @param array{string: string} $data */ public function __unserialize(array $data): void { @@ -113,46 +150,4 @@ public function __unserialize(array $data): void $this->unserialize($data['string']); } - - /** - * @return numeric-string - */ - private function prepareValue(float | int | string $value): string - { - $value = (string) $value; - $sign = '+'; - - // If the value contains a sign, remove it for digit pattern check. - if (str_starts_with($value, '-') || str_starts_with($value, '+')) { - $sign = substr($value, 0, 1); - $value = substr($value, 1); - } - - if (!preg_match('/^\d+$/', $value)) { - throw new InvalidArgumentException( - 'Value must be a signed integer or a string containing only ' - . 'digits 0-9 and, optionally, a sign (+ or -)' - ); - } - - // Trim any leading zeros. - $value = ltrim($value, '0'); - - // Set to zero if the string is empty after trimming zeros. - if ($value === '') { - $value = '0'; - } - - // Add the negative sign back to the value. - if ($sign === '-' && $value !== '0') { - $value = $sign . $value; - - /** @psalm-suppress InaccessibleProperty */ - $this->isNegative = true; - } - - assert(is_numeric($value)); - - return $value; - } } diff --git a/vendor/ramsey/uuid/src/Type/Time.php b/vendor/ramsey/uuid/src/Type/Time.php index 0cedb4476..dd1b8bc28 100644 --- a/vendor/ramsey/uuid/src/Type/Time.php +++ b/vendor/ramsey/uuid/src/Type/Time.php @@ -17,6 +17,7 @@ use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Type\Integer as IntegerObject; use ValueError; +use stdClass; use function json_decode; use function json_encode; @@ -33,13 +34,22 @@ */ final class Time implements TypeInterface { - private IntegerObject $seconds; - private IntegerObject $microseconds; + /** + * @var IntegerObject + */ + private $seconds; + + /** + * @var IntegerObject + */ + private $microseconds; - public function __construct( - float | int | string | IntegerObject $seconds, - float | int | string | IntegerObject $microseconds = 0, - ) { + /** + * @param mixed $seconds + * @param mixed $microseconds + */ + public function __construct($seconds, $microseconds = 0) + { $this->seconds = new IntegerObject($seconds); $this->microseconds = new IntegerObject($microseconds); } @@ -56,7 +66,7 @@ public function getMicroseconds(): IntegerObject public function toString(): string { - return $this->seconds->toString() . '.' . sprintf('%06s', $this->microseconds->toString()); + return $this->seconds->toString() . '.' . $this->microseconds->toString(); } public function __toString(): string @@ -94,26 +104,27 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $data The serialized string representation of the object + * @param string $serialized The serialized string representation of the object * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - /** @var array{seconds?: int|float|string, microseconds?: int|float|string} $time */ - $time = json_decode($data, true); + /** @var stdClass $time */ + $time = json_decode($serialized); - if (!isset($time['seconds']) || !isset($time['microseconds'])) { + if (!isset($time->seconds) || !isset($time->microseconds)) { throw new UnsupportedOperationException( 'Attempted to unserialize an invalid value' ); } - $this->__construct($time['seconds'], $time['microseconds']); + $this->__construct($time->seconds, $time->microseconds); } /** - * @param array{seconds?: string, microseconds?: string} $data + * @param array{seconds: string, microseconds: string} $data */ public function __unserialize(array $data): void { diff --git a/vendor/ramsey/uuid/src/Uuid.php b/vendor/ramsey/uuid/src/Uuid.php index e0384a50c..945480ba4 100644 --- a/vendor/ramsey/uuid/src/Uuid.php +++ b/vendor/ramsey/uuid/src/Uuid.php @@ -14,12 +14,10 @@ namespace Ramsey\Uuid; -use BadMethodCallException; use DateTimeInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; -use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Fields\FieldsInterface; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; @@ -29,7 +27,6 @@ use function assert; use function bin2hex; -use function method_exists; use function preg_match; use function sprintf; use function str_replace; @@ -85,14 +82,6 @@ class Uuid implements UuidInterface */ public const NIL = '00000000-0000-0000-0000-000000000000'; - /** - * The max UUID is a special form of UUID that is specified to have all 128 - * bits set to one - * - * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.10 Max UUID - */ - public const MAX = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - /** * Variant: reserved, NCS backward compatibility * @@ -127,7 +116,7 @@ class Uuid implements UuidInterface public const VALID_PATTERN = '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'; /** - * Version 1 (Gregorian time) UUID + * Version 1 (time-based) UUID * * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ @@ -167,28 +156,15 @@ class Uuid implements UuidInterface public const UUID_TYPE_HASH_SHA1 = 5; /** - * @deprecated Use {@see Uuid::UUID_TYPE_REORDERED_TIME} instead. - */ - public const UUID_TYPE_PEABODY = 6; - - /** - * Version 6 (reordered time) UUID + * Version 6 (ordered-time) UUID * - * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.6 UUID Version 6 - */ - public const UUID_TYPE_REORDERED_TIME = 6; - - /** - * Version 7 (Unix Epoch time) UUID + * This is named `UUID_TYPE_PEABODY`, since the specification is still in + * draft form, and the primary author/editor's name is Brad Peabody. * - * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.7 UUID Version 7 - */ - public const UUID_TYPE_UNIX_TIME = 7; - - /** - * @link https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis-00#section-5.8 UUID Version 8 + * @link https://github.com/uuid6/uuid6-ietf-draft UUID version 6 IETF draft + * @link http://gh.peabody.io/uuidv6/ "Version 6" UUIDs */ - public const UUID_TYPE_CUSTOM = 8; + public const UUID_TYPE_PEABODY = 6; /** * DCE Security principal domain @@ -222,19 +198,38 @@ class Uuid implements UuidInterface self::DCE_DOMAIN_ORG => 'org', ]; - private static ?UuidFactoryInterface $factory = null; + /** + * @var UuidFactoryInterface|null + */ + private static $factory = null; /** - * @var bool flag to detect if the UUID factory was replaced internally, - * which disables all optimizations for the default/happy path internal - * scenarios + * @var bool flag to detect if the UUID factory was replaced internally, which disables all optimizations + * for the default/happy path internal scenarios */ - private static bool $factoryReplaced = false; + private static $factoryReplaced = false; - protected CodecInterface $codec; - protected NumberConverterInterface $numberConverter; - protected Rfc4122FieldsInterface $fields; - protected TimeConverterInterface $timeConverter; + /** + * @var CodecInterface + */ + protected $codec; + + /** + * The fields that make up this UUID + * + * @var Rfc4122FieldsInterface + */ + protected $fields; + + /** + * @var NumberConverterInterface + */ + protected $numberConverter; + + /** + * @var TimeConverterInterface + */ + protected $timeConverter; /** * Creates a universally unique identifier (UUID) from an array of fields @@ -293,7 +288,7 @@ public function jsonSerialize(): string */ public function serialize(): string { - return $this->codec->encode($this); + return $this->getFields()->getBytes(); } /** @@ -307,17 +302,19 @@ public function __serialize(): array /** * Re-constructs the object from its serialized form * - * @param string $data The serialized PHP string to unserialize into + * @param string $serialized The serialized PHP string to unserialize into * a UuidInterface instance + * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint */ - public function unserialize(string $data): void + public function unserialize($serialized): void { - if (strlen($data) === 16) { + if (strlen($serialized) === 16) { /** @var Uuid $uuid */ - $uuid = self::getFactory()->fromBytes($data); + $uuid = self::getFactory()->fromBytes($serialized); } else { /** @var Uuid $uuid */ - $uuid = self::getFactory()->fromString($data); + $uuid = self::getFactory()->fromString($serialized); } $this->codec = $uuid->codec; @@ -327,7 +324,7 @@ public function unserialize(string $data): void } /** - * @param array{bytes?: string} $data + * @param array{bytes: string} $data */ public function __unserialize(array $data): void { @@ -387,11 +384,6 @@ public function getInteger(): IntegerObject return new IntegerObject($this->numberConverter->fromHex($this->getHex()->toString())); } - public function getUrn(): string - { - return 'urn:uuid:' . $this->toString(); - } - /** * @psalm-return non-empty-string */ @@ -446,20 +438,20 @@ public static function setFactory(UuidFactoryInterface $factory): void */ public static function fromBytes(string $bytes): UuidInterface { - if (!self::$factoryReplaced && strlen($bytes) === 16) { + if (! self::$factoryReplaced && strlen($bytes) === 16) { $base16Uuid = bin2hex($bytes); // Note: we are calling `fromString` internally because we don't know if the given `$bytes` is a valid UUID return self::fromString( substr($base16Uuid, 0, 8) - . '-' - . substr($base16Uuid, 8, 4) - . '-' - . substr($base16Uuid, 12, 4) - . '-' - . substr($base16Uuid, 16, 4) - . '-' - . substr($base16Uuid, 20, 12) + . '-' + . substr($base16Uuid, 8, 4) + . '-' + . substr($base16Uuid, 12, 4) + . '-' + . substr($base16Uuid, 16, 4) + . '-' + . substr($base16Uuid, 20, 12) ); } @@ -484,11 +476,10 @@ public static function fromBytes(string $bytes): UuidInterface */ public static function fromString(string $uuid): UuidInterface { - $uuid = strtolower($uuid); - if (!self::$factoryReplaced && preg_match(LazyUuidFromString::VALID_REGEX, $uuid) === 1) { + if (! self::$factoryReplaced && preg_match(LazyUuidFromString::VALID_REGEX, $uuid) === 1) { assert($uuid !== ''); - return new LazyUuidFromString($uuid); + return new LazyUuidFromString(strtolower($uuid)); } return self::getFactory()->fromString($uuid); @@ -515,33 +506,6 @@ public static function fromDateTime( return self::getFactory()->fromDateTime($dateTime, $node, $clockSeq); } - /** - * Creates a UUID from the Hexadecimal object - * - * @param Hexadecimal $hex Hexadecimal object representing a hexadecimal number - * - * @return UuidInterface A UuidInterface instance created from the Hexadecimal - * object representing a hexadecimal number - * - * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, - * but under constant factory setups, this method operates in functionally pure manners - * @psalm-suppress MixedInferredReturnType,MixedReturnStatement - */ - public static function fromHexadecimal(Hexadecimal $hex): UuidInterface - { - $factory = self::getFactory(); - - if (method_exists($factory, 'fromHexadecimal')) { - /** - * @phpstan-ignore-next-line - * @psalm-suppress UndefinedInterfaceMethod - */ - return self::getFactory()->fromHexadecimal($hex); - } - - throw new BadMethodCallException('The method fromHexadecimal() does not exist on the provided factory'); - } - /** * Creates a UUID from a 128-bit integer string * @@ -555,7 +519,6 @@ public static function fromHexadecimal(Hexadecimal $hex): UuidInterface */ public static function fromInteger(string $integer): UuidInterface { - /** @psalm-suppress ImpureMethodCall */ return self::getFactory()->fromInteger($integer); } @@ -568,23 +531,20 @@ public static function fromInteger(string $integer): UuidInterface * * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, * but under constant factory setups, this method operates in functionally pure manners - * - * @psalm-assert-if-true =non-empty-string $uuid */ public static function isValid(string $uuid): bool { - /** @psalm-suppress ImpureMethodCall */ return self::getFactory()->getValidator()->validate($uuid); } /** - * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, + * Returns a version 1 (time-based) UUID from a host ID, sequence number, * and the current time * * @param Hexadecimal|int|string|null $node A 48-bit number representing the * hardware address; this number may be represented as an integer or a * hexadecimal string - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * @param int $clockSeq A 14-bit number used to help avoid duplicates that * could arise when the clock is set backwards in time or if the node ID * changes * @@ -683,12 +643,12 @@ public static function uuid5($ns, string $name): UuidInterface } /** - * Returns a version 6 (reordered time) UUID from a host ID, sequence number, + * Returns a version 6 (ordered-time) UUID from a host ID, sequence number, * and the current time * * @param Hexadecimal|null $node A 48-bit number representing the hardware * address - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * @param int $clockSeq A 14-bit number used to help avoid duplicates that * could arise when the clock is set backwards in time or if the node ID * changes * @@ -701,58 +661,4 @@ public static function uuid6( ): UuidInterface { return self::getFactory()->uuid6($node, $clockSeq); } - - /** - * Returns a version 7 (Unix Epoch time) UUID - * - * @param DateTimeInterface|null $dateTime An optional date/time from which - * to create the version 7 UUID. If not provided, the UUID is generated - * using the current date/time. - * - * @return UuidInterface A UuidInterface instance that represents a - * version 7 UUID - */ - public static function uuid7(?DateTimeInterface $dateTime = null): UuidInterface - { - $factory = self::getFactory(); - - if (method_exists($factory, 'uuid7')) { - /** @var UuidInterface */ - return $factory->uuid7($dateTime); - } - - throw new UnsupportedOperationException( - 'The provided factory does not support the uuid7() method', - ); - } - - /** - * Returns a version 8 (custom) UUID - * - * The bytes provided may contain any value according to your application's - * needs. Be aware, however, that other applications may not understand the - * semantics of the value. - * - * @param string $bytes A 16-byte octet string. This is an open blob - * of data that you may fill with 128 bits of information. Be aware, - * however, bits 48 through 51 will be replaced with the UUID version - * field, and bits 64 and 65 will be replaced with the UUID variant. You - * MUST NOT rely on these bits for your application needs. - * - * @return UuidInterface A UuidInterface instance that represents a - * version 8 UUID - */ - public static function uuid8(string $bytes): UuidInterface - { - $factory = self::getFactory(); - - if (method_exists($factory, 'uuid8')) { - /** @var UuidInterface */ - return $factory->uuid8($bytes); - } - - throw new UnsupportedOperationException( - 'The provided factory does not support the uuid8() method', - ); - } } diff --git a/vendor/ramsey/uuid/src/UuidFactory.php b/vendor/ramsey/uuid/src/UuidFactory.php index 1b06ea6ed..6f2cea061 100644 --- a/vendor/ramsey/uuid/src/UuidFactory.php +++ b/vendor/ramsey/uuid/src/UuidFactory.php @@ -24,7 +24,6 @@ use Ramsey\Uuid\Generator\NameGeneratorInterface; use Ramsey\Uuid\Generator\RandomGeneratorInterface; use Ramsey\Uuid\Generator\TimeGeneratorInterface; -use Ramsey\Uuid\Generator\UnixTimeGenerator; use Ramsey\Uuid\Lazy\LazyUuidFromString; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\Time\FixedTimeProvider; @@ -46,26 +45,61 @@ class UuidFactory implements UuidFactoryInterface { - private CodecInterface $codec; - private DceSecurityGeneratorInterface $dceSecurityGenerator; - private NameGeneratorInterface $nameGenerator; - private NodeProviderInterface $nodeProvider; - private NumberConverterInterface $numberConverter; - private RandomGeneratorInterface $randomGenerator; - private TimeConverterInterface $timeConverter; - private TimeGeneratorInterface $timeGenerator; - private TimeGeneratorInterface $unixTimeGenerator; - private UuidBuilderInterface $uuidBuilder; - private ValidatorInterface $validator; + /** + * @var CodecInterface + */ + private $codec; + + /** + * @var DceSecurityGeneratorInterface + */ + private $dceSecurityGenerator; + + /** + * @var NameGeneratorInterface + */ + private $nameGenerator; + + /** + * @var NodeProviderInterface + */ + private $nodeProvider; + + /** + * @var NumberConverterInterface + */ + private $numberConverter; + + /** + * @var RandomGeneratorInterface + */ + private $randomGenerator; + + /** + * @var TimeConverterInterface + */ + private $timeConverter; /** - * @var bool whether the feature set was provided from outside, or we can - * operate under "default" assumptions + * @var TimeGeneratorInterface */ - private bool $isDefaultFeatureSet; + private $timeGenerator; /** - * @param FeatureSet|null $features A set of available features in the current environment + * @var UuidBuilderInterface + */ + private $uuidBuilder; + + /** + * @var ValidatorInterface + */ + private $validator; + + /** @var bool whether the feature set was provided from outside, or we can operate under "default" assumptions */ + private $isDefaultFeatureSet; + + /** + * @param FeatureSet $features A set of available features in the current environment */ public function __construct(?FeatureSet $features = null) { @@ -83,7 +117,6 @@ public function __construct(?FeatureSet $features = null) $this->timeGenerator = $features->getTimeGenerator(); $this->uuidBuilder = $features->getBuilder(); $this->validator = $features->getValidator(); - $this->unixTimeGenerator = $features->getUnixTimeGenerator(); } /** @@ -309,15 +342,7 @@ public function fromDateTime( $bytes = $timeGenerator->generate($nodeHex, $clockSeq); - return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_TIME); - } - - /** - * @psalm-pure - */ - public function fromHexadecimal(Hexadecimal $hex): UuidInterface - { - return $this->codec->decode($hex->__toString()); + return $this->uuidFromBytesAndVersion($bytes, 1); } /** @@ -327,7 +352,7 @@ public function uuid1($node = null, ?int $clockSeq = null): UuidInterface { $bytes = $this->timeGenerator->generate($node, $clockSeq); - return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_TIME); + return $this->uuidFromBytesAndVersion($bytes, 1); } public function uuid2( @@ -343,7 +368,7 @@ public function uuid2( $clockSeq ); - return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_DCE_SECURITY); + return $this->uuidFromBytesAndVersion($bytes, 2); } /** @@ -352,14 +377,14 @@ public function uuid2( */ public function uuid3($ns, string $name): UuidInterface { - return $this->uuidFromNsAndName($ns, $name, Uuid::UUID_TYPE_HASH_MD5, 'md5'); + return $this->uuidFromNsAndName($ns, $name, 3, 'md5'); } public function uuid4(): UuidInterface { $bytes = $this->randomGenerator->generate(16); - return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_RANDOM); + return $this->uuidFromBytesAndVersion($bytes, 4); } /** @@ -368,7 +393,7 @@ public function uuid4(): UuidInterface */ public function uuid5($ns, string $name): UuidInterface { - return $this->uuidFromNsAndName($ns, $name, Uuid::UUID_TYPE_HASH_SHA1, 'sha1'); + return $this->uuidFromNsAndName($ns, $name, 5, 'sha1'); } public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface @@ -387,46 +412,7 @@ public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInt $v6Bytes = hex2bin(substr($v6, 1, 12) . '0' . substr($v6, -3)); $v6Bytes .= substr($bytes, 8); - return $this->uuidFromBytesAndVersion($v6Bytes, Uuid::UUID_TYPE_REORDERED_TIME); - } - - /** - * Returns a version 7 (Unix Epoch time) UUID - * - * @param DateTimeInterface|null $dateTime An optional date/time from which - * to create the version 7 UUID. If not provided, the UUID is generated - * using the current date/time. - * - * @return UuidInterface A UuidInterface instance that represents a - * version 7 UUID - */ - public function uuid7(?DateTimeInterface $dateTime = null): UuidInterface - { - assert($this->unixTimeGenerator instanceof UnixTimeGenerator); - $bytes = $this->unixTimeGenerator->generate(null, null, $dateTime); - - return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_UNIX_TIME); - } - - /** - * Returns a version 8 (Custom) UUID - * - * The bytes provided may contain any value according to your application's - * needs. Be aware, however, that other applications may not understand the - * semantics of the value. - * - * @param string $bytes A 16-byte octet string. This is an open blob - * of data that you may fill with 128 bits of information. Be aware, - * however, bits 48 through 51 will be replaced with the UUID version - * field, and bits 64 and 65 will be replaced with the UUID variant. You - * MUST NOT rely on these bits for your application needs. - * - * @return UuidInterface A UuidInterface instance that represents a - * version 8 UUID - */ - public function uuid8(string $bytes): UuidInterface - { - return $this->uuidFromBytesAndVersion($bytes, Uuid::UUID_TYPE_CUSTOM); + return $this->uuidFromBytesAndVersion($v6Bytes, 6); } /** @@ -444,7 +430,6 @@ public function uuid8(string $bytes): UuidInterface */ public function uuid(string $bytes): UuidInterface { - /** @psalm-suppress ImpurePropertyFetch */ return $this->uuidBuilder->build($this->codec, $bytes); } @@ -462,12 +447,8 @@ public function uuid(string $bytes): UuidInterface * * @psalm-pure */ - private function uuidFromNsAndName( - UuidInterface | string $ns, - string $name, - int $version, - string $hashAlgorithm - ): UuidInterface { + private function uuidFromNsAndName($ns, string $name, int $version, string $hashAlgorithm): UuidInterface + { if (!($ns instanceof UuidInterface)) { $ns = $this->fromString($ns); } @@ -507,7 +488,6 @@ private function uuidFromBytesAndVersion(string $bytes, int $version): UuidInter return LazyUuidFromString::fromBytes($bytes); } - /** @psalm-suppress ImpureVariable */ return $this->uuid($bytes); } } diff --git a/vendor/ramsey/uuid/src/UuidFactoryInterface.php b/vendor/ramsey/uuid/src/UuidFactoryInterface.php index d99fc9d58..468cc6377 100644 --- a/vendor/ramsey/uuid/src/UuidFactoryInterface.php +++ b/vendor/ramsey/uuid/src/UuidFactoryInterface.php @@ -25,61 +25,6 @@ */ interface UuidFactoryInterface { - /** - * Creates a UUID from a byte string - * - * @param string $bytes A binary string - * - * @return UuidInterface A UuidInterface instance created from a binary - * string representation - * - * @psalm-pure - */ - public function fromBytes(string $bytes): UuidInterface; - - /** - * Creates a UUID from a DateTimeInterface instance - * - * @param DateTimeInterface $dateTime The date and time - * @param Hexadecimal|null $node A 48-bit number representing the hardware - * address - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates - * that could arise when the clock is set backwards in time or if the - * node ID changes - * - * @return UuidInterface A UuidInterface instance that represents a - * version 1 UUID created from a DateTimeInterface instance - */ - public function fromDateTime( - DateTimeInterface $dateTime, - ?Hexadecimal $node = null, - ?int $clockSeq = null - ): UuidInterface; - - /** - * Creates a UUID from a 128-bit integer string - * - * @param string $integer String representation of 128-bit integer - * - * @return UuidInterface A UuidInterface instance created from the string - * representation of a 128-bit integer - * - * @psalm-pure - */ - public function fromInteger(string $integer): UuidInterface; - - /** - * Creates a UUID from the string standard representation - * - * @param string $uuid A hexadecimal string - * - * @return UuidInterface A UuidInterface instance created from a hexadecimal - * string representation - * - * @psalm-pure - */ - public function fromString(string $uuid): UuidInterface; - /** * Returns the validator to use for the factory * @@ -88,7 +33,7 @@ public function fromString(string $uuid): UuidInterface; public function getValidator(): ValidatorInterface; /** - * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, + * Returns a version 1 (time-based) UUID from a host ID, sequence number, * and the current time * * @param Hexadecimal|int|string|null $node A 48-bit number representing the @@ -166,7 +111,7 @@ public function uuid4(): UuidInterface; public function uuid5($ns, string $name): UuidInterface; /** - * Returns a version 6 (reordered time) UUID from a host ID, sequence number, + * Returns a version 6 (ordered-time) UUID from a host ID, sequence number, * and the current time * * @param Hexadecimal|null $node A 48-bit number representing the hardware @@ -179,4 +124,59 @@ public function uuid5($ns, string $name): UuidInterface; * version 6 UUID */ public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface; + + /** + * Creates a UUID from a byte string + * + * @param string $bytes A binary string + * + * @return UuidInterface A UuidInterface instance created from a binary + * string representation + * + * @psalm-pure + */ + public function fromBytes(string $bytes): UuidInterface; + + /** + * Creates a UUID from the string standard representation + * + * @param string $uuid A hexadecimal string + * + * @return UuidInterface A UuidInterface instance created from a hexadecimal + * string representation + * + * @psalm-pure + */ + public function fromString(string $uuid): UuidInterface; + + /** + * Creates a UUID from a 128-bit integer string + * + * @param string $integer String representation of 128-bit integer + * + * @return UuidInterface A UuidInterface instance created from the string + * representation of a 128-bit integer + * + * @psalm-pure + */ + public function fromInteger(string $integer): UuidInterface; + + /** + * Creates a UUID from a DateTimeInterface instance + * + * @param DateTimeInterface $dateTime The date and time + * @param Hexadecimal|null $node A 48-bit number representing the hardware + * address + * @param int|null $clockSeq A 14-bit number used to help avoid duplicates + * that could arise when the clock is set backwards in time or if the + * node ID changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID created from a DateTimeInterface instance + */ + public function fromDateTime( + DateTimeInterface $dateTime, + ?Hexadecimal $node = null, + ?int $clockSeq = null + ): UuidInterface; } diff --git a/vendor/ramsey/uuid/src/UuidInterface.php b/vendor/ramsey/uuid/src/UuidInterface.php index cac9457de..f22eb0f99 100644 --- a/vendor/ramsey/uuid/src/UuidInterface.php +++ b/vendor/ramsey/uuid/src/UuidInterface.php @@ -19,7 +19,6 @@ use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; use Serializable; -use Stringable; /** * A UUID is a universally unique identifier adhering to an agreed-upon @@ -30,8 +29,7 @@ interface UuidInterface extends DeprecatedUuidInterface, JsonSerializable, - Serializable, - Stringable + Serializable { /** * Returns -1, 0, or 1 if the UUID is less than, equal to, or greater than @@ -46,7 +44,7 @@ interface UuidInterface extends * * @param UuidInterface $other The UUID to compare * - * @return int<-1,1> -1, 0, or 1 if the UUID is less than, equal to, or greater than $other + * @return int -1, 0, or 1 if the UUID is less than, equal to, or greater than $other */ public function compareTo(UuidInterface $other): int; @@ -85,14 +83,6 @@ public function getHex(): Hexadecimal; */ public function getInteger(): IntegerObject; - /** - * Returns the string standard representation of the UUID as a URN - * - * @link http://en.wikipedia.org/wiki/Uniform_Resource_Name Uniform Resource Name - * @link https://tools.ietf.org/html/rfc4122#section-3 RFC 4122, § 3: Namespace Registration Template - */ - public function getUrn(): string; - /** * Returns the string standard representation of the UUID * diff --git a/vendor/ramsey/uuid/src/functions.php b/vendor/ramsey/uuid/src/functions.php index 1b3ce00f7..f5df1488d 100644 --- a/vendor/ramsey/uuid/src/functions.php +++ b/vendor/ramsey/uuid/src/functions.php @@ -15,18 +15,17 @@ namespace Ramsey\Uuid; -use DateTimeInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; /** - * Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, + * Returns a version 1 (time-based) UUID from a host ID, sequence number, * and the current time * * @param Hexadecimal|int|string|null $node A 48-bit number representing the * hardware address; this number may be represented as an integer or a * hexadecimal string - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * @param int $clockSeq A 14-bit number used to help avoid duplicates that * could arise when the clock is set backwards in time or if the node ID * changes * @@ -107,12 +106,12 @@ function v5($ns, string $name): string } /** - * Returns a version 6 (reordered time) UUID from a host ID, sequence number, + * Returns a version 6 (ordered-time) UUID from a host ID, sequence number, * and the current time * * @param Hexadecimal|null $node A 48-bit number representing the hardware * address - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * @param int $clockSeq A 14-bit number used to help avoid duplicates that * could arise when the clock is set backwards in time or if the node ID * changes * @@ -122,37 +121,3 @@ function v6(?Hexadecimal $node = null, ?int $clockSeq = null): string { return Uuid::uuid6($node, $clockSeq)->toString(); } - -/** - * Returns a version 7 (Unix Epoch time) UUID - * - * @param DateTimeInterface|null $dateTime An optional date/time from which - * to create the version 7 UUID. If not provided, the UUID is generated - * using the current date/time. - * - * @return non-empty-string Version 7 UUID as a string - */ -function v7(?DateTimeInterface $dateTime = null): string -{ - return Uuid::uuid7($dateTime)->toString(); -} - -/** - * Returns a version 8 (custom) UUID - * - * The bytes provided may contain any value according to your application's - * needs. Be aware, however, that other applications may not understand the - * semantics of the value. - * - * @param string $bytes A 16-byte octet string. This is an open blob - * of data that you may fill with 128 bits of information. Be aware, - * however, bits 48 through 51 will be replaced with the UUID version - * field, and bits 64 and 65 will be replaced with the UUID variant. You - * MUST NOT rely on these bits for your application needs. - * - * @return non-empty-string Version 8 UUID as a string - */ -function v8(string $bytes): string -{ - return Uuid::uuid8($bytes)->toString(); -} diff --git a/vendor/symfony/deprecation-contracts/LICENSE b/vendor/symfony/deprecation-contracts/LICENSE index 0ed3a2465..406242ff2 100644 --- a/vendor/symfony/deprecation-contracts/LICENSE +++ b/vendor/symfony/deprecation-contracts/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2020-present Fabien Potencier +Copyright (c) 2020-2022 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/symfony/deprecation-contracts/README.md b/vendor/symfony/deprecation-contracts/README.md index 9814864c0..4957933a6 100644 --- a/vendor/symfony/deprecation-contracts/README.md +++ b/vendor/symfony/deprecation-contracts/README.md @@ -22,5 +22,5 @@ trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use This will generate the following message: `Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.` -While not recommended, the deprecation notices can be completely ignored by declaring an empty +While not necessarily recommended, the deprecation notices can be completely ignored by declaring an empty `function trigger_deprecation() {}` in your application. diff --git a/vendor/symfony/deprecation-contracts/composer.json b/vendor/symfony/deprecation-contracts/composer.json index c6d02d874..cc7cc1237 100644 --- a/vendor/symfony/deprecation-contracts/composer.json +++ b/vendor/symfony/deprecation-contracts/composer.json @@ -15,7 +15,7 @@ } ], "require": { - "php": ">=8.1" + "php": ">=7.1" }, "autoload": { "files": [ @@ -25,7 +25,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-main": "3.4-dev" + "dev-main": "2.5-dev" }, "thanks": { "name": "symfony/contracts", diff --git a/vendor/symfony/deprecation-contracts/function.php b/vendor/symfony/deprecation-contracts/function.php index 2d56512ba..d4371504a 100644 --- a/vendor/symfony/deprecation-contracts/function.php +++ b/vendor/symfony/deprecation-contracts/function.php @@ -20,7 +20,7 @@ * * @author Nicolas Grekas */ - function trigger_deprecation(string $package, string $version, string $message, mixed ...$args): void + function trigger_deprecation(string $package, string $version, string $message, ...$args): void { @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED); }