Upgrade to Laravel 13

- laravel/framework ^12.0 -> ^13.0 (installed 13.19.0)
- laravel/tinker ^2.9 -> ^3.0 (installed 3.0.2, pulls psysh >=0.12.19)
- phpunit/phpunit ^11.0 -> ^12.0 (installed 12.5.31)
- Symfony components move to 8.x (supported by L13); symfony/yaml stays on
  patched 7.4.14 via its direct ^7.0 constraint
- league/commonmark auto-bumped to 2.8.2 (patched)
- No application/config code changes required; the fluent
  validateCsrfTokens(except: ...) config still resolves under L13

composer audit: No security vulnerability advisories found.
Full suite green: 59 tests, 128 assertions (1 skipped).
This commit is contained in:
KodeStar
2026-07-08 19:57:08 +01:00
parent 39191885e5
commit 8a622545ff
1606 changed files with 49071 additions and 24352 deletions
+3 -3
View File
@@ -14,8 +14,8 @@
"enshrined/svg-sanitize": "^0.22.0",
"graham-campbell/github": "^13.0",
"guzzlehttp/guzzle": "^7.8",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.9",
"laravel/framework": "^13.0",
"laravel/tinker": "^3.0",
"laravel/ui": "^4.4",
"league/flysystem-aws-s3-v3": "^3.0",
"nunomaduro/collision": "^8.0",
@@ -27,7 +27,7 @@
"barryvdh/laravel-ide-helper": "^3.0",
"filp/whoops": "^2.8",
"mockery/mockery": "^1.6",
"phpunit/phpunit": "^11.0",
"phpunit/phpunit": "^12.0",
"squizlabs/php_codesniffer": "3.*",
"symfony/thanks": "^1.2",
"fakerphp/faker": "^1.23"
Generated
+570 -671
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -857,7 +857,7 @@ namespace Aws;
*/
class Sdk
{
const VERSION = '3.388.0';
const VERSION = '3.388.1';
/** @var array Arguments for creating clients */
private $args;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+146 -1
View File
@@ -2,6 +2,150 @@
All notable changes to this project will be documented in this file.
## [0.18.0](https://github.com/brick/math/releases/tag/0.18.0) - 2026-06-14
💥 **Breaking changes**
The following breaking change only affects you if you're using named arguments:
- `BigInteger::fromBytes()` now uses `$bytes` as the parameter name
🐛 **Bug fixes**
- `of()` no longer accepts a trailing newline (`\n`) in the input string; such input now throws `NumberFormatException`
- `of()` now consistently throws `NumberFormatException` for exponents too large to process, instead of `IntegerOverflowException` in some cases
- `BigInteger::fromBase()` now reports the invalid character with its original case in the `NumberFormatException` message, instead of lower-casing it
⚡️ **Performance improvements**
- `BigInteger::gcd()` no longer exhausts memory on large inputs when the GMP extension is not installed
- `BigInteger::modInverse()` no longer exhausts memory on large inputs, and is faster when the GMP extension is not installed
👌 **Static analysis improvements**
- Narrowed parameter and return types with static analysis annotations:
- `nthRoot()`'s `$n` is now `positive-int`
- `BigInteger::toBase()`, `toArbitraryBase()`, `toBytes()` and `BigRational::toRepeatingDecimalString()` now return `non-empty-string`
## [0.17.2](https://github.com/brick/math/releases/tag/0.17.2) - 2026-05-25
**New features**
- New methods: `BigInteger::nthRoot()` and `BigDecimal::nthRoot()` compute the nth root of a number (#113 by @Pablo1Gustavo)
## [0.17.1](https://github.com/brick/math/releases/tag/0.17.1) - 2026-04-19
👌 **Improvements**
- More precise `float` approximations in `BigRational::toFloat()`
## [0.17.0](https://github.com/brick/math/releases/tag/0.17.0) - 2026-03-17
💥 **Breaking changes**
- Deprecated method `BigDecimal::hasNonZeroFractionalPart()` has been removed, use `! $number->getFractionalPart()->isZero()` instead
- Exception constructors and factory methods are now `@internal`
**Compatibility improvements**
- `BigDecimal::fromFloatExact()` now supports 32-bit PHP
## [0.16.2](https://github.com/brick/math/releases/tag/0.16.2) - 2026-03-15
**New features**
New methods to create a `BigDecimal` from a `float` value:
- `BigDecimal::fromFloatExact()`
- `BigDecimal::fromFloatShortest()`
## [0.16.1](https://github.com/brick/math/releases/tag/0.16.1) - 2026-03-09
👌 **Improvements**
- Add `@return non-empty-string` to `toString()`, `jsonSerialize()` and `__toString()` (#111 by @vudaltsov)
## [0.16.0](https://github.com/brick/math/releases/tag/0.16.0) - 2026-03-06
💥 **Breaking changes**
- **`BigInteger::getLowestSetBit()` now returns `null` instead of `-1` when the number is zero**
- Deprecated method `BigRational::simplified()` has been removed, as it is now a no-op
**New features**
- New method: `BigDecimal::getIntegralPart()` returns the integral part as `BigInteger` (this method existed with a different signature in version 0.14, and was removed in 0.15)
- New method: `BigDecimal::getFractionalPart()` returns the fractional part as `BigDecimal` (this method existed with a different signature and meaning in version 0.14, and was removed in 0.15)
🗑️ **Deprecations**
- Method `BigDecimal::hasNonZeroFractionalPart()` is deprecated, use `->getFractionalPart()->isZero()` instead
## [0.15.0](https://github.com/brick/math/releases/tag/0.15.0) - 2026-02-20
💥 **Breaking changes**
- **floating-point inputs are no longer accepted by `of()` and arithmetic methods**, use `of((string) $float)` to get the same behaviour as before (#105)
- **`BigRational` is now always simplified to lowest terms:** all operations, including `of()` and `ofFraction()`, now return a fraction in its simplest form (e.g. `2/3` instead of `4/6`)
- **`BigDecimal::dividedBy()` now requires the `$scale` parameter**
- **`BigInteger::sqrt()` and `BigDecimal::sqrt()` now default to `RoundingMode::Unnecessary`**, explicitly pass `RoundingMode::Down` to get the previous behaviour
- **`BigInteger::mod()` now uses Euclidean modulo semantics**: the modulus must be strictly positive, and the result is always non-negative; this change aligns with Java's `BigInteger.mod()` behaviour
- **`BigInteger::mod()`, `modInverse()` and `modPow()` now throw `InvalidArgumentException` (instead of `NegativeNumberException`) for negative modulus/exponent arguments**
- **`MathException` is now an interface** instead of a class
- **`BigDecimal::getPrecision()` now returns `1` for zero values**
- `BigNumber::min()`, `max()` and `sum()` now throw an `ArgumentCountError` when called with no arguments (previously threw `InvalidArgumentException`)
- `BigInteger::randomBits()` and `randomRange()` now throw `RandomSourceException` when random byte generation fails or returns invalid data
Deprecated API elements removed:
- deprecated method `BigInteger::testBit()` has been removed, use `isBitSet()` instead
- deprecated method `BigInteger::gcdMultiple()` has been removed, use `gcdAll()` instead
- deprecated method `BigDecimal::exactlyDividedBy()` has been removed, use `dividedByExact()` instead
- deprecated method `BigDecimal::getIntegralPart()` has been removed (will be re-introduced as returning `BigInteger` in 0.16)
- deprecated method `BigDecimal::getFractionalPart()` has been removed (will be re-introduced as returning `BigDecimal` with a different meaning in 0.16)
- deprecated method `BigDecimal::stripTrailingZeros()` has been removed, use `strippedOfTrailingZeros()` instead
- deprecated method `BigRational::nd()` has been removed, use `ofFraction()` instead
- deprecated method `BigRational::quotient()` has been removed, use `getIntegralPart()` instead
- deprecated method `BigRational::remainder()` has been removed, use `$number->getNumerator()->remainder($number->getDenominator())` instead
- deprecated method `BigRational::quotientAndRemainder()` has been removed, use `$number->getNumerator()->quotientAndRemainder($number->getDenominator())` instead
- deprecated `RoundingMode` upper snake case constants (e.g. `HALF_UP`) have been removed, use the pascal case version (e.g. `HalfUp`) instead
The following breaking changes only affect you if you're using named arguments:
- `BigInteger::mod()` now uses `$modulus` as the parameter name
- `BigInteger::modInverse()` now uses `$modulus` as the parameter name
- `BigInteger::modPow()` now uses `$exponent` and `$modulus` as parameter names
- `BigInteger::shiftedLeft()` now uses `$bits` as the parameter name
- `BigInteger::shiftedRight()` now uses `$bits` as the parameter name
- `BigInteger::isBitSet()` now uses `$bitIndex` as the parameter name
- `BigInteger::randomBits()` now uses `$bitCount` as the parameter name
- `BigDecimal::withPointMovedLeft()` now uses `$places` as the parameter name
- `BigDecimal::withPointMovedRight()` now uses `$places` as the parameter name
The following breaking changes are unlikely to affect you:
- `DivisionByZeroException::modulusMustNotBeZero()` has been renamed to `zeroModulus()`
- `DivisionByZeroException::denominatorMustNotBeZero()` has been renamed to `zeroDenominator()`
- `IntegerOverflowException::toIntOverflow()` has been renamed to `integerOutOfRange()`
- `RoundingNecessaryException::roundingNecessary()` has been removed
🗑️ **Deprecations**
- Method `BigRational::simplified()` is deprecated, as it is now a no-op
**New features**
- `BigInteger::power()`, `BigDecimal::power()` and `BigRational::power()` no longer enforce an exponent limit
- `BigInteger::shiftedLeft()` and `BigInteger::shiftedRight()` no longer enforce a limit on the number of bits
- `BigRational::power()` now accepts negative exponents
- New exception: `InvalidArgumentException` for invalid argument errors
- New exception: `NoInverseException` for modular inverse errors
- New exception: `RandomSourceException` for random source errors
👌 **Improvements**
- Narrowed parameter and return types with static analysis annotations (#108 by @simPod)
## [0.14.8](https://github.com/brick/math/releases/tag/0.14.8) - 2026-02-10
🗑️ **Deprecations**
@@ -58,7 +202,7 @@ All notable changes to this project will be documented in this file.
🗑️ **Deprecations**
- Passing a negative modulus to `BigInteger::mod()` is deprecated to align with Euclidean modulo semantics; it will throw `NegativeNumberException` in 0.15
- Passing a negative modulus to `BigInteger::mod()` is deprecated to align with Euclidean modulo semantics; it will throw `InvalidArgumentException` in 0.15
- Method `BigDecimal::stripTrailingZeros()` is deprecated, use `strippedOfTrailingZeros()` instead
**New features**
@@ -107,6 +251,7 @@ All notable changes to this project will be documented in this file.
👌 **Improvements**
- All exceptions thrown by the library now implement a common `MathException` interface
- `BigInteger::modInverse()` now accepts `BigNumber|int|float|string` instead of just `BigInteger`
- `BigInteger::gcdMultiple()` now accepts `BigNumber|int|float|string` instead of just `BigInteger`
+265
View File
@@ -0,0 +1,265 @@
## Brick\Math
<img src="https://raw.githubusercontent.com/brick/brick/master/logo.png" alt="" align="left" height="64">
A PHP library to work with arbitrary precision numbers.
[![Build Status](https://github.com/brick/math/workflows/CI/badge.svg)](https://github.com/brick/math/actions)
[![Coverage Status](https://codecov.io/github/brick/math/graph/badge.svg)](https://codecov.io/github/brick/math)
[![Latest Stable Version](https://poser.pugx.org/brick/math/v/stable)](https://packagist.org/packages/brick/math)
[![Total Downloads](https://poser.pugx.org/brick/math/downloads)](https://packagist.org/packages/brick/math)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT)
### Installation
This library is installable via [Composer](https://getcomposer.org/):
```bash
composer require brick/math
```
### Requirements
This library requires PHP 8.2 or later.
For PHP 8.1 compatibility, you can use version `0.13`. For PHP 8.0, you can use version `0.11`. For PHP 7.4, you can use version `0.10`. For PHP 7.1, 7.2 & 7.3, you can use version `0.9`. Note that [PHP versions < 8.1 are EOL](http://php.net/supported-versions.php) and not supported anymore. If you're still using one of these PHP versions, you should consider upgrading as soon as possible.
Although the library can work seamlessly on any PHP installation, it is highly recommended that you install the
[GMP](http://php.net/manual/en/book.gmp.php) or [BCMath](http://php.net/manual/en/book.bc.php) extension
to speed up calculations. The fastest available calculator implementation will be automatically selected at runtime.
### Project status & release process
While this library is still under development, it is well tested and considered stable enough to use in production
environments.
The current releases are numbered `0.x.y`. When a non-breaking change is introduced (adding new methods, optimizing
existing code, etc.), `y` is incremented.
**When a breaking change is introduced, a new `0.x` version cycle is always started.**
It is therefore safe to lock your project to a given release cycle, such as `^0.17`.
If you need to upgrade to a newer release cycle, check the [release history](https://github.com/brick/math/releases)
for a list of changes introduced by each further `0.x.0` version.
### Package contents
This library provides the following public classes in the `Brick\Math` namespace:
- [BigNumber](https://github.com/brick/math/blob/0.17.2/src/BigNumber.php): base class for `BigInteger`, `BigDecimal` and `BigRational`
- [BigInteger](https://github.com/brick/math/blob/0.17.2/src/BigInteger.php): represents an arbitrary-precision integer number.
- [BigDecimal](https://github.com/brick/math/blob/0.17.2/src/BigDecimal.php): represents an arbitrary-precision decimal number.
- [BigRational](https://github.com/brick/math/blob/0.17.2/src/BigRational.php): represents an arbitrary-precision rational number (fraction), always reduced to lowest terms.
- [RoundingMode](https://github.com/brick/math/blob/0.17.2/src/RoundingMode.php): enum representing all available rounding modes.
And [exceptions](#exceptions) in the `Brick\Math\Exception` namespace.
### Overview
#### Instantiation
The constructors of the classes are not public, you must use a factory method to obtain an instance.
All classes provide an `of()` factory method that accepts any of the following types:
- `BigNumber` instances
- `int` numbers
- `string` representations of integer, decimal and rational numbers
Example:
```php
BigInteger::of(123546);
BigInteger::of('9999999999999999999999999999999999999999999');
BigDecimal::of('9.99999999999999999999999999999999999999999999');
BigRational::of('2/3');
```
Note that all `of()` methods accept all the representations above, *as long as it can be safely converted to
the current type*:
```php
BigInteger::of('1.00'); // 1
BigInteger::of('1.01'); // RoundingNecessaryException
BigDecimal::of('1/8'); // 0.125
BigDecimal::of('1/3'); // RoundingNecessaryException
BigRational::of('1.1'); // 11/10
BigRational::of('1.15'); // 23/20 (reduced to lowest terms)
```
> [!NOTE]
> The `of()` factory method does not accept `float` values, because casting a float to string can be lossy.
> To convert a float to a `BigDecimal`, use one of the dedicated methods:
>
> ```php
> // Exact IEEE-754 representation — the value the float actually holds:
> BigDecimal::fromFloatExact(0.1); // 0.1000000000000000055511151231257827021181583404541015625
>
> // Shortest decimal that round-trips back to the same float:
> BigDecimal::fromFloatShortest(0.1); // 0.1
> ```
#### Immutability & chaining
The `BigInteger`, `BigDecimal` and `BigRational` classes are immutable: their value never changes,
so that they can be safely passed around. All methods that return a `BigInteger`, `BigDecimal` or `BigRational`
return a new object, leaving the original object unaffected:
```php
$ten = BigInteger::of(10);
echo $ten->plus(5); // 15
echo $ten->multipliedBy(3); // 30
```
The methods can be chained for better readability:
```php
echo BigInteger::of(10)->plus(5)->multipliedBy(3); // 45
```
#### Parameter types
All methods that accept a number: `plus()`, `minus()`, `multipliedBy()`, etc. accept the same types as `of()`.
For example, given the following number:
```php
$integer = BigInteger::of(123);
```
The following lines are equivalent:
```php
$integer->multipliedBy(123);
$integer->multipliedBy('123');
$integer->multipliedBy($integer);
```
Just like `of()`, other types of `BigNumber` are acceptable, as long as they can be safely converted to the current type:
```php
echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.0')); // 4
echo BigInteger::of(2)->multipliedBy(BigDecimal::of('2.5')); // RoundingNecessaryException
echo BigDecimal::of(2.5)->multipliedBy(BigInteger::of(2)); // 5.0
```
#### Division & rounding
##### BigInteger
By default, dividing a `BigInteger` returns the exact result of the division, or throws an exception if the remainder
of the division is not zero:
```php
echo BigInteger::of(999)->dividedBy(3); // 333
echo BigInteger::of(1000)->dividedBy(3); // RoundingNecessaryException
```
You can pass an optional [rounding mode](https://github.com/brick/math/blob/0.17.2/src/RoundingMode.php) to round the result, if necessary:
```php
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Down); // 333
echo BigInteger::of(1000)->dividedBy(3, RoundingMode::Up); // 334
```
If you're into quotients and remainders, there are methods for this, too:
```php
echo BigInteger::of(1000)->quotient(3); // 333
echo BigInteger::of(1000)->remainder(3); // 1
```
You can even get both at the same time:
```php
[$quotient, $remainder] = BigInteger::of(1000)->quotientAndRemainder(3);
```
##### BigDecimal
Dividing a `BigDecimal` always requires a scale to be specified. If the exact result of the division does not fit in
the given scale, a [rounding mode](https://github.com/brick/math/blob/0.17.2/src/RoundingMode.php) must be provided.
```php
echo BigDecimal::of(1)->dividedBy('8', 3); // 0.125
echo BigDecimal::of(1)->dividedBy('8', 2); // RoundingNecessaryException
echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HalfDown); // 0.12
echo BigDecimal::of(1)->dividedBy('8', 2, RoundingMode::HalfUp); // 0.13
```
If you know that the division yields a finite number of decimals places, you can use `dividedByExact()`, which will
automatically compute the required scale to fit the result, or throw an exception if the division yields an infinite
repeating decimal:
```php
echo BigDecimal::of(1)->dividedByExact(256); // 0.00390625
echo BigDecimal::of(1)->dividedByExact(11); // RoundingNecessaryException
```
##### BigRational
The result of the division of a `BigRational` can always be represented exactly:
```php
echo BigRational::of('13/99')->dividedBy('7'); // 13/693
echo BigRational::of('13/99')->dividedBy('9/8'); // 104/891
```
#### Bitwise operations
`BigInteger` supports bitwise operations:
- `and()`
- `or()`
- `xor()`
- `not()`
and bit shifting:
- `shiftedLeft()`
- `shiftedRight()`
#### Exceptions
All exceptions thrown by this library implement the `MathException` interface.
This means that you can safely catch all exceptions thrown by this library using a single catch clause:
```php
use Brick\Math\BigDecimal;
use Brick\Math\Exception\MathException;
try {
$number = BigInteger::of(1)->dividedBy(3);
} catch (MathException $e) {
// ...
}
```
If you need more granular control over the exceptions thrown, you can catch the specific exception classes:
- `DivisionByZeroException`
- `IntegerOverflowException`
- `InvalidArgumentException`
- `NegativeNumberException`
- `NoInverseException`
- `NumberFormatException`
- `RandomSourceException`
- `RoundingNecessaryException`
- `UnsupportedPlatformException`
#### Serialization
`BigInteger`, `BigDecimal` and `BigRational` can be safely serialized on a machine and unserialized on another,
even if these machines do not share the same set of PHP extensions.
For example, serializing on a machine with GMP support and unserializing on a machine that does not have this extension
installed will still work as expected.
#### PHPStan extension
A third-party [PHPStan extension](https://github.com/simPod/phpstan-brick-math) is available for this library. It provides more specific throw type narrowing for brick/math methods, so that PHPStan can infer the exact exception classes thrown. Note that this extension is not maintained by the author of brick/math.
+14
View File
@@ -0,0 +1,14 @@
codecov:
require_ci_to_pass: true
notify:
after_n_builds: 6
wait_for_ci: true
coverage:
status:
project:
default:
informational: true
patch:
default:
informational: true
-1
View File
@@ -23,7 +23,6 @@
},
"require-dev": {
"phpunit/phpunit": "^11.5",
"php-coveralls/php-coveralls": "^2.2",
"phpstan/phpstan": "2.1.22"
},
"autoload": {
+479 -247
View File
File diff suppressed because it is too large Load Diff
+378 -253
View File
File diff suppressed because it is too large Load Diff
+128 -133
View File
@@ -5,20 +5,19 @@ declare(strict_types=1);
namespace Brick\Math;
use Brick\Math\Exception\DivisionByZeroException;
use Brick\Math\Exception\IntegerOverflowException;
use Brick\Math\Exception\InvalidArgumentException;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\NumberFormatException;
use Brick\Math\Exception\RoundingNecessaryException;
use InvalidArgumentException;
use Brick\Math\Internal\Safe;
use JsonSerializable;
use Override;
use Stringable;
use function array_shift;
use function assert;
use function filter_var;
use function is_float;
use function is_int;
use function is_nan;
use function is_null;
use function ltrim;
use function preg_match;
@@ -26,9 +25,7 @@ use function str_contains;
use function str_repeat;
use function strlen;
use function substr;
use function trigger_error;
use const E_USER_DEPRECATED;
use const FILTER_VALIDATE_INT;
use const PREG_UNMATCHED_AS_NULL;
@@ -44,6 +41,8 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
{
/**
* The regular expression used to parse integer or decimal numbers.
*
* The end anchor must be \z, not $: the latter would also match before a trailing newline.
*/
private const PARSE_REGEXP_NUMERICAL =
'/^' .
@@ -52,10 +51,12 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
'(?<point>\.)?' .
'(?<fractional>[0-9]+)?' .
'(?:[eE](?<exponent>[\-\+]?[0-9]+))?' .
'$/';
'\z/';
/**
* The regular expression used to parse rational numbers.
*
* The end anchor must be \z, not $: the latter would also match before a trailing newline.
*/
private const PARSE_REGEXP_RATIONAL =
'/^' .
@@ -63,7 +64,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
'(?<numerator>[0-9]+)' .
'\/' .
'(?<denominator>[0-9]+)' .
'$/';
'\z/';
/**
* Creates a BigNumber of the given value.
@@ -73,7 +74,6 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* - BigNumber instances are returned as is
* - integer numbers are returned as BigInteger
* - floating point numbers are converted to a string then parsed as such (deprecated, will be removed in 0.15)
* - strings containing a `/` character are returned as BigRational
* - 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
@@ -87,7 +87,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public static function of(BigNumber|int|float|string $value): static
final public static function of(BigNumber|int|string $value): static
{
$value = self::_of($value);
@@ -113,7 +113,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public static function ofNullable(BigNumber|int|float|string|null $value): ?static
final public static function ofNullable(BigNumber|int|string|null $value): ?static
{
if (is_null($value)) {
return null;
@@ -128,31 +128,28 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
* If several values are equal and minimal, the first one is returned.
* This can affect the concrete return type when calling this method on BigNumber.
*
* @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers must be convertible to an
* instance of the class this method is called on.
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws InvalidArgumentException If no values are given.
* @throws MathException If a number is not valid, or is not convertible to an instance of the class
* this method is called on.
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function min(BigNumber|int|float|string ...$values): static
final public static function min(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$min = null;
$min = static::of($a);
foreach ($values as $value) {
foreach ($n as $value) {
$value = static::of($value);
if ($min === null || $value->isLessThan($min)) {
if ($value->isLessThan($min)) {
$min = $value;
}
}
if ($min === null) {
throw new InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $min;
}
@@ -162,31 +159,28 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
* If several values are equal and maximal, the first one is returned.
* This can affect the concrete return type when calling this method on BigNumber.
*
* @param BigNumber|int|float|string ...$values The numbers to compare. All the numbers must be convertible to an
* instance of the class this method is called on.
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws InvalidArgumentException If no values are given.
* @throws MathException If a number is not valid, or is not convertible to an instance of the class
* this method is called on.
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function max(BigNumber|int|float|string ...$values): static
final public static function max(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$max = null;
$max = static::of($a);
foreach ($values as $value) {
foreach ($n as $value) {
$value = static::of($value);
if ($max === null || $value->isGreaterThan($max)) {
if ($value->isGreaterThan($max)) {
$max = $value;
}
}
if ($max === null) {
throw new InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
return $max;
}
@@ -199,26 +193,21 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
* When called on BigInteger, BigDecimal, or BigRational, sum() requires that all values can be converted to that
* specific subclass, and returns a result of the same type.
*
* @param BigNumber|int|float|string ...$values The numbers to add. All the numbers must be convertible to an
* instance of the class this method is called on.
* @param BigNumber|int|string $a The first number. Must be convertible to an instance of the class this method
* is called on.
* @param BigNumber|int|string ...$n The additional numbers. Each number must be convertible to an instance of the
* class this method is called on.
*
* @throws InvalidArgumentException If no values are given.
* @throws MathException If a number is not valid, or is not convertible to an instance of the class
* this method is called on.
* @throws MathException If a number is not valid, or is not convertible to an instance of the class this method is
* called on.
*
* @pure
*/
final public static function sum(BigNumber|int|float|string ...$values): static
final public static function sum(BigNumber|int|string $a, BigNumber|int|string ...$n): static
{
$first = array_shift($values);
$sum = static::of($a);
if ($first === null) {
throw new InvalidArgumentException(__METHOD__ . '() expects at least one value.');
}
$sum = static::of($first);
foreach ($values as $value) {
foreach ($n as $value) {
$sum = self::add($sum, static::of($value));
}
@@ -234,7 +223,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public function isEqualTo(BigNumber|int|float|string $that): bool
final public function isEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) === 0;
}
@@ -246,7 +235,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public function isLessThan(BigNumber|int|float|string $that): bool
final public function isLessThan(BigNumber|int|string $that): bool
{
return $this->compareTo($that) < 0;
}
@@ -258,7 +247,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public function isLessThanOrEqualTo(BigNumber|int|float|string $that): bool
final public function isLessThanOrEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) <= 0;
}
@@ -270,7 +259,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public function isGreaterThan(BigNumber|int|float|string $that): bool
final public function isGreaterThan(BigNumber|int|string $that): bool
{
return $this->compareTo($that) > 0;
}
@@ -282,7 +271,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final public function isGreaterThanOrEqualTo(BigNumber|int|float|string $that): bool
final public function isGreaterThanOrEqualTo(BigNumber|int|string $that): bool
{
return $this->compareTo($that) >= 0;
}
@@ -376,7 +365,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
abstract public function compareTo(BigNumber|int|float|string $that): int;
abstract public function compareTo(BigNumber|int|string $that): int;
/**
* Limits (clamps) this number between the given minimum and maximum values.
@@ -385,21 +374,21 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
* If the number is greater than $max, returns $max.
* Otherwise, returns this number unchanged.
*
* @param BigNumber|int|float|string $min The minimum. Must be convertible to an instance of the class this method is called on.
* @param BigNumber|int|float|string $max The maximum. Must be convertible to an instance of the class this method is called on.
* @param BigNumber|int|string $min The minimum. Must be convertible to an instance of the class this method is called on.
* @param BigNumber|int|string $max The maximum. Must be convertible to an instance of the class this method is called on.
*
* @throws MathException If min/max are not convertible to an instance of the class this method is called on.
* @throws InvalidArgumentException If min is greater than max.
*
* @pure
*/
final public function clamp(BigNumber|int|float|string $min, BigNumber|int|float|string $max): static
final public function clamp(BigNumber|int|string $min, BigNumber|int|string $max): static
{
$min = static::of($min);
$max = static::of($max);
if ($min->isGreaterThan($max)) {
throw new InvalidArgumentException('Minimum value must be less than or equal to maximum value.');
throw InvalidArgumentException::minGreaterThanMax();
}
if ($this->isLessThan($min)) {
@@ -441,8 +430,8 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
/**
* Converts this number to a BigDecimal with the given scale, using rounding if necessary.
*
* @param int $scale The scale of the resulting `BigDecimal`. Must be non-negative.
* @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
* @param non-negative-int $scale The scale of the resulting `BigDecimal`. Must be non-negative.
* @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
*
* @throws InvalidArgumentException If the scale is negative.
* @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and this number cannot be converted to
@@ -458,7 +447,8 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
* 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.
*
* @throws MathException If this number cannot be exactly converted to a native integer.
* @throws RoundingNecessaryException If this number cannot be converted to an integer without rounding.
* @throws IntegerOverflowException If this number is too large to fit in a native integer.
*
* @pure
*/
@@ -484,10 +474,15 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
* The output of this method can be parsed by the `of()` factory method; this will yield an object equal to this
* one, but possibly of a different type if instantiated through `BigNumber::of()`.
*
* @return non-empty-string
*
* @pure
*/
abstract public function toString(): string;
/**
* @return non-empty-string
*/
#[Override]
final public function jsonSerialize(): string
{
@@ -495,8 +490,11 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
}
/**
* @return non-empty-string
*
* @pure
*/
#[Override]
final public function __toString(): string
{
return $this->toString();
@@ -528,6 +526,8 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @internal
*
* @param non-negative-int $scale
*
* @pure
*/
final protected function newBigDecimal(string $value, int $scale = 0): BigDecimal
@@ -542,9 +542,9 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
final protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator): BigRational
final protected function newBigRational(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator, bool $simplify): BigRational
{
return new BigRational($numerator, $denominator, $checkDenominator);
return new BigRational($numerator, $denominator, $checkDenominator, $simplify);
}
/**
@@ -553,7 +553,7 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
*
* @pure
*/
private static function _of(BigNumber|int|float|string $value): BigNumber
private static function _of(BigNumber|int|string $value): BigNumber
{
if ($value instanceof BigNumber) {
return $value;
@@ -563,19 +563,8 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
return new BigInteger((string) $value);
}
if (is_float($value)) {
// @phpstan-ignore-next-line
trigger_error(
'Passing floats to BigNumber::of() and arithmetic methods is deprecated and will be removed in 0.15. ' .
'Cast the float to string explicitly to preserve the previous behaviour.',
E_USER_DEPRECATED,
);
if (is_nan($value)) {
$value = 'NAN';
} else {
$value = (string) $value;
}
if ($value === '') {
throw NumberFormatException::emptyNumber();
}
if (str_contains($value, '/')) {
@@ -592,84 +581,90 @@ abstract readonly class BigNumber implements JsonSerializable, Stringable
$denominator = self::cleanUp(null, $denominator);
if ($denominator === '0') {
throw DivisionByZeroException::denominatorMustNotBeZero();
throw DivisionByZeroException::zeroDenominator();
}
return new BigRational(
new BigInteger($numerator),
new BigInteger($denominator),
false,
true,
);
} else {
// Integer or decimal number
if (preg_match(self::PARSE_REGEXP_NUMERICAL, $value, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
throw NumberFormatException::invalidFormat($value);
}
}
$sign = $matches['sign'];
$point = $matches['point'];
$integral = $matches['integral'];
$fractional = $matches['fractional'];
$exponent = $matches['exponent'];
// Integer or decimal number
if (preg_match(self::PARSE_REGEXP_NUMERICAL, $value, $matches, PREG_UNMATCHED_AS_NULL) !== 1) {
throw NumberFormatException::invalidFormat($value);
}
if ($integral === null && $fractional === null) {
throw NumberFormatException::invalidFormat($value);
}
$sign = $matches['sign'];
$point = $matches['point'];
$integral = $matches['integral'];
$fractional = $matches['fractional'];
$exponent = $matches['exponent'];
if ($integral === null) {
$integral = '0';
}
if ($integral === null && $fractional === null) {
throw NumberFormatException::invalidFormat($value);
}
if ($point !== null || $exponent !== null) {
$fractional ??= '';
if ($integral === null) {
$integral = '0';
}
if ($exponent !== null) {
if ($exponent[0] === '-') {
$exponent = ltrim(substr($exponent, 1), '0') ?: '0';
$exponent = filter_var($exponent, FILTER_VALIDATE_INT);
if ($exponent !== false) {
$exponent = -$exponent;
}
} else {
if ($exponent[0] === '+') {
$exponent = substr($exponent, 1);
}
$exponent = ltrim($exponent, '0') ?: '0';
$exponent = filter_var($exponent, FILTER_VALIDATE_INT);
if ($point !== null || $exponent !== null) {
$fractional ??= '';
if ($exponent !== null) {
if ($exponent[0] === '-') {
$exponent = ltrim(substr($exponent, 1), '0') ?: '0';
$exponent = filter_var($exponent, FILTER_VALIDATE_INT);
if ($exponent !== false) {
$exponent = -$exponent;
}
} else {
$exponent = 0;
}
if ($exponent === false) {
throw new NumberFormatException('Exponent too large.');
}
$unscaledValue = self::cleanUp($sign, $integral . $fractional);
$scale = strlen($fractional) - $exponent;
if ($scale < 0) {
if ($unscaledValue !== '0') {
$unscaledValue .= str_repeat('0', -$scale);
if ($exponent[0] === '+') {
$exponent = substr($exponent, 1);
}
$scale = 0;
$exponent = ltrim($exponent, '0') ?: '0';
$exponent = filter_var($exponent, FILTER_VALIDATE_INT);
}
return new BigDecimal($unscaledValue, $scale);
} else {
$exponent = 0;
}
$integral = self::cleanUp($sign, $integral);
if ($exponent === false) {
throw NumberFormatException::exponentTooLarge();
}
return new BigInteger($integral);
$unscaledValue = self::cleanUp($sign, $integral . $fractional);
$scale = strlen($fractional) - $exponent;
// @phpstan-ignore function.alreadyNarrowedType
if (! is_int($scale)) {
throw NumberFormatException::exponentTooLarge();
}
if ($scale < 0) {
if ($unscaledValue !== '0') {
$unscaledValue .= str_repeat('0', Safe::neg($scale));
}
$scale = 0;
}
return new BigDecimal($unscaledValue, $scale);
}
$integral = self::cleanUp($sign, $integral);
return new BigInteger($integral);
}
/**
* Removes optional leading zeros and applies sign.
*
* @param string|null $sign The sign, '+' or '-', optional. Null is allowed for convenience and treated as '+'.
* @param string $number The number, validated as a string of digits.
* @param '+'|'-'|null $sign The sign, optional. Null is allowed for convenience and treated as '+'.
* @param non-empty-string $number The number, validated as a string of digits.
*
* @pure
*/
+130 -142
View File
@@ -5,21 +5,18 @@ declare(strict_types=1);
namespace Brick\Math;
use Brick\Math\Exception\DivisionByZeroException;
use Brick\Math\Exception\InvalidArgumentException;
use Brick\Math\Exception\MathException;
use Brick\Math\Exception\NumberFormatException;
use Brick\Math\Exception\RoundingNecessaryException;
use InvalidArgumentException;
use Brick\Math\Internal\DecimalHelper;
use Brick\Math\Internal\Safe;
use LogicException;
use Override;
use function is_finite;
use function max;
use function min;
use function strlen;
use function substr;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* An arbitrarily large rational number.
@@ -47,16 +44,17 @@ final readonly class BigRational extends BigNumber
* @param BigInteger $numerator The numerator.
* @param BigInteger $denominator The denominator.
* @param bool $checkDenominator Whether to check the denominator for negative and zero.
* @param bool $simplify Whether to simplify the fraction to lowest terms.
*
* @throws DivisionByZeroException If the denominator is zero.
*
* @pure
*/
protected function __construct(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator)
protected function __construct(BigInteger $numerator, BigInteger $denominator, bool $checkDenominator, bool $simplify)
{
if ($checkDenominator) {
if ($denominator->isZero()) {
throw DivisionByZeroException::denominatorMustNotBeZero();
throw DivisionByZeroException::zeroDenominator();
}
if ($denominator->isNegative()) {
@@ -65,6 +63,13 @@ final readonly class BigRational extends BigNumber
}
}
if ($simplify) {
$gcd = $numerator->gcd($denominator);
$numerator = $numerator->quotient($gcd);
$denominator = $denominator->quotient($gcd);
}
$this->numerator = $numerator;
$this->denominator = $denominator;
}
@@ -75,35 +80,8 @@ final readonly class BigRational extends BigNumber
* If the denominator is negative, the signs of both the numerator and the denominator
* will be inverted to ensure that the denominator is always positive.
*
* @deprecated Use ofFraction() instead.
*
* @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.
*
* @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.
*/
public static function nd(
BigNumber|int|float|string $numerator,
BigNumber|int|float|string $denominator,
): BigRational {
trigger_error(
'The BigRational::nd() method is deprecated, use BigRational::ofFraction() instead.',
E_USER_DEPRECATED,
);
return self::ofFraction($numerator, $denominator);
}
/**
* Creates a BigRational out of a numerator and a denominator.
*
* If the denominator is negative, the signs of both the numerator and the denominator
* will be inverted to ensure that the denominator is always positive.
*
* @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.
* @param BigNumber|int|string $numerator The numerator. Must be convertible to a BigInteger.
* @param BigNumber|int|string $denominator The denominator. Must be convertible to a BigInteger.
*
* @throws MathException If an argument is not valid, or is not convertible to a BigInteger.
* @throws DivisionByZeroException If the denominator is zero.
@@ -111,13 +89,13 @@ final readonly class BigRational extends BigNumber
* @pure
*/
public static function ofFraction(
BigNumber|int|float|string $numerator,
BigNumber|int|float|string $denominator,
BigNumber|int|string $numerator,
BigNumber|int|string $denominator,
): BigRational {
$numerator = BigInteger::of($numerator);
$denominator = BigInteger::of($denominator);
return new BigRational($numerator, $denominator, true);
return new BigRational($numerator, $denominator, true, true);
}
/**
@@ -131,7 +109,7 @@ final readonly class BigRational extends BigNumber
static $zero;
if ($zero === null) {
$zero = new BigRational(BigInteger::zero(), BigInteger::one(), false);
$zero = new BigRational(BigInteger::zero(), BigInteger::one(), false, false);
}
return $zero;
@@ -148,7 +126,7 @@ final readonly class BigRational extends BigNumber
static $one;
if ($one === null) {
$one = new BigRational(BigInteger::one(), BigInteger::one(), false);
$one = new BigRational(BigInteger::one(), BigInteger::one(), false, false);
}
return $one;
@@ -165,13 +143,15 @@ final readonly class BigRational extends BigNumber
static $ten;
if ($ten === null) {
$ten = new BigRational(BigInteger::ten(), BigInteger::one(), false);
$ten = new BigRational(BigInteger::ten(), BigInteger::one(), false, false);
}
return $ten;
}
/**
* Returns the numerator of this rational number.
*
* @pure
*/
public function getNumerator(): BigInteger
@@ -180,6 +160,10 @@ final readonly class BigRational extends BigNumber
}
/**
* Returns the denominator of this rational number.
*
* The denominator is always strictly positive.
*
* @pure
*/
public function getDenominator(): BigInteger
@@ -187,53 +171,6 @@ final readonly class BigRational extends BigNumber
return $this->denominator;
}
/**
* Returns the quotient of the division of the numerator by the denominator.
*
* @deprecated Will be removed in 0.15. Use getIntegralPart() instead.
*/
public function quotient(): BigInteger
{
trigger_error(
'BigRational::quotient() is deprecated and will be removed in 0.15. Use getIntegralPart() instead.',
E_USER_DEPRECATED,
);
return $this->numerator->quotient($this->denominator);
}
/**
* Returns the remainder of the division of the numerator by the denominator.
*
* @deprecated Will be removed in 0.15. Use `$number->getNumerator()->remainder($number->getDenominator())` instead.
*/
public function remainder(): BigInteger
{
trigger_error(
'BigRational::remainder() is deprecated and will be removed in 0.15. Use `$number->getNumerator()->remainder($number->getDenominator())` instead.',
E_USER_DEPRECATED,
);
return $this->numerator->remainder($this->denominator);
}
/**
* Returns the quotient and remainder of the division of the numerator by the denominator.
*
* @deprecated Will be removed in 0.15. Use `$number->getNumerator()->quotientAndRemainder($number->getDenominator())` instead.
*
* @return array{BigInteger, BigInteger}
*/
public function quotientAndRemainder(): array
{
trigger_error(
'BigRational::quotientAndRemainder() is deprecated and will be removed in 0.15. Use `$number->getNumerator()->quotientAndRemainder($number->getDenominator())` instead.',
E_USER_DEPRECATED,
);
return $this->numerator->quotientAndRemainder($this->denominator);
}
/**
* Returns the integral part of this rational number.
*
@@ -242,7 +179,8 @@ final readonly class BigRational extends BigNumber
* - `7/3` returns `2` (since 7/3 = 2 + 1/3)
* - `-7/3` returns `-2` (since -7/3 = -2 + (-1/3))
*
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`.
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`. Note that in
* this identity, the operand order is significant: the reversed form throws when the fractional part is non-zero.
*
* @pure
*/
@@ -259,85 +197,106 @@ final readonly class BigRational extends BigNumber
* - `7/3` returns `1/3` (since 7/3 = 2 + 1/3)
* - `-7/3` returns `-1/3` (since -7/3 = -2 + (-1/3))
*
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`.
* The following identity holds: `$r->isEqualTo($r->getFractionalPart()->plus($r->getIntegralPart()))`. Note that in
* this identity, the operand order is significant: the reversed form throws when the fractional part is non-zero.
*
* @pure
*/
public function getFractionalPart(): BigRational
{
return new BigRational($this->numerator->remainder($this->denominator), $this->denominator, false);
return new BigRational($this->numerator->remainder($this->denominator), $this->denominator, false, false);
}
/**
* Returns the sum of this number and the given one.
*
* @param BigNumber|int|float|string $that The number to add.
* @param BigNumber|int|string $that The number to add.
*
* @throws MathException If the number is not valid.
*
* @pure
*/
public function plus(BigNumber|int|float|string $that): BigRational
public function plus(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
return $this;
}
if ($this->isZero()) {
return $that;
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->plus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the difference of this number and the given one.
*
* @param BigNumber|int|float|string $that The number to subtract.
* @param BigNumber|int|string $that The number to subtract.
*
* @throws MathException If the number is not valid.
*
* @pure
*/
public function minus(BigNumber|int|float|string $that): BigRational
public function minus(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero()) {
return $this;
}
if ($this->isZero()) {
return $that->negated();
}
$numerator = $this->numerator->multipliedBy($that->denominator);
$numerator = $numerator->minus($that->numerator->multipliedBy($this->denominator));
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the product of this number and the given one.
*
* @param BigNumber|int|float|string $that The multiplier.
* @param BigNumber|int|string $that The multiplier.
*
* @throws MathException If the multiplier is not valid.
*
* @pure
*/
public function multipliedBy(BigNumber|int|float|string $that): BigRational
public function multipliedBy(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
if ($that->isZero() || $this->isZero()) {
return BigRational::zero();
}
$numerator = $this->numerator->multipliedBy($that->numerator);
$denominator = $this->denominator->multipliedBy($that->denominator);
return new BigRational($numerator, $denominator, false);
return new BigRational($numerator, $denominator, false, true);
}
/**
* Returns the result of the division of this number by the given one.
*
* @param BigNumber|int|float|string $that The divisor.
* @param BigNumber|int|string $that The divisor.
*
* @throws MathException If the divisor is not valid.
* @throws DivisionByZeroException If the divisor is zero.
*
* @pure
*/
public function dividedBy(BigNumber|int|float|string $that): BigRational
public function dividedBy(BigNumber|int|string $that): BigRational
{
$that = BigRational::of($that);
@@ -348,13 +307,16 @@ final readonly class BigRational extends BigNumber
$numerator = $this->numerator->multipliedBy($that->denominator);
$denominator = $this->denominator->multipliedBy($that->numerator);
return new BigRational($numerator, $denominator, true);
return new BigRational($numerator, $denominator, true, true);
}
/**
* Returns this number exponentiated to the given value.
*
* @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
* Unlike BigInteger and BigDecimal, BigRational supports negative exponents:
* the result is the reciprocal raised to the absolute value of the exponent.
*
* @throws DivisionByZeroException If the exponent is negative and this number is zero.
*
* @pure
*/
@@ -368,10 +330,19 @@ final readonly class BigRational extends BigNumber
return $this;
}
if ($exponent < 0) {
if ($this->isZero()) {
throw DivisionByZeroException::zeroToNegativePower();
}
return $this->reciprocal()->power(Safe::neg($exponent));
}
return new BigRational(
$this->numerator->power($exponent),
$this->denominator->power($exponent),
false,
false,
);
}
@@ -380,38 +351,27 @@ final readonly class BigRational extends BigNumber
*
* The reciprocal has the numerator and denominator swapped.
*
* @throws DivisionByZeroException If the numerator is zero.
* @throws DivisionByZeroException If this number is zero.
*
* @pure
*/
public function reciprocal(): BigRational
{
return new BigRational($this->denominator, $this->numerator, true);
if ($this->isZero()) {
throw DivisionByZeroException::reciprocalOfZero();
}
return new BigRational($this->denominator, $this->numerator, true, false);
}
#[Override]
public function negated(): static
{
return new BigRational($this->numerator->negated(), $this->denominator, false);
}
/**
* Returns the simplified value of this BigRational.
*
* @pure
*/
public function simplified(): BigRational
{
$gcd = $this->numerator->gcd($this->denominator);
$numerator = $this->numerator->quotient($gcd);
$denominator = $this->denominator->quotient($gcd);
return new BigRational($numerator, $denominator, false);
return new BigRational($this->numerator->negated(), $this->denominator, false, false);
}
#[Override]
public function compareTo(BigNumber|int|float|string $that): int
public function compareTo(BigNumber|int|string $that): int
{
$that = BigRational::of($that);
@@ -433,19 +393,23 @@ final readonly class BigRational extends BigNumber
#[Override]
public function toBigInteger(): BigInteger
{
$simplified = $this->simplified();
if (! $simplified->denominator->isEqualTo(1)) {
throw new RoundingNecessaryException('This rational number cannot be represented as an integer value without rounding.');
if ($this->denominator->isEqualTo(1)) {
return $this->numerator;
}
return $simplified->numerator;
throw RoundingNecessaryException::rationalNotConvertibleToInteger();
}
#[Override]
public function toBigDecimal(): BigDecimal
{
return $this->numerator->toBigDecimal()->dividedByExact($this->denominator);
$scale = DecimalHelper::computeScaleFromReducedFractionDenominator($this->denominator->toString());
if ($scale === null) {
throw RoundingNecessaryException::rationalNotConvertibleToDecimal();
}
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale)->strippedOfTrailingZeros();
}
#[Override]
@@ -457,6 +421,22 @@ final readonly class BigRational extends BigNumber
#[Override]
public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
{
if ($scale < 0) { // @phpstan-ignore smaller.alwaysFalse
throw InvalidArgumentException::negativeScale();
}
if ($roundingMode === RoundingMode::Unnecessary) {
$requiredScale = DecimalHelper::computeScaleFromReducedFractionDenominator($this->denominator->toString());
if ($requiredScale === null) {
throw RoundingNecessaryException::rationalNotConvertibleToDecimal();
}
if ($requiredScale > $scale) {
throw RoundingNecessaryException::rationalScaleTooSmall();
}
}
return $this->numerator->toBigDecimal()->dividedBy($this->denominator, $scale, $roundingMode);
}
@@ -469,26 +449,32 @@ final readonly class BigRational extends BigNumber
#[Override]
public function toFloat(): float
{
$simplified = $this->simplified();
$numeratorFloat = $simplified->numerator->toFloat();
$denominatorFloat = $simplified->denominator->toFloat();
if (is_finite($numeratorFloat) && is_finite($denominatorFloat)) {
return $numeratorFloat / $denominatorFloat;
if ($this->denominator->isEqualTo(1)) {
return $this->numerator->toFloat();
}
// At least one side overflows to INF; use a decimal approximation instead.
// Avoid $this->numerator->toFloat() / $this->denominator->toFloat(): converting both operands to float first
// adds an extra rounding step before the division and can change the final float. Instead, divide in decimal
// first and convert the resulting decimal approximation to float once.
// We need ~17 significant digits for double precision (we use 20 for some margin). Since $scale controls
// decimal places (not significant digits), we subtract the estimated order of magnitude so that large results
// use fewer decimal places and small results use more (to look past leading zeros). Clamped to [0, 350] as
// doubles range from e-324 to e308 (350 ≈ 324 + 20 significant digits + margin).
$magnitude = strlen($simplified->numerator->abs()->toString()) - strlen($simplified->denominator->toString());
$magnitude = strlen($this->numerator->abs()->toString()) - strlen($this->denominator->toString());
$scale = min(350, max(0, 20 - $magnitude));
return $simplified->numerator
$result = $this->numerator
->toBigDecimal()
->dividedBy($simplified->denominator, $scale, RoundingMode::HalfEven)
->dividedBy($this->denominator, $scale, RoundingMode::HalfEven)
->toFloat();
// Preserve the sign when the decimal approximation underflows to zero.
if ($result === 0.0 && $this->numerator->isNegative()) {
return -0.0;
}
return $result;
}
#[Override]
@@ -518,11 +504,13 @@ final readonly class BigRational extends BigNumber
* - `171/70` returns `2.4(428571)`
* - `1/2` returns `0.5`
*
* @return non-empty-string
*
* @pure
*/
public function toRepeatingDecimalString(): string
{
if ($this->numerator->isZero()) {
if ($this->isZero()) {
return '0';
}
+43 -5
View File
@@ -4,32 +4,70 @@ declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when a division by zero occurs.
*/
final class DivisionByZeroException extends MathException
final class DivisionByZeroException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public static function divisionByZero(): DivisionByZeroException
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function divisionByZero(): self
{
return new self('Division by zero.');
}
/**
* @internal
*
* @pure
*/
public static function modulusMustNotBeZero(): DivisionByZeroException
public static function zeroModulus(): self
{
return new self('The modulus must not be zero.');
}
/**
* @internal
*
* @pure
*/
public static function denominatorMustNotBeZero(): DivisionByZeroException
public static function zeroDenominator(): self
{
return new self('The denominator of a rational number cannot be zero.');
return new self('The denominator of a rational number must not be zero.');
}
/**
* @internal
*
* @pure
*/
public static function reciprocalOfZero(): self
{
return new self('The reciprocal of zero is undefined.');
}
/**
* @internal
*
* @pure
*/
public static function zeroToNegativePower(): self
{
return new self('Cannot raise zero to a negative power.');
}
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Brick\Math\Exception;
use Brick\Math\BigInteger;
use RuntimeException;
use function sprintf;
@@ -12,17 +13,44 @@ use const PHP_INT_MAX;
use const PHP_INT_MIN;
/**
* Exception thrown when an integer overflow occurs.
* Exception thrown when a native integer overflow occurs.
*/
final class IntegerOverflowException extends MathException
final class IntegerOverflowException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public static function toIntOverflow(BigInteger $value): IntegerOverflowException
public function __construct(string $message)
{
$message = '%s is out of range %d to %d and cannot be represented as an integer.';
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function integerOutOfRange(BigInteger $value): self
{
$message = '%s is out of range [%d, %d] and cannot be represented as an integer.';
return new self(sprintf($message, $value->toString(), PHP_INT_MIN, PHP_INT_MAX));
}
/**
* @internal
*
* @pure
*/
public static function nativeIntegerOverflow(string $expression): self
{
return new self(sprintf(
'Cannot compute %s because the result is outside the native integer range [%d, %d].',
$expression,
PHP_INT_MIN,
PHP_INT_MAX,
));
}
}
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use function sprintf;
/**
* Exception thrown when an invalid argument is provided.
*/
final class InvalidArgumentException extends \InvalidArgumentException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function baseOutOfRange(int $base): self
{
return new self(sprintf('Base %d is out of range [2, 36].', $base));
}
/**
* @internal
*
* @pure
*/
public static function negativeScale(): self
{
return new self('The scale must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeBitIndex(): self
{
return new self('The bit index must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeBitCount(): self
{
return new self('The bit count must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function alphabetTooShort(): self
{
return new self('The alphabet must contain at least 2 characters.');
}
/**
* @internal
*
* @pure
*/
public static function duplicateCharsInAlphabet(): self
{
return new self('The alphabet must not contain duplicate characters.');
}
/**
* @internal
*
* @pure
*/
public static function minGreaterThanMax(): self
{
return new self('The minimum value must be less than or equal to the maximum value.');
}
/**
* @internal
*
* @pure
*/
public static function cannotConvertFloat(string $type): self
{
return new self(sprintf('Cannot convert %s to a BigDecimal.', $type));
}
/**
* @internal
*
* @pure
*/
public static function negativeExponent(): self
{
return new self('The exponent must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function negativeModulus(): self
{
return new self('The modulus must not be negative.');
}
/**
* @internal
*
* @pure
*/
public static function nonPositiveNthRootDegree(): self
{
return new self('The degree of an nth root must be a positive integer.');
}
}
+3 -3
View File
@@ -4,11 +4,11 @@ declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use Throwable;
/**
* Base class for all math exceptions.
* Base interface for all math exceptions.
*/
class MathException extends RuntimeException
interface MathException extends Throwable
{
}
+52 -1
View File
@@ -4,9 +4,60 @@ declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when attempting to perform an unsupported operation, such as a square root, on a negative number.
*/
final class NegativeNumberException extends MathException
final class NegativeNumberException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function squareRootOfNegativeNumber(): self
{
return new self('Cannot calculate the square root of a negative number.');
}
/**
* @internal
*
* @pure
*/
public static function nthRootOfNegativeNumber(): self
{
return new self('Cannot take an even nth root of a negative number.');
}
/**
* @internal
*
* @pure
*/
public static function toArbitraryBaseOfNegativeNumber(): self
{
return new self('Cannot convert a negative number to an arbitrary base.');
}
/**
* @internal
*
* @pure
*/
public static function unsignedBytesOfNegativeNumber(): self
{
return new self('Cannot convert a negative number to a byte string in unsigned mode.');
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when attempting to compute a modular inverse that does not exist.
*/
final class NoInverseException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function noModularInverse(): self
{
return new self('This number has no multiplicative inverse modulo the given modulus (they are not coprime).');
}
}
+62 -2
View File
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use function dechex;
use function ord;
use function sprintf;
@@ -12,20 +14,34 @@ use function strtoupper;
/**
* Exception thrown when attempting to create a number from a string with an invalid format.
*/
final class NumberFormatException extends MathException
final class NumberFormatException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function invalidFormat(string $value): self
{
return new self(sprintf(
'The given value "%s" does not represent a valid number.',
'Value "%s" does not represent a valid number.',
$value,
));
}
/**
* @internal
*
* @param string $char The failing character.
*
* @pure
@@ -38,6 +54,50 @@ final class NumberFormatException extends MathException
));
}
/**
* @internal
*
* @pure
*/
public static function charNotValidInBase(string $char, int $base): self
{
return new self(sprintf(
'Character %s is not valid in base %d.',
self::charToString($char),
$base,
));
}
/**
* @internal
*
* @pure
*/
public static function emptyNumber(): self
{
return new self('The number must not be empty.');
}
/**
* @internal
*
* @pure
*/
public static function emptyByteString(): self
{
return new self('The byte string must not be empty.');
}
/**
* @internal
*
* @pure
*/
public static function exponentTooLarge(): self
{
return new self('The exponent is too large to be represented as an integer.');
}
/**
* @pure
*/
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
use Throwable;
use function get_debug_type;
use function sprintf;
/**
* Exception thrown when random byte generation fails.
*/
final class RandomSourceException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message, ?Throwable $previous = null)
{
parent::__construct($message, 0, $previous);
}
/**
* @internal
*
* @pure
*/
public static function randomSourceFailure(Throwable $previous): self
{
return new self('Random byte generation failed.', $previous);
}
/**
* @internal
*
* @pure
*/
public static function invalidRandomBytesType(mixed $value): self
{
return new self(sprintf(
'The random bytes generator must return a string, got %s.',
get_debug_type($value),
));
}
/**
* @internal
*
* @pure
*/
public static function invalidRandomBytesLength(int $expectedLength, int $actualLength): self
{
return new self(sprintf(
'The random bytes generator returned %d byte(s), expected %d.',
$actualLength,
$expectedLength,
));
}
}
@@ -4,16 +4,160 @@ declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when a number cannot be represented at the requested scale without rounding.
*/
final class RoundingNecessaryException extends MathException
final class RoundingNecessaryException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public static function roundingNecessary(): RoundingNecessaryException
public function __construct(string $message)
{
return new self('Rounding is necessary to represent the result of the operation at this scale.');
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function decimalScaleTooSmall(): self
{
return new self('This decimal number cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalScaleTooSmall(): self
{
return new self('This rational number cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerDivisionNotExact(): self
{
return new self('The division has a non-zero remainder and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalDivisionNotExact(): self
{
return new self('The division yields a non-terminating decimal expansion and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalDivisionScaleTooSmall(): self
{
return new self('The division result is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerSquareRootNotExact(): self
{
return new self('The square root is not exact and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalSquareRootNotExact(): self
{
return new self('The square root is not exact and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalSquareRootScaleTooSmall(): self
{
return new self('The square root is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function integerNthRootNotExact(): self
{
return new self('The nth root is not exact and cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNthRootNotExact(): self
{
return new self('The nth root is not exact and cannot be represented as a decimal without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNthRootScaleTooSmall(): self
{
return new self('The nth root is exact but cannot be represented at the requested scale without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function decimalNotConvertibleToInteger(): self
{
return new self('This decimal number cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalNotConvertibleToInteger(): self
{
return new self('This rational number cannot be represented as an integer without rounding.');
}
/**
* @internal
*
* @pure
*/
public static function rationalNotConvertibleToDecimal(): self
{
return new self('This rational number has a non-terminating decimal expansion and cannot be represented as a decimal without rounding.');
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Exception;
use RuntimeException;
/**
* Exception thrown when the current PHP platform does not support a required feature.
*/
final class UnsupportedPlatformException extends RuntimeException implements MathException
{
/**
* @internal
*
* @pure
*/
public function __construct(string $message)
{
parent::__construct($message);
}
/**
* @internal
*
* @pure
*/
public static function unsupportedFloatFormat(): self
{
return new self('Unsupported float format: expected IEEE-754 double.');
}
}
+81 -28
View File
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\Exception\RoundingNecessaryException;
use Brick\Math\RoundingMode;
use function chr;
use function intdiv;
use function ltrim;
use function ord;
use function str_repeat;
@@ -30,11 +30,6 @@ use function substr;
*/
abstract readonly class Calculator
{
/**
* The maximum exponent value allowed for the pow() method.
*/
public const MAX_POWER = 1_000_000;
/**
* The alphabet for converting from and to base 2 to 36, lowercase.
*/
@@ -164,7 +159,7 @@ abstract readonly class Calculator
* Exponentiates a number.
*
* @param string $a The base number.
* @param int $e The exponent, validated as an integer between 0 and MAX_POWER.
* @param int $e The exponent, validated as a non-negative integer.
*
* @return string The power.
*
@@ -237,15 +232,11 @@ abstract readonly class Calculator
*/
public function gcd(string $a, string $b): string
{
if ($a === '0') {
return $this->abs($b);
while ($b !== '0') {
[$a, $b] = [$b, $this->divR($a, $b)];
}
if ($b === '0') {
return $this->abs($a);
}
return $this->gcd($b, $this->divR($a, $b));
return $this->abs($a);
}
/**
@@ -277,6 +268,64 @@ abstract readonly class Calculator
*/
abstract public function sqrt(string $n): string;
/**
* Returns the integer nth root of the given number, truncated toward zero.
*
* If $n is non-negative, the result is the largest x such that x^$k ≤ $n (floor).
* If $n is negative, $k MUST be odd, and the result is the negation of the floor root of |$n|
* (i.e., truncation toward zero: the smallest x such that x^$k ≥ $n).
*
* The caller MUST guarantee that $k ≥ 1 and that $n is non-negative when $k is even.
*
* This method can be overridden by the concrete implementation if the underlying library
* has built-in support for nth root calculations.
*
* @param string $n The number. May be negative only when $k is odd.
* @param int $k The root degree. Must be strictly positive.
*
* @pure
*/
public function nthRoot(string $n, int $k): string
{
if ($n === '0') {
return '0';
}
$negative = ($n[0] === '-');
$m = $negative ? substr($n, 1) : $n;
if ($m === '1') {
return $negative ? '-1' : '1';
}
// Initial overshoot: 10^ceil(strlen(m)/k) is strictly greater than the true root.
// Newton-Raphson requires starting above the true root to converge monotonically down.
$x = '1' . str_repeat('0', intdiv(strlen($m) - 1, $k) + 1);
$kStr = (string) $k;
$kMinusOneStr = (string) ($k - 1);
// Newton-Raphson recurrence for integer nth root:
// x_{i+1} = floor(((k-1) * x_i + floor(m / x_i^{k-1})) / k)
for (; ;) {
$nx = $this->divQ(
$this->add(
$this->mul($kMinusOneStr, $x),
$this->divQ($m, $this->pow($x, $k - 1)),
),
$kStr,
);
if ($this->cmp($nx, $x) >= 0) {
break;
}
$x = $nx;
}
return $negative ? $this->neg($x) : $x;
}
/**
* Converts a number from an arbitrary base.
*
@@ -407,17 +456,16 @@ abstract readonly class Calculator
/**
* Performs a rounded division.
*
* Rounding is performed when the remainder of the division is not zero.
* When the remainder of the division is not zero, rounding is performed according to the rounding mode provided,
* unless RoundingMode::Unnecessary is used, in which case the method returns null.
*
* @param string $a The dividend.
* @param string $b The divisor, must not be zero.
* @param RoundingMode $roundingMode The rounding mode.
*
* @throws RoundingNecessaryException If RoundingMode::Unnecessary is provided but rounding is necessary.
*
* @pure
*/
final public function divRound(string $a, string $b, RoundingMode $roundingMode): string
final public function divRound(string $a, string $b, RoundingMode $roundingMode): ?string
{
[$quotient, $remainder] = $this->divQR($a, $b);
@@ -436,7 +484,7 @@ abstract readonly class Calculator
switch ($roundingMode) {
case RoundingMode::Unnecessary:
if ($hasDiscardedFraction) {
throw RoundingNecessaryException::roundingNecessary();
return null;
}
break;
@@ -552,22 +600,27 @@ abstract readonly class Calculator
}
/**
* @return array{string, string, string} GCD, X, Y
* @param string $a Must be non-negative.
* @param string $b Must be non-negative.
*
* @return array{string, string} GCD, X
*
* @pure
*/
private function gcdExtended(string $a, string $b): array
{
if ($a === '0') {
return [$b, '0', '1'];
// Iterative extended Euclidean algorithm; recursion would exhaust memory on large inputs.
[$r0, $r1] = [$a, $b];
[$x0, $x1] = ['1', '0'];
while ($r1 !== '0') {
[$q, $r] = $this->divQR($r0, $r1);
[$r0, $r1] = [$r1, $r];
[$x0, $x1] = [$x1, $this->sub($x0, $this->mul($q, $x1))];
}
[$gcd, $x1, $y1] = $this->gcdExtended($this->mod($b, $a), $a);
$x = $this->sub($y1, $this->mul($this->divQ($b, $a), $x1));
$y = $x1;
return [$gcd, $x, $y];
return [$r0, $x0];
}
/**
@@ -65,6 +65,20 @@ final readonly class BcMathCalculator extends Calculator
#[Override]
public function pow(string $a, int $e): string
{
if ($e === 0) {
return '1';
}
// bcpow() allocates memory proportional to the exponent even when the base is trivial,
// exhausting memory on 32-bit builds at large exponents.
if ($a === '0' || $a === '1') {
return $a;
}
if ($a === '-1') {
return $e % 2 === 0 ? '1' : '-1';
}
return bcpow($a, (string) $e, 0);
}
@@ -21,10 +21,12 @@ use function gmp_mul;
use function gmp_or;
use function gmp_pow;
use function gmp_powm;
use function gmp_root;
use function gmp_sqrt;
use function gmp_strval;
use function gmp_sub;
use function gmp_xor;
use function substr;
/**
* Calculator implementation built around the GMP library.
@@ -149,4 +151,17 @@ final readonly class GmpCalculator extends Calculator
{
return gmp_strval(gmp_sqrt($n));
}
#[Override]
public function nthRoot(string $n, int $k): string
{
// Delegate on the absolute value and re-apply the sign ourselves so the
// truncation-toward-zero convention matches the shared Newton-Raphson fallback
// bit-for-bit, regardless of any PHP/GMP behaviour changes for negative inputs.
if ($n[0] === '-') {
return '-' . gmp_strval(gmp_root(substr($n, 1), $k));
}
return gmp_strval(gmp_root($n, $k));
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\RoundingMode;
use function ltrim;
use function rtrim;
use function str_pad;
use function str_repeat;
use function strlen;
use function substr;
use const STR_PAD_LEFT;
/**
* Shared helper for decimal operations.
*
* @internal
*/
final class DecimalHelper
{
private function __construct()
{
}
/**
* Computes the scale needed to represent the exact decimal result of a reduced fraction.
*
* Returns null if the denominator has prime factors other than 2 or 5.
*
* @param string $denominator The denominator of the reduced fraction. Must be strictly positive.
*
* @return non-negative-int|null
*
* @pure
*/
public static function computeScaleFromReducedFractionDenominator(string $denominator): ?int
{
$calculator = CalculatorRegistry::get();
$d = rtrim($denominator, '0');
/** @var non-negative-int $scale rtrim can only shorten a string */
$scale = strlen($denominator) - strlen($d);
foreach ([5, 2] as $prime) {
for (; ;) {
$lastDigit = (int) $d[-1];
if ($lastDigit % $prime !== 0) {
break;
}
$d = $calculator->divQ($d, (string) $prime);
$scale++;
}
}
return $d === '1' ? $scale : null;
}
/**
* Scales an unscaled decimal value to the requested scale.
*
* Returns null when rounding is necessary and the rounding mode is Unnecessary.
*
* @param string $value The unscaled value.
* @param int $currentScale The current scale.
* @param int $targetScale The target scale.
* @param RoundingMode $roundingMode The rounding mode.
*
* @return string|null The unscaled value at the target scale, or null if RoundingMode::Unnecessary is used and rounding is necessary.
*
* @pure
*/
public static function scale(string $value, int $currentScale, int $targetScale, RoundingMode $roundingMode): ?string
{
$scaled = self::tryScaleExactly($value, $currentScale, $targetScale);
if ($scaled !== null) {
return $scaled;
}
if ($roundingMode === RoundingMode::Unnecessary) {
return null;
}
$divisor = '1' . str_repeat('0', $currentScale - $targetScale);
return CalculatorRegistry::get()->divRound($value, $divisor, $roundingMode);
}
/**
* Adds leading zeros if necessary to represent the full decimal number.
*
* @param string $value The unscaled value.
* @param int $scale The current scale.
*
* @pure
*/
public static function padUnscaledValue(string $value, int $scale): string
{
$targetLength = $scale + 1;
$negative = ($value[0] === '-');
$length = strlen($value);
if ($negative) {
$length--;
}
if ($length >= $targetLength) {
return $value;
}
if ($negative) {
$value = substr($value, 1);
}
$value = str_pad($value, $targetLength, '0', STR_PAD_LEFT);
if ($negative) {
$value = '-' . $value;
}
return $value;
}
/**
* Tries to scale exactly without rounding, returning null when rounding would be required.
*
* @param string $value The unscaled value.
* @param int $currentScale The current scale.
* @param int $targetScale The target scale.
*
* @return string|null The unscaled value at the target scale, or null if rounding would be required.
*
* @pure
*/
public static function tryScaleExactly(string $value, int $currentScale, int $targetScale): ?string
{
if ($value === '0' || $targetScale === $currentScale) {
return $value;
}
if ($targetScale > $currentScale) {
return $value . str_repeat('0', $targetScale - $currentScale);
}
$negative = ($value[0] === '-');
if ($negative) {
$value = substr($value, 1);
}
$value = self::padUnscaledValue($value, $currentScale);
$discardedDigits = $currentScale - $targetScale;
if (substr($value, -$discardedDigits) !== str_repeat('0', $discardedDigits)) {
return null;
}
$value = substr($value, 0, -$discardedDigits);
$value = ltrim($value, '0');
if ($value === '') {
return '0';
}
if ($negative) {
$value = '-' . $value;
}
return $value;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Brick\Math\Internal;
use Brick\Math\Exception\IntegerOverflowException;
use function is_int;
use function sprintf;
use const PHP_INT_MIN;
/**
* Helpers for arithmetic operations that throw on native integer overflow.
*
* @internal
*/
final class Safe
{
private function __construct()
{
}
/**
* @pure
*/
public static function add(int $a, int $b): int
{
$result = $a + $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d + %d', $a, $b));
}
/**
* @pure
*/
public static function sub(int $a, int $b): int
{
$result = $a - $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d - %d', $a, $b));
}
/**
* @pure
*/
public static function mul(int $a, int $b): int
{
$result = $a * $b;
if (is_int($result)) {
return $result;
}
// @phpstan-ignore deadCode.unreachable
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('%d * %d', $a, $b));
}
/**
* @pure
*/
public static function neg(int $value): int
{
if ($value === PHP_INT_MIN) {
throw IntegerOverflowException::nativeIntegerOverflow(sprintf('-(%d)', $value));
}
return -$value;
}
}
+1 -51
View File
@@ -87,57 +87,7 @@ enum RoundingMode
*
* Note that this is the rounding mode that statistically minimizes
* cumulative error when applied repeatedly over a sequence of calculations.
* It is sometimes known as "Banker's rounding", and is chiefly used in the USA.
* It is sometimes known as "Banker's rounding", and is the default rounding mode in IEEE 754.
*/
case HalfEven;
/**
* @deprecated Use RoundingMode::Unnecessary instead.
*/
public const UNNECESSARY = self::Unnecessary;
/**
* @deprecated Use RoundingMode::Up instead.
*/
public const UP = self::Up;
/**
* @deprecated Use RoundingMode::Down instead.
*/
public const DOWN = self::Down;
/**
* @deprecated Use RoundingMode::Ceiling instead.
*/
public const CEILING = self::Ceiling;
/**
* @deprecated Use RoundingMode::Floor instead.
*/
public const FLOOR = self::Floor;
/**
* @deprecated Use RoundingMode::HalfUp instead.
*/
public const HALF_UP = self::HalfUp;
/**
* @deprecated Use RoundingMode::HalfDown instead.
*/
public const HALF_DOWN = self::HalfDown;
/**
* @deprecated Use RoundingMode::HalfCeiling instead.
*/
public const HALF_CEILING = self::HalfCeiling;
/**
* @deprecated Use RoundingMode::HalfFloor instead.
*/
public const HALF_FLOOR = self::HalfFloor;
/**
* @deprecated Use RoundingMode::HalfEven instead.
*/
public const HALF_EVEN = self::HalfEven;
}
+321 -92
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -11,6 +11,7 @@ return array(
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'606a39d89246991a373564698c2d8383' => $vendorDir . '/symfony/polyfill-php85/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php',
'667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php',
@@ -18,7 +19,6 @@ return array(
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'9c67151ae59aff4788964ce8eb2a0f43' => $vendorDir . '/clue/stream-filter/src/functions_include.php',
'8cff32064859f4559445b89279f3199c' => $vendorDir . '/php-http/message/src/filters.php',
'606a39d89246991a373564698c2d8383' => $vendorDir . '/symfony/polyfill-php85/bootstrap.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'2203a247e6fda86070a5e4e07aed533a' => $vendorDir . '/symfony/clock/Resources/now.php',
'deecf9d6b2672fb73429f9b28fdee35f' => $vendorDir . '/symfony/polyfill-deepclone/bootstrap.php',
@@ -32,8 +32,8 @@ return array(
'6124b4c8570aa390c21fafd04a26c69f' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/deep_copy.php',
'801c31d8ed748cfa537fa45402288c95' => $vendorDir . '/psy/psysh/src/functions.php',
'e39a8b23c42d4e1452234d762b03835a' => $vendorDir . '/ramsey/uuid/src/functions.php',
'662a729f963d39afe703c9d9b7ab4a8c' => $vendorDir . '/symfony/polyfill-php83/bootstrap.php',
'9d2b9fc6db0f153a0a149fefb182415e' => $vendorDir . '/symfony/polyfill-php84/bootstrap.php',
'2c2415ec15363ede1bff13a287462ba1' => $vendorDir . '/symfony/polyfill-php86/bootstrap.php',
'476ca15b8d69b04665cd879be9cb4c68' => $vendorDir . '/laravel/framework/src/Illuminate/Collections/functions.php',
'265b4faa2b3a9766332744949e83bf97' => $vendorDir . '/laravel/framework/src/Illuminate/Collections/helpers.php',
'c7a3c339e7e14b60e06a2d7fcce9476b' => $vendorDir . '/laravel/framework/src/Illuminate/Events/functions.php',
+1 -1
View File
@@ -14,9 +14,9 @@ return array(
'Termwind\\' => array($vendorDir . '/nunomaduro/termwind/src'),
'Symfony\\Thanks\\' => array($vendorDir . '/symfony/thanks/src'),
'Symfony\\Polyfill\\Uuid\\' => array($vendorDir . '/symfony/polyfill-uuid'),
'Symfony\\Polyfill\\Php86\\' => array($vendorDir . '/symfony/polyfill-php86'),
'Symfony\\Polyfill\\Php85\\' => array($vendorDir . '/symfony/polyfill-php85'),
'Symfony\\Polyfill\\Php84\\' => array($vendorDir . '/symfony/polyfill-php84'),
'Symfony\\Polyfill\\Php83\\' => array($vendorDir . '/symfony/polyfill-php83'),
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'),
+328 -99
View File
File diff suppressed because it is too large Load Diff
+610 -719
View File
File diff suppressed because it is too large Load Diff
+158 -174
View File
@@ -3,7 +3,7 @@
'name' => 'laravel/laravel',
'pretty_version' => '2.x-dev',
'version' => '2.9999999.9999999.9999999-dev',
'reference' => 'cb59689ead6ba29ea3b8dfe896c8ef9ff8da8b3c',
'reference' => '39191885e53b2c8ab49b3d594ece9825b6fd87b4',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -20,9 +20,9 @@
'dev_requirement' => false,
),
'aws/aws-sdk-php' => array(
'pretty_version' => '3.388.0',
'version' => '3.388.0.0',
'reference' => '6dd9a0674641ef7d302a50cc8f275eb443182dc9',
'pretty_version' => '3.388.1',
'version' => '3.388.1.0',
'reference' => 'c04551617a8cb58d73a8009cb994ccc629590cdf',
'type' => 'library',
'install_path' => __DIR__ . '/../aws/aws-sdk-php',
'aliases' => array(),
@@ -47,9 +47,9 @@
'dev_requirement' => true,
),
'brick/math' => array(
'pretty_version' => '0.14.8',
'version' => '0.14.8.0',
'reference' => '63422359a44b7f06cae63c3b429b59e8efcc0629',
'pretty_version' => '0.18.0',
'version' => '0.18.0.0',
'reference' => '82944324d1c1bdb2c2618e89978d4e2ad78d69ad',
'type' => 'library',
'install_path' => __DIR__ . '/../brick/math',
'aliases' => array(),
@@ -268,217 +268,217 @@
'illuminate/auth' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/broadcasting' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/bus' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/cache' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/collections' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/concurrency' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/conditionable' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/config' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/console' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/container' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/contracts' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/cookie' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/database' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/encryption' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/events' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/filesystem' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/hashing' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/http' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/json-schema' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/log' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/macroable' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/mail' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/notifications' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/pagination' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/pipeline' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/process' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/queue' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/redis' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/reflection' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/routing' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/session' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/support' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/testing' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/translation' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/validation' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'illuminate/view' => array(
'dev_requirement' => false,
'replaced' => array(
0 => 'v12.63.0',
0 => 'v13.19.0',
),
),
'knplabs/github-api' => array(
@@ -497,9 +497,9 @@
),
),
'laravel/framework' => array(
'pretty_version' => 'v12.63.0',
'version' => '12.63.0.0',
'reference' => '7adfddbf4738f2e6cae5419b0e6bc46d4cccfbcf',
'pretty_version' => 'v13.19.0',
'version' => '13.19.0.0',
'reference' => '514502b38e11bd676ecf83b271c9452cc7500f16',
'type' => 'library',
'install_path' => __DIR__ . '/../laravel/framework',
'aliases' => array(),
@@ -508,7 +508,7 @@
'laravel/laravel' => array(
'pretty_version' => '2.x-dev',
'version' => '2.9999999.9999999.9999999-dev',
'reference' => 'cb59689ead6ba29ea3b8dfe896c8ef9ff8da8b3c',
'reference' => '39191885e53b2c8ab49b3d594ece9825b6fd87b4',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -533,9 +533,9 @@
'dev_requirement' => false,
),
'laravel/tinker' => array(
'pretty_version' => 'v2.11.1',
'version' => '2.11.1.0',
'reference' => 'c9f80cc835649b5c1842898fb043f8cc098dd741',
'pretty_version' => 'v3.0.2',
'version' => '3.0.2.0',
'reference' => '4faba77764bd33411735936acdf30446d058c78b',
'type' => 'library',
'install_path' => __DIR__ . '/../laravel/tinker',
'aliases' => array(),
@@ -836,54 +836,54 @@
'dev_requirement' => false,
),
'phpunit/php-code-coverage' => array(
'pretty_version' => '11.0.12',
'version' => '11.0.12.0',
'reference' => '2c1ed04922802c15e1de5d7447b4856de949cf56',
'pretty_version' => '12.5.7',
'version' => '12.5.7.0',
'reference' => '186dab580576598076de6818596d12b61801880e',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-code-coverage',
'aliases' => array(),
'dev_requirement' => true,
),
'phpunit/php-file-iterator' => array(
'pretty_version' => '5.1.1',
'version' => '5.1.1.0',
'reference' => '2f3a64888c814fc235386b7387dd5b5ed92ad903',
'pretty_version' => '6.0.1',
'version' => '6.0.1.0',
'reference' => '3d1cd096ef6bea4bf2762ba586e35dbd317cbfd5',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-file-iterator',
'aliases' => array(),
'dev_requirement' => true,
),
'phpunit/php-invoker' => array(
'pretty_version' => '5.0.1',
'version' => '5.0.1.0',
'reference' => 'c1ca3814734c07492b3d4c5f794f4b0995333da2',
'pretty_version' => '6.0.0',
'version' => '6.0.0.0',
'reference' => '12b54e689b07a25a9b41e57736dfab6ec9ae5406',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-invoker',
'aliases' => array(),
'dev_requirement' => true,
),
'phpunit/php-text-template' => array(
'pretty_version' => '4.0.1',
'version' => '4.0.1.0',
'reference' => '3e0404dc6b300e6bf56415467ebcb3fe4f33e964',
'pretty_version' => '5.0.0',
'version' => '5.0.0.0',
'reference' => 'e1367a453f0eda562eedb4f659e13aa900d66c53',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-text-template',
'aliases' => array(),
'dev_requirement' => true,
),
'phpunit/php-timer' => array(
'pretty_version' => '7.0.1',
'version' => '7.0.1.0',
'reference' => '3b415def83fbcb41f991d9ebf16ae4ad8b7837b3',
'pretty_version' => '8.0.0',
'version' => '8.0.0.0',
'reference' => 'f258ce36aa457f3aa3339f9ed4c81fc66dc8c2cc',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/php-timer',
'aliases' => array(),
'dev_requirement' => true,
),
'phpunit/phpunit' => array(
'pretty_version' => '11.5.56',
'version' => '11.5.56.0',
'reference' => '5f83edffa6967c3db468d48a695ec7bcb02e9256',
'pretty_version' => '12.5.31',
'version' => '12.5.31.0',
'reference' => '0608d157a284f15cc73b99a3327eff06b66a176d',
'type' => 'library',
'install_path' => __DIR__ . '/../phpunit/phpunit',
'aliases' => array(),
@@ -931,7 +931,7 @@
'psr/container-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.1|2.0',
0 => '1.1 || 2.0',
),
),
'psr/event-dispatcher' => array(
@@ -1009,8 +1009,9 @@
'psr/log-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0|2.0|3.0',
1 => '3.0.0',
0 => '1.0 || 2.0 || 3.0',
1 => '1.0|2.0|3.0',
2 => '3.0.0',
),
),
'psr/simple-cache' => array(
@@ -1025,7 +1026,8 @@
'psr/simple-cache-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0|2.0|3.0',
0 => '1.0 || 2.0 || 3.0',
1 => '1.0|2.0|3.0',
),
),
'psy/psysh' => array(
@@ -1071,135 +1073,117 @@
),
),
'sebastian/cli-parser' => array(
'pretty_version' => '3.0.2',
'version' => '3.0.2.0',
'reference' => '15c5dd40dc4f38794d383bb95465193f5e0ae180',
'pretty_version' => '4.2.1',
'version' => '4.2.1.0',
'reference' => '7d05781b13f7dec9043a629a21d086ed74582a15',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/cli-parser',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/code-unit' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'reference' => '54391c61e4af8078e5b276ab082b6d3c54c9ad64',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/code-unit',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/code-unit-reverse-lookup' => array(
'pretty_version' => '4.0.1',
'version' => '4.0.1.0',
'reference' => '183a9b2632194febd219bb9246eee421dad8d45e',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/code-unit-reverse-lookup',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/comparator' => array(
'pretty_version' => '6.3.3',
'version' => '6.3.3.0',
'reference' => '2c95e1e86cb8dd41beb8d502057d1081ccc8eca9',
'pretty_version' => '7.1.8',
'version' => '7.1.8.0',
'reference' => '7c65c1e79836812819705b473a90c12399542485',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/comparator',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/complexity' => array(
'pretty_version' => '4.0.1',
'version' => '4.0.1.0',
'reference' => 'ee41d384ab1906c68852636b6de493846e13e5a0',
'pretty_version' => '5.0.0',
'version' => '5.0.0.0',
'reference' => 'bad4316aba5303d0221f43f8cee37eb58d384bbb',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/complexity',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/diff' => array(
'pretty_version' => '6.0.2',
'version' => '6.0.2.0',
'reference' => 'b4ccd857127db5d41a5b676f24b51371d76d8544',
'pretty_version' => '7.0.0',
'version' => '7.0.0.0',
'reference' => '7ab1ea946c012266ca32390913653d844ecd085f',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/diff',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/environment' => array(
'pretty_version' => '7.2.1',
'version' => '7.2.1.0',
'reference' => 'a5c75038693ad2e8d4b6c15ba2403532647830c4',
'pretty_version' => '8.1.2',
'version' => '8.1.2.0',
'reference' => '9d32c685773823b1983e256ae4ecd48a10d6e439',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/environment',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/exporter' => array(
'pretty_version' => '6.3.2',
'version' => '6.3.2.0',
'reference' => '70a298763b40b213ec087c51c739efcaa90bcd74',
'pretty_version' => '7.0.3',
'version' => '7.0.3.0',
'reference' => 'c5e21b5de653ce0a769fb36f5cdfcb5e7a32cf23',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/exporter',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/global-state' => array(
'pretty_version' => '7.0.2',
'version' => '7.0.2.0',
'reference' => '3be331570a721f9a4b5917f4209773de17f747d7',
'pretty_version' => '8.0.3',
'version' => '8.0.3.0',
'reference' => 'b164d3274d6537ab462591c5755f76a8f5b1aae9',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/global-state',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/lines-of-code' => array(
'pretty_version' => '3.0.1',
'version' => '3.0.1.0',
'reference' => 'd36ad0d782e5756913e42ad87cb2890f4ffe467a',
'pretty_version' => '4.0.1',
'version' => '4.0.1.0',
'reference' => 'd543b8ef219dcd8da262cbb958639a96bedba10e',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/lines-of-code',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/object-enumerator' => array(
'pretty_version' => '6.0.1',
'version' => '6.0.1.0',
'reference' => 'f5b498e631a74204185071eb41f33f38d64608aa',
'pretty_version' => '7.0.0',
'version' => '7.0.0.0',
'reference' => '1effe8e9b8e068e9ae228e542d5d11b5d16db894',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/object-enumerator',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/object-reflector' => array(
'pretty_version' => '4.0.1',
'version' => '4.0.1.0',
'reference' => '6e1a43b411b2ad34146dee7524cb13a068bb35f9',
'pretty_version' => '5.0.0',
'version' => '5.0.0.0',
'reference' => '4bfa827c969c98be1e527abd576533293c634f6a',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/object-reflector',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/recursion-context' => array(
'pretty_version' => '6.0.3',
'version' => '6.0.3.0',
'reference' => 'f6458abbf32a6c8174f8f26261475dc133b3d9dc',
'pretty_version' => '7.0.1',
'version' => '7.0.1.0',
'reference' => '0b01998a7d5b1f122911a66bebcb8d46f0c82d8c',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/recursion-context',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/type' => array(
'pretty_version' => '5.1.3',
'version' => '5.1.3.0',
'reference' => 'f77d2d4e78738c98d9a68d2596fe5e8fa380f449',
'pretty_version' => '6.0.4',
'version' => '6.0.4.0',
'reference' => '82ff822c2edc46724be9f7411d3163021f602773',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/type',
'aliases' => array(),
'dev_requirement' => true,
),
'sebastian/version' => array(
'pretty_version' => '5.0.2',
'version' => '5.0.2.0',
'reference' => 'c687e3387b99f5b03b6caa64c74b63e2936ff874',
'pretty_version' => '6.0.0',
'version' => '6.0.0.0',
'reference' => '3e6ccf7657d4f0a59200564b08cead899313b53c',
'type' => 'library',
'install_path' => __DIR__ . '/../sebastian/version',
'aliases' => array(),
@@ -1317,9 +1301,9 @@
'dev_requirement' => false,
),
'symfony/console' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => '92f58bc4bf97a92ed1b9f367f0cd44f20bde0e87',
'pretty_version' => 'v8.1.1',
'version' => '8.1.1.0',
'reference' => 'b711a8ab808b6c074c6b8caef70d0fd8d6b6d07d',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/console',
'aliases' => array(),
@@ -1344,9 +1328,9 @@
'dev_requirement' => false,
),
'symfony/error-handler' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => '4e1a093b481f323e6e326451f9760c3868430673',
'pretty_version' => 'v8.1.0',
'version' => '8.1.0.0',
'reference' => 'd8aeb1abd3fef84795567850d3a567bdb5945ee5',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/error-handler',
'aliases' => array(),
@@ -1386,45 +1370,45 @@
'dev_requirement' => false,
),
'symfony/finder' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => '13b38720174286f55d1761152b575a8d1436fc25',
'pretty_version' => 'v8.1.1',
'version' => '8.1.1.0',
'reference' => 'e2989e762c70f9490fa3a00a0ac0fae5aa97a531',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/finder',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/http-foundation' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => '06db5ae1552177bf8572f8908839f12e3c06aed3',
'pretty_version' => 'v8.1.1',
'version' => '8.1.1.0',
'reference' => '6a168c8fcee806b57ac020244da14293d1f9a883',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/http-foundation',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/http-kernel' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => 'e99af79b1e776646eda0e1c23b7b45c184ff99be',
'pretty_version' => 'v8.1.1',
'version' => '8.1.1.0',
'reference' => '89d8d6e7fbab3d9eda89ccb5ecdf44a74c4ec9d2',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/http-kernel',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/mailer' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => 'f88ce03ae73e3edb5c176ce1f337709996e88495',
'pretty_version' => 'v8.1.1',
'version' => '8.1.1.0',
'reference' => '4fa583a7377f28d54e4de442fba76375b2e20a12',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/mailer',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/mime' => array(
'pretty_version' => 'v7.4.13',
'version' => '7.4.13.0',
'reference' => 'a845722765c4f6b2ce88beaf4f4479975b186770',
'pretty_version' => 'v8.1.0',
'version' => '8.1.0.0',
'reference' => 'b164ae7e3f7915aacfe9ee155f2f358502440664',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/mime',
'aliases' => array(),
@@ -1502,15 +1486,6 @@
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php83' => array(
'pretty_version' => 'v1.38.2',
'version' => '1.38.2.0',
'reference' => '796a26abb75ce49f3a84433cd81bf1009d73d5f8',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php83',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php84' => array(
'pretty_version' => 'v1.38.1',
'version' => '1.38.1.0',
@@ -1529,6 +1504,15 @@
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php86' => array(
'pretty_version' => 'v1.38.0',
'version' => '1.38.0.0',
'reference' => 'fcec68d64f46dc84e1f6ffcf2c6dda40ff3143ad',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php86',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-uuid' => array(
'pretty_version' => 'v1.37.0',
'version' => '1.37.0.0',
@@ -1539,18 +1523,18 @@
'dev_requirement' => false,
),
'symfony/process' => array(
'pretty_version' => 'v7.4.13',
'version' => '7.4.13.0',
'reference' => 'f5804be144caceb570f6747519999636b664f24c',
'pretty_version' => 'v8.1.0',
'version' => '8.1.0.0',
'reference' => 'c4a9e58f235a6bf7f97ffbfedae2687353ac79e5',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/process',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/routing' => array(
'pretty_version' => 'v7.4.13',
'version' => '7.4.13.0',
'reference' => '3a162171bb008e5e0f15dce6581373a4c0e8390d',
'pretty_version' => 'v8.1.0',
'version' => '8.1.0.0',
'reference' => 'fe0bfec72c8a806109fb9c3a5f2b898fe0c76eb3',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/routing',
'aliases' => array(),
@@ -1608,18 +1592,18 @@
),
),
'symfony/uid' => array(
'pretty_version' => 'v7.4.9',
'version' => '7.4.9.0',
'reference' => '2676b524340abcfe4d6151ec698463cebafee439',
'pretty_version' => 'v8.1.0',
'version' => '8.1.0.0',
'reference' => '7393f157a55f7e70a4de0334435c55a5a8fe749a',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/uid',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/var-dumper' => array(
'pretty_version' => 'v7.4.14',
'version' => '7.4.14.0',
'reference' => '9a3a56a4a1e65a5cb4f8d13801fe8ab0a170e358',
'pretty_version' => 'v8.1.1',
'version' => '8.1.1.0',
'reference' => '40096a2515a979f3125c5c928603995b8664c62a',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/var-dumper',
'aliases' => array(),
@@ -1644,9 +1628,9 @@
'dev_requirement' => false,
),
'theseer/tokenizer' => array(
'pretty_version' => '1.3.1',
'version' => '1.3.1.0',
'reference' => 'b7489ce515e168639d17feec34b8847c326b0b3c',
'pretty_version' => '2.0.1',
'version' => '2.0.1.0',
'reference' => '7989e43bf381af0eac72e4f0ca5bcbfa81658be4',
'type' => 'library',
'install_path' => __DIR__ . '/../theseer/tokenizer',
'aliases' => array(),
+2
View File
@@ -29,6 +29,8 @@ Laravel has the most extensive and thorough [documentation](https://laravel.com/
If you're not in the mood to read, [Laracasts](https://laracasts.com) contains thousands of video tutorials covering a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library.
You can also watch bite-sized lessons with real-world projects on [Laravel Learn](https://laravel.com/learn), where you will be guided through building a Laravel application from scratch while learning PHP fundamentals.
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
+121 -115
View File
@@ -1,21 +1,24 @@
{
"name": "laravel/framework",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"keywords": [
"framework",
"laravel"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"require": {
"php": "^8.2",
"php": "^8.3",
"ext-ctype": "*",
"ext-filter": "*",
"ext-hash": "*",
@@ -24,15 +27,16 @@
"ext-session": "*",
"ext-tokenizer": "*",
"composer-runtime-api": "^2.2",
"brick/math": "^0.11|^0.12|^0.13|^0.14",
"brick/math": "^0.14.2 || ^0.15 || ^0.16 || ^0.17 || ^0.18",
"doctrine/inflector": "^2.0.5",
"dragonmantank/cron-expression": "^3.4",
"egulias/email-validator": "^3.2.1|^4.0",
"egulias/email-validator": "^4.0",
"fruitcake/php-cors": "^1.3",
"guzzlehttp/guzzle": "^7.8.2",
"guzzlehttp/promises": "^2.0.3",
"guzzlehttp/uri-template": "^1.0",
"laravel/prompts": "^0.3.0",
"laravel/serializable-closure": "^1.3|^2.0",
"laravel/serializable-closure": "^2.0.10",
"league/commonmark": "^2.8.1",
"league/flysystem": "^3.25.1",
"league/flysystem-local": "^3.25.1",
@@ -40,28 +44,55 @@
"monolog/monolog": "^3.0",
"nesbot/carbon": "^3.8.4",
"nunomaduro/termwind": "^2.0",
"psr/container": "^1.1.1|^2.0.1",
"psr/log": "^1.0|^2.0|^3.0",
"psr/simple-cache": "^1.0|^2.0|^3.0",
"psr/container": "^1.1.1 || ^2.0.1",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"psr/simple-cache": "^1.0 || ^2.0 || ^3.0",
"ramsey/uuid": "^4.7",
"symfony/console": "^7.2.0",
"symfony/error-handler": "^7.2.0",
"symfony/finder": "^7.2.0",
"symfony/http-foundation": "^7.2.0",
"symfony/http-kernel": "^7.2.0",
"symfony/mailer": "^7.2.0",
"symfony/mime": "^7.2.0",
"symfony/polyfill-php83": "^1.33",
"symfony/polyfill-php84": "^1.34",
"symfony/polyfill-php85": "^1.34",
"symfony/process": "^7.2.0",
"symfony/routing": "^7.2.0",
"symfony/uid": "^7.2.0",
"symfony/var-dumper": "^7.2.0",
"symfony/console": "^7.4.0 || ^8.0.0",
"symfony/error-handler": "^7.4.0 || ^8.0.0",
"symfony/finder": "^7.4.0 || ^8.0.0",
"symfony/http-foundation": "^7.4.0 || ^8.0.0",
"symfony/http-kernel": "^7.4.0 || ^8.0.0",
"symfony/mailer": "^7.4.0 || ^8.0.0",
"symfony/mime": "^7.4.0 || ^8.0.0",
"symfony/polyfill-php84": "^1.36",
"symfony/polyfill-php85": "^1.36",
"symfony/polyfill-php86": "^1.36",
"symfony/process": "^7.4.5 || ^8.0.5",
"symfony/routing": "^7.4.0 || ^8.0.0",
"symfony/uid": "^7.4.0 || ^8.0.0",
"symfony/var-dumper": "^7.4.0 || ^8.0.0",
"tijsverkoyen/css-to-inline-styles": "^2.2.5",
"vlucas/phpdotenv": "^5.6.1",
"voku/portable-ascii": "^2.0.2"
},
"require-dev": {
"ext-gmp": "*",
"ably/ably-php": "^1.0",
"aws/aws-sdk-php": "^3.322.9",
"fakerphp/faker": "^1.24",
"guzzlehttp/psr7": "^2.9",
"laravel/pint": "^1.18",
"league/flysystem-aws-s3-v3": "^3.25.1",
"league/flysystem-ftp": "^3.25.1",
"league/flysystem-path-prefixing": "^3.25.1",
"league/flysystem-read-only": "^3.25.1",
"league/flysystem-sftp-v3": "^3.25.1",
"mockery/mockery": "^1.6.10",
"opis/json-schema": "^2.4.1",
"orchestra/testbench-core": "^11.0.0",
"pda/pheanstalk": "^7.0.0 || ^8.0.0",
"php-http/discovery": "^1.15",
"phpstan/phpstan": "^2.0",
"phpunit/phpunit": "^11.5.50 || ^12.5.8 || ^13.0.3",
"predis/predis": "^2.3 || ^3.0",
"rector/rector": "^2.3",
"resend/resend-php": "^1.0",
"symfony/cache": "^7.4.0 || ^8.0.0",
"symfony/http-client": "^7.4.0 || ^8.0.0",
"symfony/psr-http-message-bridge": "^7.4.0 || ^8.0.0",
"symfony/translation": "^7.4.0 || ^8.0.0"
},
"replace": {
"illuminate/auth": "self.version",
"illuminate/broadcasting": "self.version",
@@ -90,8 +121,8 @@
"illuminate/pipeline": "self.version",
"illuminate/process": "self.version",
"illuminate/queue": "self.version",
"illuminate/reflection": "self.version",
"illuminate/redis": "self.version",
"illuminate/reflection": "self.version",
"illuminate/routing": "self.version",
"illuminate/session": "self.version",
"illuminate/support": "self.version",
@@ -101,75 +132,13 @@
"illuminate/view": "self.version",
"spatie/once": "*"
},
"require-dev": {
"ext-gmp": "*",
"ably/ably-php": "^1.0",
"aws/aws-sdk-php": "^3.322.9",
"fakerphp/faker": "^1.24",
"guzzlehttp/promises": "^2.0.3",
"guzzlehttp/psr7": "^2.4",
"laravel/pint": "^1.18",
"league/flysystem-aws-s3-v3": "^3.25.1",
"league/flysystem-ftp": "^3.25.1",
"league/flysystem-path-prefixing": "^3.25.1",
"league/flysystem-read-only": "^3.25.1",
"league/flysystem-sftp-v3": "^3.25.1",
"mockery/mockery": "^1.6.10",
"opis/json-schema": "^2.4.1",
"orchestra/testbench-core": "^10.9.0",
"pda/pheanstalk": "^5.0.6|^7.0.0",
"php-http/discovery": "^1.15",
"phpstan/phpstan": "^2.1.41",
"phpunit/phpunit": "^10.5.35|^11.5.3|^12.0.1",
"predis/predis": "^2.3|^3.0",
"resend/resend-php": "^0.10.0|^1.0",
"symfony/cache": "^7.2.0",
"symfony/http-client": "^7.2.0",
"symfony/psr-http-message-bridge": "^7.2.0",
"symfony/translation": "^7.2.0"
},
"conflict": {
"tightenco/collect": "<5.5.33"
},
"provide": {
"psr/container-implementation": "1.1|2.0",
"psr/log-implementation": "1.0|2.0|3.0",
"psr/simple-cache-implementation": "1.0|2.0|3.0"
},
"autoload": {
"files": [
"src/Illuminate/Collections/functions.php",
"src/Illuminate/Collections/helpers.php",
"src/Illuminate/Events/functions.php",
"src/Illuminate/Filesystem/functions.php",
"src/Illuminate/Foundation/helpers.php",
"src/Illuminate/Log/functions.php",
"src/Illuminate/Reflection/helpers.php",
"src/Illuminate/Support/functions.php",
"src/Illuminate/Support/helpers.php"
],
"psr-4": {
"Illuminate\\": "src/Illuminate/",
"Illuminate\\Support\\": [
"src/Illuminate/Macroable/",
"src/Illuminate/Collections/",
"src/Illuminate/Conditionable/",
"src/Illuminate/Reflection/"
]
}
},
"autoload-dev": {
"files": [
"tests/Database/stubs/MigrationCreatorFakeMigration.php"
],
"psr-4": {
"Illuminate\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "12.x-dev"
}
"psr/container-implementation": "1.1 || 2.0",
"psr/log-implementation": "1.0 || 2.0 || 3.0",
"psr/simple-cache-implementation": "1.0 || 2.0 || 3.0"
},
"suggest": {
"ext-apcu": "Required to use the APC cache driver.",
@@ -180,10 +149,10 @@
"ext-pcntl": "Required to use all features of the queue worker and console signal trapping.",
"ext-pdo": "Required to use all database features.",
"ext-posix": "Required to use all features of the queue worker.",
"ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0|^6.0).",
"ext-redis": "Required to use the Redis cache and queue drivers (^4.0 || ^5.0 || ^6.0).",
"ably/ably-php": "Required to use the Ably broadcast driver (^1.0).",
"aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage, and SES mail driver (^3.322.9).",
"brianium/paratest": "Required to run tests in parallel (^7.0|^8.0).",
"brianium/paratest": "Required to run tests in parallel (^7.0 || ^8.0).",
"fakerphp/faker": "Required to generate fake data using the fake() helper (^1.23).",
"filp/whoops": "Required for friendly error pages in development (^2.14.3).",
"laravel/tinker": "Required to use the tinker console command (^2.0).",
@@ -193,32 +162,69 @@
"league/flysystem-read-only": "Required to use read-only disks (^3.25.1)",
"league/flysystem-sftp-v3": "Required to use the Flysystem SFTP driver (^3.25.1).",
"mockery/mockery": "Required to use mocking (^1.6).",
"pda/pheanstalk": "Required to use the beanstalk queue driver (^5.0).",
"pda/pheanstalk": "Required to use the beanstalk queue driver (^7.0 || ^8.0).",
"php-http/discovery": "Required to use PSR-7 bridging features (^1.15).",
"phpunit/phpunit": "Required to use assertions and run tests (^10.5.35|^11.5.3|^12.0.1).",
"predis/predis": "Required to use the predis connector (^2.3|^3.0).",
"phpunit/phpunit": "Required to use assertions and run tests (^11.5.50 || ^12.5.8 || ^13.0.3).",
"predis/predis": "Required to use the predis connector (^2.3 || ^3.0).",
"psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).",
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0|^7.0).",
"resend/resend-php": "Required to enable support for the Resend mail transport (^0.10.0|^1.0).",
"symfony/cache": "Required to PSR-6 cache bridge (^7.2).",
"symfony/filesystem": "Required to enable support for relative symbolic links (^7.2).",
"symfony/http-client": "Required to enable support for the Symfony API mail transports (^7.2).",
"symfony/mailgun-mailer": "Required to enable support for the Mailgun mail transport (^7.2).",
"symfony/postmark-mailer": "Required to enable support for the Postmark mail transport (^7.2).",
"symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^7.2)."
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0 || ^7.0).",
"resend/resend-php": "Required to enable support for the Resend mail transport (^0.10.0 || ^1.0).",
"spatie/fork": "Required to use the 'fork' concurrency driver (^1.2).",
"symfony/cache": "Required to PSR-6 cache bridge (^7.4 || ^8.0).",
"symfony/filesystem": "Required to enable support for relative symbolic links (^7.4 || ^8.0).",
"symfony/http-client": "Required to enable support for the Symfony API mail transports (^7.4 || ^8.0).",
"symfony/mailgun-mailer": "Required to enable support for the Mailgun mail transport (^7.4 || ^8.0).",
"symfony/postmark-mailer": "Required to enable support for the Postmark mail transport (^7.4 || ^8.0).",
"symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^7.4 || ^8.0)."
},
"minimum-stability": "dev",
"prefer-stable": true,
"autoload": {
"psr-4": {
"Illuminate\\": "src/Illuminate/",
"Illuminate\\Support\\": [
"src/Illuminate/Macroable/",
"src/Illuminate/Collections/",
"src/Illuminate/Conditionable/",
"src/Illuminate/Reflection/"
]
},
"files": [
"src/Illuminate/Collections/functions.php",
"src/Illuminate/Collections/helpers.php",
"src/Illuminate/Events/functions.php",
"src/Illuminate/Filesystem/functions.php",
"src/Illuminate/Foundation/helpers.php",
"src/Illuminate/Log/functions.php",
"src/Illuminate/Reflection/helpers.php",
"src/Illuminate/Support/functions.php",
"src/Illuminate/Support/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"Illuminate\\Tests\\": "tests/"
},
"files": [
"tests/Database/stubs/MigrationCreatorFakeMigration.php"
]
},
"config": {
"sort-packages": true,
"audit": {
"ignore": {
"GHSA-vvj3-c3rp-c85p": "Ensure testing features are compatible with affected PHPUnit versions"
}
},
"allow-plugins": {
"composer/package-versions-deprecated": true,
"php-http/discovery": false
}
},
"audit": {
"ignore": {
"GHSA-qrr6-mg7r-m243": "Ensure testing features are compatible with affected PHPUnit versions",
"GHSA-vvj3-c3rp-c85p": "Ensure testing features are compatible with affected PHPUnit versions"
}
},
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true
"extra": {
"branch-alias": {
"dev-master": "13.0.x-dev"
}
}
}
+1 -1
View File
@@ -143,7 +143,7 @@ return [
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
| Supported drivers: "file", "cache", "array"
|
*/
+9 -3
View File
@@ -27,8 +27,8 @@ return [
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
| "redis", "dynamodb", "storage", "octane",
| "session", "failover", "null"
|
*/
@@ -58,6 +58,12 @@ return [
'lock_path' => storage_path('framework/cache/data'),
],
'storage' => [
'driver' => 'storage',
'disk' => env('CACHE_STORAGE_DISK'),
'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
@@ -117,6 +123,6 @@ return [
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel'), '_').'_cache_'),
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];
+9 -1
View File
@@ -99,6 +99,14 @@ return [
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
'pooled' => env('DB_POOLED', false),
'direct' => array_filter([
'host' => env('DB_DIRECT_HOST'),
'port' => env('DB_DIRECT_PORT'),
'username' => env('DB_DIRECT_USERNAME'),
'password' => env('DB_DIRECT_PASSWORD'),
'sslmode' => env('DB_DIRECT_SSLMODE'),
]),
],
'sqlsrv' => [
@@ -151,7 +159,7 @@ return [
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel'), '_').'_database_'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
+7
View File
@@ -62,6 +62,13 @@ return [
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
'overflow' => [
'enabled' => env('SQS_OVERFLOW_ENABLED', false),
'store' => env('SQS_OVERFLOW_STORE'),
'always' => false,
'delete_after_processing' => true,
'flush_on_clear' => env('SQS_OVERFLOW_FLUSH_ON_CLEAR', false),
],
],
'redis' => [
+1 -1
View File
@@ -129,7 +129,7 @@ return [
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel'), '_').'_session'
Str::snake((string) env('APP_NAME', 'laravel')).'_session'
),
/*
-212
View File
@@ -1,212 +0,0 @@
{
"preset": "empty",
"rules": {
"align_multiline_comment": true,
"array_indentation": true,
"array_syntax": {
"syntax": "short"
},
"binary_operator_spaces": {
"default": "single_space"
},
"blank_line_after_namespace": true,
"blank_line_after_opening_tag": true,
"blank_line_before_statement": {
"statements": [
"return"
]
},
"blank_line_between_import_groups": true,
"blank_lines_before_namespace": true,
"braces_position": {
"control_structures_opening_brace": "same_line",
"functions_opening_brace": "next_line_unless_newline_at_signature_end",
"anonymous_functions_opening_brace": "same_line",
"classes_opening_brace": "next_line_unless_newline_at_signature_end",
"anonymous_classes_opening_brace": "next_line_unless_newline_at_signature_end",
"allow_single_line_empty_anonymous_classes": false,
"allow_single_line_anonymous_functions": false
},
"cast_spaces": true,
"class_definition": true,
"class_reference_name_casing": true,
"clean_namespace": true,
"compact_nullable_type_declaration": true,
"concat_space": true,
"constant_case": {
"case": "lower"
},
"control_structure_braces": true,
"declare_equal_normalize": true,
"elseif": true,
"encoding": true,
"full_opening_tag": true,
"function_declaration": true,
"heredoc_to_nowdoc": true,
"include": true,
"increment_style": {
"style": "post"
},
"indentation_type": true,
"integer_literal_case": true,
"lambda_not_used_import": true,
"line_ending": true,
"list_syntax": {
"syntax": "short"
},
"lowercase_cast": true,
"lowercase_keywords": true,
"lowercase_static_reference": true,
"magic_constant_casing": true,
"magic_method_casing": true,
"method_argument_space": {
"on_multiline": "ignore"
},
"method_chaining_indentation": true,
"modernize_types_casting": true,
"multiline_whitespace_before_semicolons": {
"strategy": "no_multi_line"
},
"native_function_casing": true,
"native_type_declaration_casing": true,
"no_alternative_syntax": true,
"no_binary_string": true,
"no_blank_lines_after_class_opening": true,
"no_blank_lines_after_phpdoc": true,
"no_closing_tag": true,
"no_empty_phpdoc": true,
"no_empty_statement": true,
"no_extra_blank_lines": {
"tokens": [
"extra",
"throw",
"use"
]
},
"no_leading_import_slash": true,
"no_leading_namespace_whitespace": true,
"no_mixed_echo_print": {
"use": "echo"
},
"no_multiline_whitespace_around_double_arrow": true,
"no_short_bool_cast": true,
"no_singleline_whitespace_before_semicolons": true,
"no_space_around_double_colon": true,
"no_spaces_around_offset": {
"positions": [
"inside",
"outside"
]
},
"no_spaces_after_function_name": true,
"no_trailing_comma_in_singleline": true,
"no_trailing_whitespace": true,
"no_trailing_whitespace_in_comment": true,
"no_unneeded_braces": true,
"no_unneeded_control_parentheses": true,
"no_unneeded_import_alias": true,
"no_unset_cast": true,
"no_unused_imports": true,
"no_useless_return": true,
"no_whitespace_before_comma_in_array": true,
"no_whitespace_in_blank_line": true,
"normalize_index_brace": true,
"not_operator_with_successor_space": true,
"nullable_type_declaration_for_default_null_value": true,
"object_operator_without_whitespace": true,
"ordered_imports": {
"sort_algorithm": "alpha",
"imports_order": [
"const",
"class",
"function"
]
},
"phpdoc_align": {
"align": "left",
"spacing": {
"param": 2
}
},
"phpdoc_indent": true,
"phpdoc_inline_tag_normalizer": true,
"phpdoc_no_access": true,
"phpdoc_no_package": true,
"phpdoc_no_useless_inheritdoc": true,
"phpdoc_order": {
"order": [
"param",
"return",
"throws"
]
},
"phpdoc_return_self_reference": true,
"phpdoc_scalar": true,
"phpdoc_separation": {
"groups": [
[
"deprecated",
"link",
"see",
"since"
],
[
"author",
"copyright",
"license"
],
[
"category",
"package",
"subpackage"
],
[
"property",
"property-read",
"property-write"
],
[
"param",
"return"
]
]
},
"phpdoc_single_line_var_spacing": true,
"phpdoc_summary": true,
"phpdoc_trim": true,
"phpdoc_types": true,
"phpdoc_var_without_name": true,
"return_type_declaration": {
"space_before": "none"
},
"short_scalar_cast": true,
"single_blank_line_at_eof": true,
"single_class_element_per_statement": true,
"single_import_per_statement": true,
"single_line_after_imports": true,
"single_line_comment_style": true,
"single_quote": true,
"space_after_semicolon": true,
"spaces_inside_parentheses": true,
"standardize_not_equals": true,
"switch_case_semicolon_to_colon": true,
"switch_case_space": true,
"switch_continue_to_break": true,
"ternary_operator_spaces": true,
"trailing_comma_in_multiline": true,
"trim_array_spaces": true,
"type_declaration_spaces": true,
"types_spaces": true,
"unary_operator_spaces": true,
"visibility_required": {
"elements": [
"method",
"property"
]
},
"whitespace_after_comma_in_array": true
},
"notPath": [
"tests/Foundation/fixtures/bad-syntax-strategy.php"
]
}
@@ -8,7 +8,7 @@ use Throwable;
class AuthorizationException extends Exception
{
/**
* The response from the gate.
* The authorization response returned by the gate.
*
* @var \Illuminate\Auth\Access\Response
*/
@@ -124,13 +124,7 @@ class Gate implements GateContract
{
$abilities = is_array($ability) ? $ability : func_get_args();
foreach ($abilities as $ability) {
if (! isset($this->abilities[enum_value($ability)])) {
return false;
}
}
return true;
return array_all($abilities, fn ($ability) => isset($this->abilities[enum_value($ability)]));
}
/**
@@ -4,7 +4,12 @@ namespace Illuminate\Auth;
use Closure;
use Illuminate\Contracts\Auth\Factory as FactoryContract;
use Illuminate\Support\RebindsCallbacksToSelf;
use InvalidArgumentException;
use ReflectionException;
use RuntimeException;
use function Illuminate\Support\enum_value;
/**
* @mixin \Illuminate\Contracts\Auth\Guard
@@ -12,7 +17,7 @@ use InvalidArgumentException;
*/
class AuthManager implements FactoryContract
{
use CreatesUserProviders;
use CreatesUserProviders, RebindsCallbacksToSelf;
/**
* The application instance.
@@ -59,12 +64,12 @@ class AuthManager implements FactoryContract
/**
* Attempt to get the guard from the local cache.
*
* @param string|null $name
* @param \UnitEnum|string|null $name
* @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
*/
public function guard($name = null)
{
$name = $name ?: $this->getDefaultDriver();
$name = enum_value($name) ?: $this->getDefaultDriver();
return $this->guards[$name] ??= $this->resolve($name);
}
@@ -195,12 +200,12 @@ class AuthManager implements FactoryContract
/**
* Set the default guard driver the factory should serve.
*
* @param string $name
* @param \UnitEnum|string|null $name
* @return void
*/
public function shouldUse($name)
{
$name = $name ?: $this->getDefaultDriver();
$name = enum_value($name) ?: $this->getDefaultDriver();
$this->setDefaultDriver($name);
@@ -210,12 +215,12 @@ class AuthManager implements FactoryContract
/**
* Set the default authentication driver name.
*
* @param string $name
* @param \UnitEnum|string $name
* @return void
*/
public function setDefaultDriver($name)
{
$this->app['config']['auth.defaults.guard'] = $name;
$this->app['config']['auth.defaults.guard'] = enum_value($name);
}
/**
@@ -264,10 +269,19 @@ class AuthManager implements FactoryContract
*
* @param string $driver
* @param \Closure $callback
*
* @param-closure-this $this $callback
*
* @return $this
*/
public function extend($driver, Closure $callback)
{
try {
$callback = $this->bindCallbackToSelf($callback) ?? throw new RuntimeException('Unable to bind custom driver callback');
} catch (ReflectionException $e) {
throw new RuntimeException('Unable to bind custom driver callback', previous: $e);
}
$this->customCreators[$driver] = $callback;
return $this;
@@ -74,7 +74,7 @@ class ResetPassword extends Notification
protected function buildMailMessage($url)
{
return (new MailMessage)
->subject(Lang::get('Reset Password Notification'))
->subject(Lang::get('Reset your password'))
->line(Lang::get('You are receiving this email because we received a password reset request for your account.'))
->action(Lang::get('Reset Password'), $url)
->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]))
@@ -62,7 +62,7 @@ class VerifyEmail extends Notification
protected function buildMailMessage($url)
{
return (new MailMessage)
->subject(Lang::get('Verify Email Address'))
->subject(Lang::get('Verify your email address'))
->line(Lang::get('Please click the button below to verify your email address.'))
->action(Lang::get('Verify Email Address'), $url)
->line(Lang::get('If you did not create an account, no further action is required.'));
@@ -5,6 +5,8 @@ namespace Illuminate\Auth\Passwords;
use Illuminate\Contracts\Auth\PasswordBrokerFactory as FactoryContract;
use InvalidArgumentException;
use function Illuminate\Support\enum_value;
/**
* @mixin \Illuminate\Contracts\Auth\PasswordBroker
*/
@@ -37,12 +39,12 @@ class PasswordBrokerManager implements FactoryContract
/**
* Attempt to get the broker from the local cache.
*
* @param string|null $name
* @param \UnitEnum|string|null $name
* @return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker($name = null)
{
$name = $name ?: $this->getDefaultDriver();
$name = enum_value($name) ?: $this->getDefaultDriver();
return $this->brokers[$name] ?? ($this->brokers[$name] = $this->resolve($name));
}
@@ -132,12 +134,12 @@ class PasswordBrokerManager implements FactoryContract
/**
* Set the default password broker name.
*
* @param string $name
* @param \UnitEnum|string $name
* @return void
*/
public function setDefaultDriver($name)
{
$this->app['config']['auth.defaults.passwords'] = $name;
$this->app['config']['auth.defaults.passwords'] = enum_value($name);
}
/**
+25 -25
View File
@@ -2,44 +2,44 @@
"name": "illuminate/auth",
"description": "The Illuminate Auth package.",
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"require": {
"php": "^8.2",
"ext-hash": "*",
"illuminate/collections": "^12.0",
"illuminate/contracts": "^12.0",
"illuminate/http": "^12.0",
"illuminate/macroable": "^12.0",
"illuminate/queue": "^12.0",
"illuminate/support": "^12.0"
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"require": {
"php": "^8.3",
"ext-hash": "*",
"illuminate/collections": "^13.0",
"illuminate/contracts": "^13.0",
"illuminate/http": "^13.0",
"illuminate/macroable": "^13.0",
"illuminate/queue": "^13.0",
"illuminate/support": "^13.0"
},
"suggest": {
"illuminate/console": "Required to use the auth:clear-resets command (^13.0).",
"illuminate/queue": "Required to fire login / logout events (^13.0).",
"illuminate/session": "Required to use the session based guard (^13.0)."
},
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Illuminate\\Auth\\": ""
}
},
"extra": {
"branch-alias": {
"dev-master": "12.x-dev"
}
},
"suggest": {
"illuminate/console": "Required to use the auth:clear-resets command (^12.0).",
"illuminate/queue": "Required to fire login / logout events (^12.0).",
"illuminate/session": "Required to use the session based guard (^12.0)."
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev"
"extra": {
"branch-alias": {
"dev-master": "13.0.x-dev"
}
}
}
@@ -6,14 +6,22 @@ use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastingFactory;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\DeleteWhenMissingModels;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\ReadsQueueAttributes;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Arr;
use ReflectionClass;
use ReflectionProperty;
use Throwable;
use function Illuminate\Support\enum_value;
class BroadcastEvent implements ShouldQueue
{
use Queueable;
use Queueable, ReadsQueueAttributes;
/**
* The event instance.
@@ -65,11 +73,12 @@ class BroadcastEvent implements ShouldQueue
public function __construct($event)
{
$this->event = $event;
$this->tries = property_exists($event, 'tries') ? $event->tries : null;
$this->timeout = property_exists($event, 'timeout') ? $event->timeout : null;
$this->backoff = property_exists($event, 'backoff') ? $event->backoff : null;
$this->tries = $this->getAttributeValue($event, Tries::class, 'tries');
$this->timeout = $this->getAttributeValue($event, Timeout::class, 'timeout');
$this->backoff = $this->getAttributeValue($event, Backoff::class, 'backoff');
$this->afterCommit = property_exists($event, 'afterCommit') ? $event->afterCommit : null;
$this->maxExceptions = property_exists($event, 'maxExceptions') ? $event->maxExceptions : null;
$this->maxExceptions = $this->getAttributeValue($event, MaxExceptions::class, 'maxExceptions');
$this->deleteWhenMissingModels = $this->getAttributeValue($event, DeleteWhenMissingModels::class, 'deleteWhenMissingModels');
}
/**
@@ -81,7 +90,7 @@ class BroadcastEvent implements ShouldQueue
public function handle(BroadcastingFactory $manager)
{
$name = method_exists($this->event, 'broadcastAs')
? $this->event->broadcastAs()
? enum_value($this->event->broadcastAs())
: get_class($this->event);
$channels = Arr::wrap($this->event->broadcastOn());
@@ -18,17 +18,27 @@ use Illuminate\Contracts\Broadcasting\ShouldRescue;
use Illuminate\Contracts\Bus\Dispatcher as BusDispatcherContract;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Foundation\CachesRoutes;
use Illuminate\Queue\Attributes\Connection as ConnectionAttribute;
use Illuminate\Queue\Attributes\Queue as QueueAttribute;
use Illuminate\Queue\Attributes\ReadsQueueAttributes;
use Illuminate\Support\Queue\Concerns\ResolvesQueueRoutes;
use Illuminate\Support\RebindsCallbacksToSelf;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Pusher\Pusher;
use ReflectionException;
use RuntimeException;
use Throwable;
use function Illuminate\Support\enum_value;
/**
* @mixin \Illuminate\Contracts\Broadcasting\Broadcaster
*/
class BroadcastManager implements FactoryContract
{
use ReadsQueueAttributes, RebindsCallbacksToSelf, ResolvesQueueRoutes;
/**
* The application instance.
*
@@ -78,7 +88,7 @@ class BroadcastManager implements FactoryContract
$router->match(
['get', 'post'], '/broadcasting/auth',
'\\'.BroadcastController::class.'@authenticate'
)->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]);
)->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class]);
});
}
@@ -100,7 +110,7 @@ class BroadcastManager implements FactoryContract
$router->match(
['get', 'post'], '/broadcasting/user-auth',
'\\'.BroadcastController::class.'@authenticateUser'
)->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class]);
)->withoutMiddleware([\Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class]);
});
}
@@ -196,6 +206,12 @@ class BroadcastManager implements FactoryContract
default => null,
};
if (is_null($queue)) {
$queue = $this->getAttributeValue($event, QueueAttribute::class, 'queue')
?? $this->resolveQueueFromQueueRoute($event)
?? null;
}
$broadcastEvent = new BroadcastEvent(clone $event);
if ($event instanceof ShouldBeUnique) {
@@ -207,7 +223,12 @@ class BroadcastManager implements FactoryContract
}
$push = fn () => $this->app->make('queue')
->connection($event->connection ?? null)
->connection(
$event->connection
?? $this->getAttributeValue($event, ConnectionAttribute::class, 'connection')
?? $this->resolveConnectionFromQueueRoute($event)
?? null
)
->pushOn($queue, $broadcastEvent);
$event instanceof ShouldRescue
@@ -231,25 +252,25 @@ class BroadcastManager implements FactoryContract
}
/**
* Get a driver instance.
* Get a broadcaster instance by name.
*
* @param string|null $driver
* @param \UnitEnum|string|null $name
* @return mixed
*/
public function connection($driver = null)
public function connection($name = null)
{
return $this->driver($driver);
return $this->driver($name);
}
/**
* Get a driver instance.
*
* @param string|null $name
* @param \UnitEnum|string|null $name
* @return mixed
*/
public function driver($name = null)
{
$name = $name ?: $this->getDefaultDriver();
$name = enum_value($name) ?: $this->getDefaultDriver();
return $this->drivers[$name] = $this->get($name);
}
@@ -272,6 +293,7 @@ class BroadcastManager implements FactoryContract
* @return \Illuminate\Contracts\Broadcasting\Broadcaster
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
protected function resolve($name)
{
@@ -447,29 +469,29 @@ class BroadcastManager implements FactoryContract
*/
public function getDefaultDriver()
{
return $this->app['config']['broadcasting.default'];
return $this->app['config']['broadcasting.default'] ?? 'null';
}
/**
* Set the default driver name.
*
* @param string $name
* @param \UnitEnum|string $name
* @return void
*/
public function setDefaultDriver($name)
{
$this->app['config']['broadcasting.default'] = $name;
$this->app['config']['broadcasting.default'] = enum_value($name);
}
/**
* Disconnect the given driver / connection and remove it from local cache.
*
* @param string|null $name
* @param \UnitEnum|string|null $name
* @return void
*/
public function purge($name = null)
{
$name ??= $this->getDefaultDriver();
$name = enum_value($name) ?? $this->getDefaultDriver();
unset($this->drivers[$name]);
}
@@ -479,10 +501,19 @@ class BroadcastManager implements FactoryContract
*
* @param string $driver
* @param \Closure $callback
*
* @param-closure-this $this $callback
*
* @return $this
*/
public function extend($driver, Closure $callback)
{
try {
$callback = $this->bindCallbackToSelf($callback) ?? throw new RuntimeException('Unable to bind custom driver callback');
} catch (ReflectionException $e) {
throw new RuntimeException('Unable to bind custom driver callback', previous: $e);
}
$this->customCreators[$driver] = $callback;
return $this;
@@ -2,44 +2,44 @@
"name": "illuminate/broadcasting",
"description": "The Illuminate Broadcasting package.",
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"require": {
"php": "^8.2",
"psr/log": "^1.0|^2.0|^3.0",
"illuminate/bus": "^12.0",
"illuminate/collections": "^12.0",
"illuminate/container": "^12.0",
"illuminate/contracts": "^12.0",
"illuminate/queue": "^12.0",
"illuminate/support": "^12.0"
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"require": {
"php": "^8.3",
"illuminate/bus": "^13.0",
"illuminate/collections": "^13.0",
"illuminate/container": "^13.0",
"illuminate/contracts": "^13.0",
"illuminate/queue": "^13.0",
"illuminate/support": "^13.0",
"psr/log": "^1.0 || ^2.0 || ^3.0"
},
"suggest": {
"ext-hash": "Required to use the Ably and Pusher broadcast drivers.",
"ably/ably-php": "Required to use the Ably broadcast driver (^1.0).",
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0 || ^7.0)."
},
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Illuminate\\Broadcasting\\": ""
}
},
"extra": {
"branch-alias": {
"dev-master": "12.x-dev"
}
},
"suggest": {
"ext-hash": "Required to use the Ably and Pusher broadcast drivers.",
"ably/ably-php": "Required to use the Ably broadcast driver (^1.0).",
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0|^7.0)."
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev"
"extra": {
"branch-alias": {
"dev-master": "13.0.x-dev"
}
}
}
+44 -9
View File
@@ -6,6 +6,7 @@ use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Bus\Events\BatchCanceled;
use Illuminate\Bus\Events\BatchFinished;
use Illuminate\Bus\Events\BatchStarted;
use Illuminate\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Queue\Factory as QueueFactory;
@@ -136,7 +137,7 @@ class Batch implements Arrayable, JsonSerializable
/**
* Get a fresh instance of the batch represented by this ID.
*
* @return self
* @return self|null
*/
public function fresh()
{
@@ -147,7 +148,7 @@ class Batch implements Arrayable, JsonSerializable
* Add additional jobs to the batch.
*
* @param \Illuminate\Support\Enumerable|object|array $jobs
* @return self
* @return self|null
*/
public function add($jobs)
{
@@ -161,10 +162,17 @@ class Batch implements Arrayable, JsonSerializable
$chain = $this->prepareBatchedChain($job);
return $chain->first()
->allOnQueue($this->options['queue'] ?? null)
->allOnConnection($this->options['connection'] ?? null)
->chain($chain->slice(1)->values()->all());
$first = $chain->first();
if (isset($this->options['queue'])) {
$first->allOnQueue($this->options['queue']);
}
if (isset($this->options['connection'])) {
$first->allOnConnection($this->options['connection']);
}
return $first->chain($chain->slice(1)->values()->all());
} else {
$job->withBatchId($this->id);
@@ -230,6 +238,14 @@ class Batch implements Arrayable, JsonSerializable
{
$counts = $this->decrementPendingJobs($jobId);
if ($this->isFirstJobProcessed($counts)) {
$container = Container::getInstance();
if ($container->bound(Dispatcher::class)) {
$container->make(Dispatcher::class)->dispatch(new BatchStarted($this));
}
}
if ($this->hasProgressCallbacks()) {
$this->invokeCallbacks('progress');
}
@@ -335,8 +351,16 @@ class Batch implements Arrayable, JsonSerializable
{
$counts = $this->incrementFailedJobs($jobId);
if ($this->isFirstJobProcessed($counts)) {
$container = Container::getInstance();
if ($container->bound(Dispatcher::class)) {
$container->make(Dispatcher::class)->dispatch(new BatchStarted($this));
}
}
if ($counts->failedJobs === 1 && ! $this->allowsFailures()) {
$this->cancel();
$this->cancel($e);
}
if ($this->allowsFailures()) {
@@ -368,6 +392,16 @@ class Batch implements Arrayable, JsonSerializable
return $this->repository->incrementFailedJobs($this->id, $jobId);
}
/**
* Determine if this is the first job processed in the batch.
*
* @return bool
*/
protected function isFirstJobProcessed(UpdatedBatchJobCounts $counts): bool
{
return $this->totalJobs - $counts->pendingJobs + $counts->failedJobs === 1;
}
/**
* Determine if the batch has "catch" callbacks.
*
@@ -399,16 +433,17 @@ class Batch implements Arrayable, JsonSerializable
/**
* Cancel the batch.
*
* @param \Throwable|null $exception
* @return void
*/
public function cancel()
public function cancel(?Throwable $exception = null)
{
$this->repository->cancel($this->id);
$container = Container::getInstance();
if ($container->bound(Dispatcher::class)) {
$container->make(Dispatcher::class)->dispatch(new BatchCanceled($this));
$container->make(Dispatcher::class)->dispatch(new BatchCanceled($this, $exception));
}
}
@@ -85,8 +85,10 @@ interface BatchRepository
/**
* Execute the given Closure within a storage specific transaction.
*
* @param \Closure $callback
* @return mixed
* @template TReturn
*
* @param (\Closure(): TReturn) $callback
* @return TReturn
*/
public function transaction(Closure $callback);
+1 -1
View File
@@ -48,7 +48,7 @@ trait Batchable
{
$batch = $this->batch();
return $batch && ! $batch->cancelled();
return $batch && ! $batch->finished() && ! $batch->cancelled();
}
/**
@@ -33,7 +33,7 @@ class BusServiceProvider extends ServiceProvider implements DeferrableProvider
);
$this->app->alias(
Dispatcher::class, QueueingDispatcherContract::class
DispatcherContract::class, QueueingDispatcherContract::class
);
}
@@ -304,8 +304,10 @@ class DatabaseBatchRepository implements PrunableBatchRepository
/**
* Execute the given Closure within a storage specific transaction.
*
* @param \Closure $callback
* @return mixed
* @template TReturn
*
* @param (\Closure(): TReturn) $callback
* @return TReturn
*/
public function transaction(Closure $callback)
{
@@ -0,0 +1,173 @@
<?php
namespace Illuminate\Bus;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Queue\Attributes\DebounceFor;
use Illuminate\Queue\Attributes\ReadsQueueAttributes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
class DebounceLock
{
use ReadsQueueAttributes;
/**
* The cache repository implementation.
*
* @var \Illuminate\Contracts\Cache\Repository
*/
protected $cache;
/**
* Create a new debounce lock manager instance.
*
* @param \Illuminate\Contracts\Cache\Repository $cache
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
/**
* Store a debounce owner token for the given job.
*
* Overwrites any existing token, implementing last-writer-wins semantics.
*
* @param mixed $job
* @param int|null $debounceFor
* @param int|null $maxWait
* @return array{owner: string, maxWaitExceeded: bool}
*/
public function acquire($job, $debounceFor = null, $maxWait = null)
{
$cache = $this->resolveCache($job);
$ttl = max(($debounceFor ?? $this->getDebounceDelay($job)) * 10, 300);
$cache->put($key = static::getKey($job), $owner = Str::random(40), $ttl);
return [
'owner' => $owner,
'maxWaitExceeded' => $this->maxWaitExceeded(
$cache, $key, $ttl, $maxWait ?? $this->getMaxDebounceWait($job)
),
];
}
/**
* Determine if the maximum debounce wait time has been exceeded.
*/
protected function maxWaitExceeded(Cache $cache, string $key, int $ttl, ?int $maxWait): bool
{
if (is_null($maxWait)) {
return false;
}
$timestampKey = $key.':first_dispatched_at';
$firstDispatchedAt = $cache->get($timestampKey);
if (is_null($firstDispatchedAt)) {
$cache->put($timestampKey, Carbon::now()->getTimestamp(), $ttl);
return false;
}
$elapsed = Carbon::now()->getTimestamp() - $firstDispatchedAt;
if ($elapsed >= $maxWait) {
$cache->forget($timestampKey);
return true;
}
return false;
}
/**
* Get the current owner for the given job.
*
* @param mixed $job
* @return string|null
*/
public function getCurrentOwner($job)
{
return $this->resolveCache($job)->get(static::getKey($job));
}
/**
* Remove the debounce token for the given job.
*
* @param mixed $job
* @param string $owner
* @return void
*/
public function release($job, string $owner = '')
{
$key = static::getKey($job);
$cache = $this->resolveCache($job);
if (! empty($owner) && $cache->get($key) !== $owner) {
return;
}
$cache->forget($key);
$cache->forget($key.':first_dispatched_at');
}
/**
* Get the debounce delay for the given job.
*
* @param mixed $job
* @return int|null
*/
public function getDebounceDelay($job)
{
return $this->getAttributeValue($job, DebounceFor::class, 'debounceFor');
}
/**
* Get the maximum debounce wait time for the given job.
*
* @param mixed $job
* @return int|null
*/
public function getMaxDebounceWait($job)
{
return $this->getAttributeInstance($job, DebounceFor::class)?->maxWait ?? null;
}
/**
* Generate the cache key for the given job.
*
* @param mixed $job
* @return string
*/
public static function getKey($job)
{
$debounceId = method_exists($job, 'debounceId')
? $job->debounceId()
: ($job->debounceId ?? '');
$jobName = method_exists($job, 'displayName')
? hash('xxh128', $job->displayName())
: get_class($job);
return 'laravel_debounced_job:'.$jobName.':'.$debounceId;
}
/**
* Resolve the cache store for the given job.
*
* @param mixed $job
* @return \Illuminate\Contracts\Cache\Repository
*/
protected function resolveCache($job)
{
return method_exists($job, 'debounceVia')
? ($job->debounceVia() ?? $this->cache)
: $this->cache;
}
}
+56 -4
View File
@@ -9,13 +9,20 @@ use Illuminate\Contracts\Queue\Queue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\PendingChain;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Queue\Attributes\Connection;
use Illuminate\Queue\Attributes\Delay;
use Illuminate\Queue\Attributes\Queue as QueueAttribute;
use Illuminate\Queue\Attributes\ReadsQueueAttributes;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Jobs\SyncJob;
use Illuminate\Support\Collection;
use Illuminate\Support\Queue\Concerns\ResolvesQueueRoutes;
use RuntimeException;
class Dispatcher implements QueueingDispatcher
{
use ReadsQueueAttributes, ResolvesQueueRoutes;
/**
* The container implementation.
*
@@ -133,6 +140,43 @@ class Dispatcher implements QueueingDispatcher
return $this->pipeline->send($command)->through($this->pipes)->then($callback);
}
/**
* Dispatch multiple commands in bulk to their appropriate handlers on the queue.
*
* @param iterable $jobs
* @return void
*/
public function bulk($jobs)
{
$groups = [];
foreach ($jobs as $job) {
if (! $this->queueResolver || ! $this->commandShouldBeQueued($job)) {
$this->dispatchNow($job);
continue;
}
$connection = $this->getAttributeValue($job, Connection::class, 'connection')
?? $this->resolveConnectionFromQueueRoute($job)
?? null;
$queue = $this->getAttributeValue($job, QueueAttribute::class, 'queue')
?? $this->resolveQueueFromQueueRoute($job)
?? null;
$groups[$connection.':'.$queue]['connection'] = $connection;
$groups[$connection.':'.$queue]['queue'] = $queue;
$groups[$connection.':'.$queue]['jobs'][] = $job;
}
foreach ($groups as $group) {
($this->queueResolver)($group['connection'])->bulk(
$group['jobs'], '', $group['queue']
);
}
}
/**
* Attempt to find the batch with the given ID.
*
@@ -215,7 +259,9 @@ class Dispatcher implements QueueingDispatcher
*/
public function dispatchToQueue($command)
{
$connection = $command->connection ?? null;
$connection = $this->getAttributeValue($command, Connection::class, 'connection')
?? $this->resolveConnectionFromQueueRoute($command)
?? null;
$queue = ($this->queueResolver)($connection);
@@ -239,11 +285,17 @@ class Dispatcher implements QueueingDispatcher
*/
protected function pushCommandToQueue($queue, $command)
{
if (isset($command->delay)) {
return $queue->later($command->delay, $command, queue: $command->queue ?? null);
$queueName = $this->getAttributeValue($command, QueueAttribute::class, 'queue')
?? $this->resolveQueueFromQueueRoute($command)
?? null;
$delay = $this->getAttributeValue($command, Delay::class, 'delay');
if (isset($delay)) {
return $queue->later($delay, $command, queue: $queueName);
}
return $queue->push($command, queue: $command->queue ?? null);
return $queue->push($command, queue: $queueName);
}
/**
@@ -377,8 +377,10 @@ class DynamoBatchRepository implements BatchRepository
/**
* Execute the given Closure within a storage specific transaction.
*
* @param \Closure $callback
* @return mixed
* @template TReturn
*
* @param (\Closure(): TReturn) $callback
* @return TReturn
*/
public function transaction(Closure $callback)
{
@@ -3,6 +3,7 @@
namespace Illuminate\Bus\Events;
use Illuminate\Bus\Batch;
use Throwable;
class BatchCanceled
{
@@ -10,9 +11,11 @@ class BatchCanceled
* Create a new event instance.
*
* @param \Illuminate\Bus\Batch $batch The batch instance.
* @param \Throwable|null $exception The exception that caused the cancellation.
*/
public function __construct(
public Batch $batch,
public ?Throwable $exception = null,
) {
}
}
@@ -0,0 +1,18 @@
<?php
namespace Illuminate\Bus\Events;
use Illuminate\Bus\Batch;
class BatchStarted
{
/**
* Create a new event instance.
*
* @param \Illuminate\Bus\Batch $batch The batch instance.
*/
public function __construct(
public Batch $batch,
) {
}
}
@@ -94,6 +94,8 @@ class PendingBatch
*
* @param object|array $job
* @return void
*
* @throws \RuntimeException
*/
protected function ensureJobIsBatchable(object|array $job): void
{
@@ -102,7 +104,7 @@ class PendingBatch
return;
}
if (! (static::$batchableClasses[$job::class] ?? false) && ! in_array(Batchable::class, class_uses_recursive($job))) {
if (! (static::$batchableClasses[$job::class] ?? false) && ! isset(class_uses_recursive($job)[Batchable::class])) {
static::$batchableClasses[$job::class] = false;
throw new RuntimeException(sprintf('Attempted to batch job [%s], but it does not use the Batchable trait.', $job::class));
@@ -42,6 +42,13 @@ trait Queueable
*/
public $deduplicator;
/**
* The lock owner token for debounce supersession checks.
*
* @var string
*/
public $debounceOwner = '';
/**
* The number of seconds before the job should be made available.
*
+7 -3
View File
@@ -3,9 +3,13 @@
namespace Illuminate\Bus;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Queue\Attributes\ReadsQueueAttributes;
use Illuminate\Queue\Attributes\UniqueFor;
class UniqueLock
{
use ReadsQueueAttributes;
/**
* The cache repository implementation.
*
@@ -33,13 +37,13 @@ class UniqueLock
{
$uniqueFor = method_exists($job, 'uniqueFor')
? $job->uniqueFor()
: ($job->uniqueFor ?? 0);
: ($this->getAttributeValue($job, UniqueFor::class, 'uniqueFor') ?? 0);
$cache = method_exists($job, 'uniqueVia')
? ($job->uniqueVia() ?? $this->cache)
: $this->cache;
return (bool) $cache->lock($this->getKey($job), $uniqueFor)->get();
return (bool) $cache->lock(self::getKey($job), $uniqueFor)->get();
}
/**
@@ -54,7 +58,7 @@ class UniqueLock
? ($job->uniqueVia() ?? $this->cache)
: $this->cache;
$cache->lock($this->getKey($job))->forceRelease();
$cache->lock(self::getKey($job))->forceRelease();
}
/**
+20 -20
View File
@@ -2,39 +2,39 @@
"name": "illuminate/bus",
"description": "The Illuminate Bus package.",
"license": "MIT",
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"require": {
"php": "^8.2",
"illuminate/collections": "^12.0",
"illuminate/contracts": "^12.0",
"illuminate/pipeline": "^12.0",
"illuminate/support": "^12.0"
"homepage": "https://laravel.com",
"support": {
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"require": {
"php": "^8.3",
"illuminate/collections": "^13.0",
"illuminate/contracts": "^13.0",
"illuminate/pipeline": "^13.0",
"illuminate/support": "^13.0"
},
"suggest": {
"illuminate/queue": "Required to use closures when chaining jobs (^13.0)."
},
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Illuminate\\Bus\\": ""
}
},
"extra": {
"branch-alias": {
"dev-master": "12.x-dev"
}
},
"suggest": {
"illuminate/queue": "Required to use closures when chaining jobs (^12.0)."
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev"
"extra": {
"branch-alias": {
"dev-master": "13.0.x-dev"
}
}
}
@@ -92,6 +92,24 @@ class ApcStore extends TaggableStore
return $this->put($key, $value, 0);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
$value = $this->apc->get($key = $this->getPrefix().$key);
if (is_null($value)) {
return false;
}
return $this->apc->put($key, $value, $seconds);
}
/**
* Remove an item from the cache.
*
@@ -2,11 +2,14 @@
namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\InteractsWithTime;
use RuntimeException;
class ArrayStore extends TaggableStore implements LockProvider
class ArrayStore extends TaggableStore implements CanFlushLocks, LockProvider
{
use InteractsWithTime, RetrievesMultipleKeys;
@@ -163,6 +166,28 @@ class ArrayStore extends TaggableStore implements LockProvider
return $this->put($key, $value, 0);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
$item = Arr::get($this->storage, $key = $this->getPrefix().$key, null);
if (is_null($item)) {
return false;
}
$item['expiresAt'] = $this->calculateExpiration($seconds);
$this->storage = array_merge($this->storage, [$key => $item]);
return true;
}
/**
* Remove an item from the cache.
*
@@ -192,6 +217,24 @@ class ArrayStore extends TaggableStore implements LockProvider
return true;
}
/**
* Remove all locks from the store.
*
* @return bool
*
* @throws \RuntimeException
*/
public function flushLocks(): bool
{
if (! $this->hasSeparateLockStore()) {
throw new RuntimeException('Flushing locks is only supported when the lock store is separate from the cache store.');
}
$this->locks = [];
return true;
}
/**
* Get the cache key prefix.
*
@@ -249,6 +292,16 @@ class ArrayStore extends TaggableStore implements LockProvider
return $this->lock($name, 0, $owner);
}
/**
* Determine if the lock store is separate from the cache store.
*
* @return bool
*/
public function hasSeparateLockStore(): bool
{
return true;
}
/**
* Unserialize the given value.
*
@@ -8,9 +8,14 @@ use Illuminate\Contracts\Cache\Factory as FactoryContract;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Support\Arr;
use Illuminate\Support\RebindsCallbacksToSelf;
use InvalidArgumentException;
use Mockery;
use Mockery\LegacyMockInterface;
use ReflectionException;
use RuntimeException;
use function Illuminate\Support\enum_value;
/**
* @mixin \Illuminate\Cache\Repository
@@ -18,6 +23,8 @@ use Mockery\LegacyMockInterface;
*/
class CacheManager implements FactoryContract
{
use RebindsCallbacksToSelf;
/**
* The application instance.
*
@@ -52,12 +59,12 @@ class CacheManager implements FactoryContract
/**
* Get a cache store instance by name, wrapped in a repository.
*
* @param string|null $name
* @param \UnitEnum|string|null $name
* @return \Illuminate\Contracts\Cache\Repository
*/
public function store($name = null)
{
$name = $name ?? $this->getDefaultDriver();
$name = enum_value($name) ?? $this->getDefaultDriver();
return $this->stores[$name] ??= $this->resolve($name);
}
@@ -65,7 +72,7 @@ class CacheManager implements FactoryContract
/**
* Get a cache driver instance.
*
* @param string|null $driver
* @param \UnitEnum|string|null $driver
* @return \Illuminate\Contracts\Cache\Repository
*/
public function driver($driver = null)
@@ -76,12 +83,12 @@ class CacheManager implements FactoryContract
/**
* Get a memoized cache driver instance.
*
* @param string|null $driver
* @param \UnitEnum|string|null $driver
* @return \Illuminate\Contracts\Cache\Repository
*/
public function memo($driver = null)
{
$driver = $driver ?? $this->getDefaultDriver();
$driver = enum_value($driver) ?? $this->getDefaultDriver();
$bindingKey = "cache.__memoized:{$driver}";
@@ -295,6 +302,22 @@ class CacheManager implements FactoryContract
);
}
/**
* Create an instance of the storage cache driver.
*
* @param array $config
* @return \Illuminate\Cache\Repository
*/
protected function createStorageDriver(array $config)
{
return $this->repository(new StorageStore(
$this->app['filesystem']->disk($config['disk'] ?? null),
$config['path'] ?? '',
$this->getPrefix($config),
$this->getSerializableClasses($config),
), $config);
}
/**
* Create an instance of the Memcached cache driver.
*
@@ -476,18 +499,18 @@ class CacheManager implements FactoryContract
/**
* Set the default cache driver name.
*
* @param string $name
* @param \UnitEnum|string $name
* @return void
*/
public function setDefaultDriver($name)
{
$this->app['config']['cache.default'] = $name;
$this->app['config']['cache.default'] = enum_value($name);
}
/**
* Unset the given driver instances.
*
* @param array|string|null $name
* @param array|\UnitEnum|string|null $name
* @return $this
*/
public function forgetDriver($name = null)
@@ -495,6 +518,8 @@ class CacheManager implements FactoryContract
$name ??= $this->getDefaultDriver();
foreach ((array) $name as $cacheName) {
$cacheName = enum_value($cacheName);
if (isset($this->stores[$cacheName])) {
unset($this->stores[$cacheName]);
}
@@ -506,12 +531,12 @@ class CacheManager implements FactoryContract
/**
* Disconnect the given driver and remove from local cache.
*
* @param string|null $name
* @param \UnitEnum|string|null $name
* @return void
*/
public function purge($name = null)
{
$name ??= $this->getDefaultDriver();
$name = enum_value($name) ?? $this->getDefaultDriver();
unset($this->stores[$name]);
}
@@ -528,7 +553,13 @@ class CacheManager implements FactoryContract
*/
public function extend($driver, Closure $callback)
{
$this->customCreators[$driver] = $callback->bindTo($this, $this);
try {
$callback = $this->bindCallbackToSelf($callback) ?? throw new RuntimeException('Unable to bind custom driver callback');
} catch (ReflectionException $e) {
throw new RuntimeException('Unable to bind custom driver callback', previous: $e);
}
$this->customCreators[$driver] = $callback;
return $this;
}
@@ -546,6 +577,17 @@ class CacheManager implements FactoryContract
return $this;
}
/**
* Register a callback to be invoked when an unserializable class is encountered.
*
* @param callable|null $callback
* @return void
*/
public function handleUnserializableClassUsing(?callable $callback): void
{
Repository::handleUnserializableClassUsing($callback);
}
/**
* Dynamically call the default driver instance.
*
@@ -2,8 +2,10 @@
namespace Illuminate\Cache\Console;
use BadMethodCallException;
use Illuminate\Cache\CacheManager;
use Illuminate\Console\Command;
use Illuminate\Console\Prohibitable;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
@@ -12,6 +14,8 @@ use Symfony\Component\Console\Input\InputOption;
#[AsCommand(name: 'cache:clear')]
class ClearCommand extends Command
{
use Prohibitable;
/**
* The console command name.
*
@@ -61,6 +65,14 @@ class ClearCommand extends Command
*/
public function handle()
{
if ($this->isProhibited()) {
return self::FAILURE;
}
if ($this->option('locks')) {
return $this->clearLocks();
}
$this->laravel['events']->dispatch(
'cache:clearing', [$this->argument('store'), $this->tags()]
);
@@ -84,6 +96,38 @@ class ClearCommand extends Command
return self::SUCCESS;
}
/**
* Clear all locks from the cache store.
*
* @return int
*/
protected function clearLocks()
{
if (! empty($this->tags())) {
$this->components->error('Cache tags cannot be used when clearing locks.');
return self::FAILURE;
}
try {
$successful = $this->cache()->flushLocks();
} catch (BadMethodCallException) {
$this->components->error('This cache store does not support clearing locks.');
return self::FAILURE;
}
if (! $successful) {
$this->components->error('Failed to clear cache locks. Make sure you have the appropriate permissions.');
return self::FAILURE;
}
$this->components->info('Application cache locks cleared successfully.');
return self::SUCCESS;
}
/**
* Flush the real-time facades stored in the cache directory.
*
@@ -145,6 +189,7 @@ class ClearCommand extends Command
{
return [
['tags', null, InputOption::VALUE_OPTIONAL, 'The cache tags you would like to clear', null],
['locks', null, InputOption::VALUE_NONE, 'Only clear cache locks'],
];
}
}
@@ -137,24 +137,18 @@ class DatabaseLock extends Lock
*/
public function release()
{
if ($this->isOwnedByCurrentProcess()) {
try {
$this->connection->table($this->table)
->where('key', $this->name)
->where('owner', $this->owner)
->delete();
try {
return $this->connection->table($this->table)
->where('key', $this->name)
->where('owner', $this->owner)
->delete() > 0;
} catch (Throwable $e) {
if ($this->causedByConcurrencyError($e)) {
return true;
} catch (Throwable $e) {
if ($this->causedByConcurrencyError($e)) {
return true;
}
throw $e;
}
}
return false;
throw $e;
}
}
/**
@@ -196,7 +190,10 @@ class DatabaseLock extends Lock
*/
protected function getCurrentOwner()
{
return $this->connection->table($this->table)->where('key', $this->name)->first()?->owner;
return $this->connection->table($this->table)
->where('key', $this->name)
->where('expiration', '>', $this->currentTime())
->first()?->owner;
}
/**
@@ -3,6 +3,7 @@
namespace Illuminate\Cache;
use Closure;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Database\ConnectionInterface;
@@ -14,8 +15,9 @@ use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Support\Str;
use RuntimeException;
class DatabaseStore implements LockProvider, Store
class DatabaseStore implements CanFlushLocks, LockProvider, Store
{
use InteractsWithTime;
@@ -124,7 +126,7 @@ class DatabaseStore implements LockProvider, Store
*/
public function many(array $keys)
{
if (count($keys) === 0) {
if ($keys === []) {
return [];
}
@@ -220,11 +222,11 @@ class DatabaseStore implements LockProvider, Store
$expiration = $this->getTime() + $seconds;
if (! $this->getConnection() instanceof SqlServerConnection) {
return $this->table()->insertOrIgnore(compact('key', 'value', 'expiration')) > 0;
return $this->table()->insertOrIgnore(['key' => $key, 'value' => $value, 'expiration' => $expiration]) > 0;
}
try {
return $this->table()->insert(compact('key', 'value', 'expiration'));
return $this->table()->insert(['key' => $key, 'value' => $value, 'expiration' => $expiration]);
} catch (QueryException) {
// ...
}
@@ -362,6 +364,21 @@ class DatabaseStore implements LockProvider, Store
return $this->lock($name, 0, $owner);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
return (bool) $this->table()
->where('key', '=', $this->getPrefix().$key)
->where('expiration', '>', $now = $this->getTime())
->update(['expiration' => $now + $seconds]);
}
/**
* Remove an item from the cache.
*
@@ -394,7 +411,7 @@ class DatabaseStore implements LockProvider, Store
{
$this->table()->whereIn('key', (new Collection($keys))->flatMap(fn ($key) => [
$this->prefix.$key,
"{$this->prefix}illuminate:cache:flexible:created:{$key}",
$this->prefix.Repository::FLEXIBLE_CREATED_KEY_PREFIX.$key,
])->all())->delete();
return true;
@@ -412,10 +429,10 @@ class DatabaseStore implements LockProvider, Store
$this->table()
->whereIn('key', (new Collection($keys))->flatMap(fn ($key) => $prefixed ? [
$key,
$this->prefix.'illuminate:cache:flexible:created:'.Str::chopStart($key, $this->prefix),
$this->prefix.Repository::FLEXIBLE_CREATED_KEY_PREFIX.Str::chopStart($key, $this->prefix),
] : [
"{$this->prefix}{$key}",
"{$this->prefix}illuminate:cache:flexible:created:{$key}",
$this->prefix.Repository::FLEXIBLE_CREATED_KEY_PREFIX.$key,
])->all())
->where('expiration', '<=', $this->getTime())
->delete();
@@ -435,6 +452,24 @@ class DatabaseStore implements LockProvider, Store
return true;
}
/**
* Remove all locks from the store.
*
* @return bool
*
* @throws \RuntimeException
*/
public function flushLocks(): bool
{
if (! $this->hasSeparateLockStore()) {
throw new RuntimeException('Flushing locks is only supported when the lock store is separate from the cache store.');
}
$this->lockTable()->delete();
return true;
}
/**
* Get a query builder for the cache table.
*
@@ -445,6 +480,16 @@ class DatabaseStore implements LockProvider, Store
return $this->connection->table($this->table);
}
/**
* Get a query builder for the cache locks table.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function lockTable()
{
return $this->lockConnection->table($this->lockTable);
}
/**
* Get the underlying database connection.
*
@@ -551,4 +596,14 @@ class DatabaseStore implements LockProvider, Store
return unserialize($value);
}
/**
* Determine if the lock store is separate from the cache store.
*
* @return bool
*/
public function hasSeparateLockStore(): bool
{
return $this->lockTable !== $this->table;
}
}
@@ -100,7 +100,7 @@ class DynamoDbStore implements LockProvider, Store
*/
public function many(array $keys)
{
if (count($keys) === 0) {
if ($keys === []) {
return [];
}
@@ -192,7 +192,7 @@ class DynamoDbStore implements LockProvider, Store
*/
public function putMany(array $values, $seconds)
{
if (count($values) === 0) {
if ($values === []) {
return true;
}
@@ -230,6 +230,8 @@ class DynamoDbStore implements LockProvider, Store
* @param mixed $value
* @param int $seconds
* @return bool
*
* @throws \Aws\DynamoDb\Exception\DynamoDbException
*/
public function add($key, $value, $seconds)
{
@@ -448,6 +450,43 @@ class DynamoDbStore implements LockProvider, Store
}
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*
* @throws DynamoDbException
*/
public function touch($key, $seconds)
{
try {
$this->dynamo->updateItem([
'TableName' => $this->table,
'Key' => [$this->keyAttribute => ['S' => $this->getPrefix().$key]],
'UpdateExpression' => 'SET #expiry = :expiry',
'ConditionExpression' => 'attribute_exists(#key) AND #expiry > :now',
'ExpressionAttributeNames' => [
'#key' => $this->keyAttribute,
'#expiry' => $this->expirationAttribute,
],
'ExpressionAttributeValues' => [
':expiry' => ['N' => (string) $this->toTimestamp($seconds)],
':now' => ['N' => (string) $this->currentTime()],
],
]);
} catch (DynamoDbException $e) {
if (str_contains($e->getMessage(), 'ConditionalCheckFailed')) {
return false;
}
throw $e;
}
return true;
}
/**
* Remove an item from the cache.
*
@@ -0,0 +1,23 @@
<?php
namespace Illuminate\Cache\Events;
class CacheLocksFlushFailed
{
/**
* The name of the cache store.
*
* @var string|null
*/
public ?string $storeName;
/**
* Create a new event instance.
*
* @param string|null $storeName
*/
public function __construct(?string $storeName)
{
$this->storeName = $storeName;
}
}
@@ -0,0 +1,23 @@
<?php
namespace Illuminate\Cache\Events;
class CacheLocksFlushed
{
/**
* The name of the cache store.
*
* @var string|null
*/
public ?string $storeName;
/**
* Create a new event instance.
*
* @param string|null $storeName
*/
public function __construct(?string $storeName)
{
$this->storeName = $storeName;
}
}
@@ -0,0 +1,23 @@
<?php
namespace Illuminate\Cache\Events;
class CacheLocksFlushing
{
/**
* The name of the cache store.
*
* @var string|null
*/
public ?string $storeName;
/**
* Create a new event instance.
*
* @param string|null $storeName
*/
public function __construct(?string $storeName)
{
$this->storeName = $storeName;
}
}
@@ -3,12 +3,13 @@
namespace Illuminate\Cache;
use Illuminate\Cache\Events\CacheFailedOver;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Events\Dispatcher;
use RuntimeException;
use Throwable;
class FailoverStore extends TaggableStore implements LockProvider
class FailoverStore extends TaggableStore implements CanFlushLocks, LockProvider
{
/**
* The caches which failed on the last action.
@@ -150,6 +151,18 @@ class FailoverStore extends TaggableStore implements LockProvider
return $this->attemptOnAllStores(__FUNCTION__, func_get_args());
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
return $this->attemptOnAllStores(__FUNCTION__, func_get_args());
}
/**
* Remove an item from the cache.
*
@@ -187,6 +200,38 @@ class FailoverStore extends TaggableStore implements LockProvider
}
}
/**
* Flush all of the stale locks from every backing store.
*
* @return bool
*/
public function flushLocks(): bool
{
$result = true;
foreach ($this->stores as $store) {
$underlyingStore = $this->store($store)->getStore();
if ($underlyingStore instanceof CanFlushLocks) {
if (! $underlyingStore->flushLocks()) {
$result = false;
}
}
}
return $result;
}
/**
* Determine if the lock store is separate from the cache store.
*
* @return bool
*/
public function hasSeparateLockStore(): bool
{
return true;
}
/**
* Get the cache key prefix.
*
+64 -6
View File
@@ -3,14 +3,16 @@
namespace Illuminate\Cache;
use Exception;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Contracts\Filesystem\LockTimeoutException;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Filesystem\LockableFile;
use Illuminate\Support\InteractsWithTime;
use RuntimeException;
class FileStore implements Store, LockProvider
class FileStore implements CanFlushLocks, LockProvider, Store
{
use InteractsWithTime, RetrievesMultipleKeys;
@@ -89,7 +91,7 @@ class FileStore implements Store, LockProvider
$this->ensureCacheDirectoryExists($path = $this->path($key));
$result = $this->files->put(
$path, $this->expiration($seconds).serialize($value), true
$path, str_pad((string) $this->expiration($seconds), 10, '0', STR_PAD_LEFT).serialize($value), true
);
if ($result !== false && $result > 0) {
@@ -127,7 +129,7 @@ class FileStore implements Store, LockProvider
if (empty($expire) || $this->currentTime() >= $expire) {
$file->truncate()
->write($this->expiration($seconds).serialize($value))
->write(str_pad((string) $this->expiration($seconds), 10, '0', STR_PAD_LEFT).serialize($value))
->close();
$this->ensurePermissionsAreCorrect($path);
@@ -279,7 +281,7 @@ class FileStore implements Store, LockProvider
$expire = substr($contents, 0, 10);
$currentOwner = unserialize(substr($contents, 10));
$currentOwner = $this->unserialize(substr($contents, 10));
if ($currentOwner !== $expectedOwner || $this->currentTime() >= $expire) {
$file->close();
@@ -296,6 +298,24 @@ class FileStore implements Store, LockProvider
return true;
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
$payload = $this->getPayload($this->getPrefix().$key);
if (is_null($payload['data'])) {
return false;
}
return $this->put($key, $payload['data'], $seconds);
}
/**
* Remove an item from the cache.
*
@@ -306,7 +326,7 @@ class FileStore implements Store, LockProvider
{
if ($this->files->exists($file = $this->path($key))) {
return tap($this->files->delete($file), function ($forgotten) use ($key) {
if ($forgotten && $this->files->exists($file = $this->path("illuminate:cache:flexible:created:{$key}"))) {
if ($forgotten && $this->files->exists($file = $this->path(Repository::FLEXIBLE_CREATED_KEY_PREFIX.$key))) {
$this->files->delete($file);
}
});
@@ -337,6 +357,34 @@ class FileStore implements Store, LockProvider
return true;
}
/**
* Remove all locks from the store.
*
* @return bool
*
* @throws \RuntimeException
*/
public function flushLocks(): bool
{
if (! $this->hasSeparateLockStore()) {
throw new RuntimeException('Flushing locks is only supported when the lock store is separate from the cache store.');
}
if (! $this->files->isDirectory($this->lockDirectory)) {
return false;
}
foreach ($this->files->directories($this->lockDirectory) as $lockDirectory) {
$deleted = $this->files->deleteDirectory($lockDirectory);
if (! $deleted || $this->files->exists($lockDirectory)) {
return false;
}
}
return true;
}
/**
* Retrieve an item and expiry time from the cache by key.
*
@@ -382,7 +430,7 @@ class FileStore implements Store, LockProvider
// operation that may be performed on this cache on a later operation.
$time = $expire - $this->currentTime();
return compact('data', 'time');
return ['data' => $data, 'time' => $time];
}
/**
@@ -491,4 +539,14 @@ class FileStore implements Store, LockProvider
{
return '';
}
/**
* Determine if the lock store is separate from the cache store.
*
* @return bool
*/
public function hasSeparateLockStore(): bool
{
return $this->lockDirectory !== null && $this->lockDirectory !== $this->directory;
}
}
+14 -3
View File
@@ -4,6 +4,7 @@ namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\Lock as LockContract;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Carbon;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Support\Sleep;
use Illuminate\Support\Str;
@@ -76,7 +77,7 @@ abstract class Lock implements LockContract
/**
* Returns the owner value written into the driver for this lock.
*
* @return string
* @return string|null
*/
abstract protected function getCurrentOwner();
@@ -112,12 +113,12 @@ abstract class Lock implements LockContract
*/
public function block($seconds, $callback = null)
{
$starting = ((int) now()->format('Uu')) / 1000;
$starting = ((int) Carbon::now()->format('Uu')) / 1000;
$milliseconds = $seconds * 1000;
while (! $this->acquire()) {
$now = ((int) now()->format('Uu')) / 1000;
$now = ((int) Carbon::now()->format('Uu')) / 1000;
if (($now + $this->sleepMilliseconds - $milliseconds) >= $starting) {
throw new LockTimeoutException;
@@ -158,6 +159,16 @@ abstract class Lock implements LockContract
return $this->owner;
}
/**
* Determine if the lock is currently held by any process.
*
* @return bool
*/
public function isLocked(): bool
{
return $this->getCurrentOwner() !== null;
}
/**
* Determines whether this lock is allowed to release the lock in the driver.
*
@@ -51,7 +51,7 @@ class MemcachedConnector
$this->setCredentials($memcached, $credentials);
}
if (count($options)) {
if ($options !== []) {
$memcached->setOptions($options);
}
@@ -202,6 +202,18 @@ class MemcachedStore extends TaggableStore implements LockProvider
return $this->lock($name, 0, $owner);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
return $this->memcached->touch($this->getPrefix().$key, $this->calculateExpiration($seconds));
}
/**
* Remove an item from the cache.
*
@@ -3,10 +3,11 @@
namespace Illuminate\Cache;
use BadMethodCallException;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\Store;
class MemoizedStore implements LockProvider, Store
class MemoizedStore implements CanFlushLocks, LockProvider, Store
{
/**
* The memoized cache values.
@@ -66,7 +67,7 @@ class MemoizedStore implements LockProvider, Store
}
}
if (count($missing) > 0) {
if ($missing !== []) {
$retrieved = tap($this->repository->many($missing), function ($values) {
foreach ($values as $key => $value) {
$this->cache[$this->prefix($key)] = $value;
@@ -105,7 +106,6 @@ class MemoizedStore implements LockProvider, Store
/**
* Store multiple items in the cache for a given number of seconds.
*
* @param array $values
* @param int $seconds
* @return bool
*/
@@ -167,6 +167,8 @@ class MemoizedStore implements LockProvider, Store
* @param int $seconds
* @param string|null $owner
* @return \Illuminate\Contracts\Cache\Lock
*
* @throws \BadMethodCallException
*/
public function lock($name, $seconds = 0, $owner = null)
{
@@ -183,6 +185,8 @@ class MemoizedStore implements LockProvider, Store
* @param string $name
* @param string $owner
* @return \Illuminate\Contracts\Cache\Lock
*
* @throws \BadMethodCallException
*/
public function restoreLock($name, $owner)
{
@@ -193,6 +197,46 @@ class MemoizedStore implements LockProvider, Store
return $this->repository->getStore()->restoreLock(...func_get_args());
}
/**
* Flush all locks managed by the store.
*
* @throws \BadMethodCallException
*/
public function flushLocks(): bool
{
$store = $this->repository->getStore();
if (! $store instanceof CanFlushLocks) {
throw new BadMethodCallException('This cache store does not support flushing locks.');
}
return $store->flushLocks();
}
/**
* Determine if the lock store is separate from the cache store.
*/
public function hasSeparateLockStore(): bool
{
$store = $this->repository->getStore();
return $store instanceof CanFlushLocks && $store->hasSeparateLockStore();
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
unset($this->cache[$this->prefix($key)]);
return $this->repository->touch($key, $seconds);
}
/**
* Remove an item from the cache.
*
@@ -45,6 +45,16 @@ class NoLock extends Lock
//
}
/**
* Determine if the lock is currently held by any process.
*
* @return bool
*/
public function isLocked(): bool
{
return false;
}
/**
* Returns the owner value written into the driver for this lock.
*
+30 -1
View File
@@ -2,9 +2,10 @@
namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
class NullStore extends TaggableStore implements LockProvider
class NullStore extends TaggableStore implements CanFlushLocks, LockProvider
{
use RetrievesMultipleKeys;
@@ -93,6 +94,34 @@ class NullStore extends TaggableStore implements LockProvider
return $this->lock($name, 0, $owner);
}
/**
* Flush all locks managed by the store.
*/
public function flushLocks(): bool
{
return true;
}
/**
* Determine if the lock store is separate from the cache store.
*/
public function hasSeparateLockStore(): bool
{
return false;
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
return false;
}
/**
* Remove an item from the cache.
*
@@ -289,8 +289,10 @@ class RateLimiter
/**
* Execute the given callback without serialization or compression when applicable.
*
* @param callable $callback
* @return mixed
* @template TReturn
*
* @param (callable(): TReturn) $callback
* @return TReturn
*/
protected function withoutSerializationOrCompression(callable $callback)
{
@@ -116,7 +116,7 @@ class Limit
/**
* Create a new unlimited rate limit.
*
* @return static
* @return \Illuminate\Cache\RateLimiting\Unlimited
*/
public static function none()
{
@@ -78,7 +78,7 @@ class RedisLock extends Lock
/**
* Returns the owner value written into the driver for this lock.
*
* @return string
* @return string|null
*/
protected function getCurrentOwner()
{
@@ -2,6 +2,7 @@
namespace Illuminate\Cache;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Redis\Factory as Redis;
use Illuminate\Redis\Connections\PhpRedisClusterConnection;
@@ -10,8 +11,9 @@ use Illuminate\Redis\Connections\PredisClusterConnection;
use Illuminate\Redis\Connections\PredisConnection;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str;
use RuntimeException;
class RedisStore extends TaggableStore implements LockProvider
class RedisStore extends TaggableStore implements CanFlushLocks, LockProvider
{
use RetrievesMultipleKeys {
many as private manyAlias;
@@ -94,7 +96,7 @@ class RedisStore extends TaggableStore implements LockProvider
*/
public function many(array $keys)
{
if (count($keys) === 0) {
if ($keys === []) {
return [];
}
@@ -263,6 +265,18 @@ class RedisStore extends TaggableStore implements LockProvider
return $this->lock($name, 0, $owner);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
return (bool) $this->connection()->expire($this->getPrefix().$key, (int) max(1, $seconds));
}
/**
* Remove an item from the cache.
*
@@ -286,6 +300,24 @@ class RedisStore extends TaggableStore implements LockProvider
return true;
}
/**
* Remove all locks from the store.
*
* @return bool
*
* @throws \RuntimeException
*/
public function flushLocks(): bool
{
if (! $this->hasSeparateLockStore()) {
throw new RuntimeException('Flushing locks is only supported when the lock store is separate from the cache store.');
}
$this->lockConnection()->flushdb();
return true;
}
/**
* Remove all expired tag set entries.
*
@@ -536,4 +568,14 @@ class RedisStore extends TaggableStore implements LockProvider
return $this->unserialize($value);
}
/**
* Determine if the lock store is separate from the cache store.
*
* @return bool
*/
public function hasSeparateLockStore(): bool
{
return $this->lockConnection !== $this->connection;
}
}
@@ -66,7 +66,7 @@ class RedisTagSet extends TagSet
$entries = array_unique(array_keys($entries));
if (count($entries) === 0) {
if ($entries === []) {
continue;
}
@@ -9,18 +9,22 @@ use Illuminate\Redis\Connections\PhpRedisConnection;
use Illuminate\Redis\Connections\PredisClusterConnection;
use Illuminate\Redis\Connections\PredisConnection;
use function Illuminate\Support\enum_value;
class RedisTaggedCache extends TaggedCache
{
/**
* Store an item in the cache if the key does not exist.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @param \DateTimeInterface|\DateInterval|int|null $ttl
* @return bool
*/
public function add($key, $value, $ttl = null)
{
$key = enum_value($key);
$seconds = null;
if ($ttl !== null) {
@@ -40,13 +44,15 @@ class RedisTaggedCache extends TaggedCache
/**
* Store an item in the cache.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @param \DateTimeInterface|\DateInterval|int|null $ttl
* @return bool
*/
public function put($key, $value, $ttl = null)
{
$key = enum_value($key);
if (is_null($ttl)) {
return $this->forever($key, $value);
}
@@ -66,12 +72,14 @@ class RedisTaggedCache extends TaggedCache
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1)
{
$key = enum_value($key);
$this->tags->addEntry($this->itemKey($key), updateWhen: 'NX');
return parent::increment($key, $value);
@@ -80,7 +88,7 @@ class RedisTaggedCache extends TaggedCache
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @return int|bool
*/
@@ -94,12 +102,14 @@ class RedisTaggedCache extends TaggedCache
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @return bool
*/
public function forever($key, $value)
{
$key = enum_value($key);
$this->tags->addEntry($this->itemKey($key));
return parent::forever($key, $value);
+140 -49
View File
@@ -10,6 +10,9 @@ use Illuminate\Cache\Events\CacheFlushed;
use Illuminate\Cache\Events\CacheFlushFailed;
use Illuminate\Cache\Events\CacheFlushing;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Cache\Events\CacheLocksFlushed;
use Illuminate\Cache\Events\CacheLocksFlushFailed;
use Illuminate\Cache\Events\CacheLocksFlushing;
use Illuminate\Cache\Events\CacheMissed;
use Illuminate\Cache\Events\ForgettingKey;
use Illuminate\Cache\Events\KeyForgetFailed;
@@ -21,6 +24,7 @@ use Illuminate\Cache\Events\RetrievingManyKeys;
use Illuminate\Cache\Events\WritingKey;
use Illuminate\Cache\Events\WritingManyKeys;
use Illuminate\Cache\Limiters\ConcurrencyLimiterBuilder;
use Illuminate\Contracts\Cache\CanFlushLocks;
use Illuminate\Contracts\Cache\LockProvider;
use Illuminate\Contracts\Cache\Repository as CacheContract;
use Illuminate\Contracts\Cache\Store;
@@ -43,6 +47,13 @@ class Repository implements ArrayAccess, CacheContract
__call as macroCall;
}
/**
* The cache key prefix used to track when a flexible cache value was last refreshed.
*
* @var string
*/
const FLEXIBLE_CREATED_KEY_PREFIX = 'illuminate:cache:flexible:created:';
/**
* The cache store implementation.
*
@@ -72,10 +83,14 @@ class Repository implements ArrayAccess, CacheContract
protected $config = [];
/**
* Create a new cache repository instance.
* The callback to invoke when an unserializable class is encountered.
*
* @param \Illuminate\Contracts\Cache\Store $store
* @param array $config
* @var callable|null
*/
protected static $unserializableClassHandler;
/**
* Create a new cache repository instance.
*/
public function __construct(Store $store, array $config = [])
{
@@ -87,7 +102,6 @@ class Repository implements ArrayAccess, CacheContract
* Determine if an item exists in the cache.
*
* @param \UnitEnum|array|string $key
* @return bool
*/
public function has($key): bool
{
@@ -110,7 +124,6 @@ class Repository implements ArrayAccess, CacheContract
*
* @param \UnitEnum|array|string $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null): mixed
{
@@ -132,6 +145,8 @@ class Repository implements ArrayAccess, CacheContract
$value = value($default);
} else {
$value = $this->handleIncompleteClass($key, $value);
$this->event(new CacheHit($this->getName(), $key, $value));
}
@@ -143,7 +158,6 @@ class Repository implements ArrayAccess, CacheContract
*
* Items not found in the cache will have a null value.
*
* @param array $keys
* @return array
*/
public function many(array $keys)
@@ -163,8 +177,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* {@inheritdoc}
*
* @return iterable
*/
public function getMultiple($keys, $default = null): iterable
{
@@ -199,6 +211,8 @@ class Repository implements ArrayAccess, CacheContract
// If we found a valid value we will fire the "hit" event and return the value
// back from this function. The "hit" event gives developers an opportunity
// to listen for every possible cache "hit" throughout this applications.
$value = $this->handleIncompleteClass($key, $value);
$this->event(new CacheHit($this->getName(), $key, $value));
return $value;
@@ -223,7 +237,6 @@ class Repository implements ArrayAccess, CacheContract
*
* @param \UnitEnum|string $key
* @param (\Closure():(string|null))|string|null $default
* @return string
*
* @throws \InvalidArgumentException
*/
@@ -245,7 +258,6 @@ class Repository implements ArrayAccess, CacheContract
*
* @param \UnitEnum|string $key
* @param (\Closure():(int|null))|int|null $default
* @return int
*
* @throws \InvalidArgumentException
*/
@@ -271,7 +283,6 @@ class Repository implements ArrayAccess, CacheContract
*
* @param \UnitEnum|string $key
* @param (\Closure():(float|null))|float|null $default
* @return float
*
* @throws \InvalidArgumentException
*/
@@ -297,7 +308,6 @@ class Repository implements ArrayAccess, CacheContract
*
* @param \UnitEnum|string $key
* @param (\Closure():(bool|null))|bool|null $default
* @return bool
*
* @throws \InvalidArgumentException
*/
@@ -381,7 +391,6 @@ class Repository implements ArrayAccess, CacheContract
* @param \UnitEnum|array|string $key
* @param mixed $value
* @param \DateTimeInterface|\DateInterval|int|null $ttl
* @return bool
*/
public function set($key, $value, $ttl = null): bool
{
@@ -391,7 +400,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* Store multiple items in the cache for a given number of seconds.
*
* @param array $values
* @param \DateTimeInterface|\DateInterval|int|null $ttl
* @return bool
*/
@@ -425,7 +433,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* Store multiple items in the cache indefinitely.
*
* @param array $values
* @return bool
*/
protected function putManyForever(array $values)
@@ -443,8 +450,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* {@inheritdoc}
*
* @return bool
*/
public function setMultiple($values, $ttl = null): bool
{
@@ -551,6 +556,21 @@ class Repository implements ArrayAccess, CacheContract
* @return TCacheValue
*/
public function remember($key, $ttl, Closure $callback)
{
return $this->rememberWithWarmth($key, $ttl, $callback)[0];
}
/**
* Get an item from the cache, or execute the given Closure and store the result.
*
* @template TCacheValue
*
* @param \UnitEnum|string $key
* @param \Closure|\DateTimeInterface|\DateInterval|int|null $ttl
* @param \Closure(): TCacheValue $callback
* @return array{TCacheValue, bool} The cached value and whether it was warm.
*/
public function rememberWithWarmth($key, $ttl, Closure $callback): array
{
$value = $this->get($key);
@@ -558,14 +578,14 @@ class Repository implements ArrayAccess, CacheContract
// not we will execute the given Closure and cache the result of that for a
// given number of seconds so it's available for all subsequent requests.
if (! is_null($value)) {
return $value;
return [$value, true];
}
$value = $callback();
$this->put($key, $value, value($ttl, $value));
return $value;
return [$value, false];
}
/**
@@ -625,13 +645,13 @@ class Repository implements ArrayAccess, CacheContract
[
$key => $value,
"illuminate:cache:flexible:created:{$key}" => $created,
] = $this->many([$key, "illuminate:cache:flexible:created:{$key}"]);
self::FLEXIBLE_CREATED_KEY_PREFIX.$key => $created,
] = $this->many([$key, self::FLEXIBLE_CREATED_KEY_PREFIX.$key]);
if (in_array(null, [$value, $created], true)) {
return tap(value($callback), fn ($value) => $this->putMany([
$key => $value,
"illuminate:cache:flexible:created:{$key}" => Carbon::now()->getTimestamp(),
self::FLEXIBLE_CREATED_KEY_PREFIX.$key => Carbon::now()->getTimestamp(),
], $ttl[1]));
}
@@ -641,26 +661,40 @@ class Repository implements ArrayAccess, CacheContract
$refresh = function () use ($key, $ttl, $callback, $lock, $created) {
$this->store->lock(
"illuminate:cache:flexible:lock:{$key}",
"illuminate:cache:flexible:lock:{$this->itemKey($key)}",
$lock['seconds'] ?? 0,
$lock['owner'] ?? null,
)->get(function () use ($key, $callback, $created, $ttl) {
if ($created !== $this->get("illuminate:cache:flexible:created:{$key}")) {
if ($created !== $this->get(self::FLEXIBLE_CREATED_KEY_PREFIX.$key)) {
return;
}
$this->putMany([
$key => value($callback),
"illuminate:cache:flexible:created:{$key}" => Carbon::now()->getTimestamp(),
self::FLEXIBLE_CREATED_KEY_PREFIX.$key => Carbon::now()->getTimestamp(),
], $ttl[1]);
});
};
defer($refresh, "illuminate:cache:flexible:{$key}", $alwaysDefer);
defer($refresh, "illuminate:cache:flexible:{$this->itemKey($key)}", $alwaysDefer);
return $value;
}
/**
* Set the expiration of a cached item.
*
* @param \UnitEnum|string $key
* @param \DateTimeInterface|\DateInterval|int $ttl
* @return bool
*/
public function touch($key, $ttl)
{
$key = enum_value($key);
return $this->store->touch($this->itemKey($key), $this->getSeconds($ttl));
}
/**
* Execute a callback while holding an atomic lock on a cache mutex to prevent overlapping calls.
*
@@ -720,7 +754,6 @@ class Repository implements ArrayAccess, CacheContract
* Remove an item from the cache.
*
* @param \UnitEnum|array|string $key
* @return bool
*/
public function delete($key): bool
{
@@ -729,8 +762,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* {@inheritdoc}
*
* @return bool
*/
public function deleteMultiple($keys): bool
{
@@ -747,8 +778,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(): bool
{
@@ -765,6 +794,32 @@ class Repository implements ArrayAccess, CacheContract
return $result;
}
/**
* Flush all locks from the cache store.
*
* @throws \BadMethodCallException
*/
public function flushLocks(): bool
{
$store = $this->getStore();
if (! $this->supportsFlushingLocks()) {
throw new BadMethodCallException('This cache store does not support flushing locks.');
}
$this->event(new CacheLocksFlushing($this->getName()));
$result = $store->flushLocks();
if ($result) {
$this->event(new CacheLocksFlushed($this->getName()));
} else {
$this->event(new CacheLocksFlushFailed($this->getName()));
}
return $result;
}
/**
* Begin executing a new tags operation if the store supports it.
*
@@ -801,6 +856,28 @@ class Repository implements ArrayAccess, CacheContract
return $key;
}
/**
* Handle a cache value that contains an incomplete class.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function handleIncompleteClass(string $key, mixed $value): mixed
{
if (! ($value instanceof \__PHP_Incomplete_Class)) {
return $value;
}
$class = ((array) $value)['__PHP_Incomplete_Class_Name'] ?? null;
if (isset(static::$unserializableClassHandler)) {
(static::$unserializableClassHandler)($key, $class);
}
return $value;
}
/**
* Calculate the number of seconds for the given TTL.
*
@@ -840,6 +917,14 @@ class Repository implements ArrayAccess, CacheContract
return method_exists($this->store, 'tags');
}
/**
* Determine if the current store supports flushing locks.
*/
public function supportsFlushingLocks(): bool
{
return $this->store instanceof CanFlushLocks;
}
/**
* Get the default cache time.
*
@@ -877,7 +962,7 @@ class Repository implements ArrayAccess, CacheContract
* Set the cache store implementation.
*
* @param \Illuminate\Contracts\Cache\Store $store
* @return static
* @return $this
*/
public function setStore($store)
{
@@ -910,7 +995,6 @@ class Repository implements ArrayAccess, CacheContract
/**
* Set the event dispatcher instance.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function setEventDispatcher(Dispatcher $events)
@@ -918,49 +1002,56 @@ class Repository implements ArrayAccess, CacheContract
$this->events = $events;
}
/**
* Register a callback to be invoked when an unserializable class is encountered.
*
* @param callable|null $callback
* @return void
*/
public static function handleUnserializableClassUsing(?callable $callback): void
{
static::$unserializableClassHandler = $callback;
}
/**
* Determine if a cached value exists.
*
* @param \UnitEnum|string $key
* @return bool
* @param \UnitEnum|string $offset
*/
public function offsetExists($key): bool
public function offsetExists($offset): bool
{
return $this->has($key);
return $this->has($offset);
}
/**
* Retrieve an item from the cache by key.
*
* @param \UnitEnum|string $key
* @return mixed
* @param \UnitEnum|string $offset
*/
public function offsetGet($key): mixed
public function offsetGet($offset): mixed
{
return $this->get($key);
return $this->get($offset);
}
/**
* Store an item in the cache for the default time.
*
* @param \UnitEnum|string $key
* @param \UnitEnum|string $offset
* @param mixed $value
* @return void
*/
public function offsetSet($key, $value): void
public function offsetSet($offset, $value): void
{
$this->put($key, $value, $this->default);
$this->put($offset, $value, $this->default);
}
/**
* Remove an item from the cache.
*
* @param \UnitEnum|string $key
* @return void
* @param \UnitEnum|string $offset
*/
public function offsetUnset($key): void
public function offsetUnset($offset): void
{
$this->forget($key);
$this->forget($offset);
}
/**
@@ -155,6 +155,26 @@ class SessionStore implements Store
return $this->put($key, $value, 0);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
$value = $this->get($key);
if (is_null($value)) {
return false;
}
$this->put($key, $value, $seconds);
return true;
}
/**
* Remove an item from the cache.
*
@@ -0,0 +1,322 @@
<?php
namespace Illuminate\Cache;
use Exception;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\InteractsWithTime;
class StorageStore implements Store
{
use InteractsWithTime, RetrievesMultipleKeys;
/**
* The filesystem disk instance.
*
* @var \Illuminate\Contracts\Filesystem\Filesystem
*/
protected $disk;
/**
* The storage path where cache files should be written.
*
* @var string
*/
protected $directory;
/**
* A string that should be prepended to keys.
*
* @var string
*/
protected $prefix;
/**
* The classes that should be allowed during unserialization.
*
* @var array|bool|null
*/
protected $serializableClasses;
/**
* Create a new storage cache store instance.
*
* @param \Illuminate\Contracts\Filesystem\Filesystem $disk
* @param string $directory
* @param string $prefix
* @param array|bool|null $serializableClasses
*/
public function __construct(Filesystem $disk, $directory = '', $prefix = '', $serializableClasses = null)
{
$this->disk = $disk;
$this->directory = trim($directory, '/');
$this->prefix = $prefix;
$this->serializableClasses = $serializableClasses;
}
/**
* Retrieve an item from the cache by key.
*
* @param string $key
* @return mixed
*/
public function get($key)
{
return $this->getPayload($key)['data'] ?? null;
}
/**
* Store an item in the cache for a given number of seconds.
*
* @param string $key
* @param mixed $value
* @param int $seconds
* @return bool
*/
public function put($key, $value, $seconds)
{
return $this->disk->put(
$this->path($key), $this->expiration($seconds).serialize($value)
);
}
/**
* Store an item in the cache if the key doesn't exist.
*
* @param string $key
* @param mixed $value
* @param int $seconds
* @return bool
*/
public function add($key, $value, $seconds)
{
if (! is_null($this->get($key))) {
return false;
}
return $this->put($key, $value, $seconds);
}
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int
*/
public function increment($key, $value = 1)
{
$raw = $this->getPayload($key);
return tap(((int) $raw['data']) + $value, function ($newValue) use ($key, $raw) {
$this->put($key, $newValue, $raw['time'] ?? 0);
});
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int
*/
public function decrement($key, $value = 1)
{
return $this->increment($key, $value * -1);
}
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return bool
*/
public function forever($key, $value)
{
return $this->put($key, $value, 0);
}
/**
* Adjust the expiration time of a cached item.
*
* @param string $key
* @param int $seconds
* @return bool
*/
public function touch($key, $seconds)
{
$payload = $this->getPayload($key);
if (is_null($payload['data'])) {
return false;
}
return $this->put($key, $payload['data'], $seconds);
}
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key)
{
$forgotten = $this->disk->delete($this->path($key));
if ($forgotten) {
$this->disk->delete($this->path(Repository::FLEXIBLE_CREATED_KEY_PREFIX.$key));
}
return $forgotten;
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
if ($this->directory === '') {
$files = $this->disk->allFiles();
return $files === [] || $this->disk->delete($files);
}
return $this->disk->deleteDirectory($this->directory)
&& $this->disk->makeDirectory($this->directory);
}
/**
* Retrieve an item and expiry time from the cache by key.
*
* @param string $key
* @return array
*/
protected function getPayload($key)
{
$path = $this->path($key);
try {
if (is_null($contents = $this->disk->get($path))) {
return $this->emptyPayload();
}
$expire = substr($contents, 0, 10);
} catch (Exception) {
return $this->emptyPayload();
}
if ($this->currentTime() >= $expire) {
$this->forget($key);
return $this->emptyPayload();
}
try {
$data = $this->unserialize(substr($contents, 10));
} catch (Exception) {
$this->forget($key);
return $this->emptyPayload();
}
$time = $expire - $this->currentTime();
return ['data' => $data, 'time' => $time];
}
/**
* Unserialize the given value.
*
* @param string $value
* @return mixed
*/
protected function unserialize($value)
{
if ($this->serializableClasses !== null) {
return unserialize($value, ['allowed_classes' => $this->serializableClasses]);
}
return unserialize($value);
}
/**
* Get a default empty payload for the cache.
*
* @return array
*/
protected function emptyPayload()
{
return ['data' => null, 'time' => null];
}
/**
* Get the full path for the given cache key.
*
* @param string $key
* @return string
*/
public function path($key)
{
$parts = array_slice(str_split($hash = sha1($this->prefix.$key), 2), 0, 2);
return trim($this->directory.'/'.implode('/', $parts).'/'.$hash, '/');
}
/**
* Get the expiration time based on the given seconds.
*
* @param int $seconds
* @return int
*/
protected function expiration($seconds)
{
$time = $this->availableAt($seconds);
return $seconds === 0 || $time > 9999999999 ? 9999999999 : $time;
}
/**
* Get the filesystem disk instance.
*
* @return \Illuminate\Contracts\Filesystem\Filesystem
*/
public function getDisk()
{
return $this->disk;
}
/**
* Get the working directory of the cache.
*
* @return string
*/
public function getDirectory()
{
return $this->directory;
}
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Set the cache key prefix.
*
* @param string $prefix
* @return void
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
}
@@ -6,6 +6,8 @@ use Illuminate\Cache\Events\CacheFlushed;
use Illuminate\Cache\Events\CacheFlushing;
use Illuminate\Contracts\Cache\Store;
use function Illuminate\Support\enum_value;
class TaggedCache extends Repository
{
use RetrievesMultipleKeys {
@@ -51,25 +53,25 @@ class TaggedCache extends Repository
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1)
{
return $this->store->increment($this->itemKey($key), $value);
return $this->store->increment($this->itemKey(enum_value($key)), $value);
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param \UnitEnum|string $key
* @param mixed $value
* @return int|bool
*/
public function decrement($key, $value = 1)
{
return $this->store->decrement($this->itemKey($key), $value);
return $this->store->decrement($this->itemKey(enum_value($key)), $value);
}
/**

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