Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Fix decimal cast, again #45602

Merged
merged 3 commits into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"php": "^8.0.2",
"ext-mbstring": "*",
"ext-openssl": "*",
"brick/math": "^0.10.2",
"doctrine/inflector": "^2.0",
"dragonmantank/cron-expression": "^3.3.2",
"egulias/email-validator": "^3.2.1",
Expand Down
24 changes: 8 additions & 16 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
namespace Illuminate\Database\Eloquent\Concerns;

use BackedEnum;
use Brick\Math\BigDecimal;
use Brick\Math\Exception\MathException as BrickMathException;
use Brick\Math\RoundingMode;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use DateTimeImmutable;
Expand All @@ -23,6 +26,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Exceptions\MathException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
Expand All @@ -31,8 +35,6 @@
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use RuntimeException;
use TypeError;

trait HasAttributes
{
Expand Down Expand Up @@ -1322,21 +1324,11 @@ public function fromFloat($value)
*/
protected function asDecimal($value, $decimals)
{
if (extension_loaded('bcmath')) {
return bcadd($value, 0, $decimals);
}

if (! is_numeric($value)) {
throw new TypeError('$value must be numeric.');
}

if (is_string($value) && Str::contains($value, 'e', true)) {
throw new RuntimeException('The "decimal" model cast is unable to handle string based floats with exponents.');
try {
return (string) BigDecimal::of($value)->toScale($decimals, RoundingMode::HALF_UP);
} catch (BrickMathException $e) {
throw new MathException('Unable to cast value to a decimal.', previous: $e);
}

[$int, $fraction] = explode('.', $value) + [1 => ''];

return Str::of($int)->padLeft('1', '0').'.'.Str::of($fraction)->limit($decimals, '')->padRight($decimals, '0');
}

/**
Expand Down
10 changes: 10 additions & 0 deletions src/Illuminate/Support/Exceptions/MathException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Illuminate\Support\Exceptions;

use RuntimeException;

class MathException extends RuntimeException
{
//
}
101 changes: 69 additions & 32 deletions tests/Integration/Database/EloquentModelDecimalCastingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

namespace Illuminate\Tests\Integration\Database\EloquentModelDecimalCastingTest;

use Brick\Math\Exception\NumberFormatException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Exceptions\MathException;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
use TypeError;
use ValueError;

class EloquentModelDecimalCastingTest extends DatabaseTestCase
{
Expand All @@ -33,28 +33,9 @@ public function testItHandlesExponent()

$model->amount = 0.123456789e3;
$this->assertSame('123.45678900000000000000', $model->amount);
}

public function testItThrowsWhenPassingExponentAsString()
{
$model = new class extends Model
{
public $timestamps = false;

protected $casts = [
'amount' => 'decimal:20',
];
};
$model->amount = '0.1e3';

if (extension_loaded('bcmath')) {
$this->expectException(ValueError::class);
} else {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('The "decimal" model cast is unable to handle string based floats with exponents.'); // when bcmath is not available
}

$model->amount;
$model->amount = '0.123456789e3';
$this->assertSame('123.45678900000000000000', $model->amount);
}

public function testItHandlesIntegersWithUnderscores()
Expand All @@ -72,7 +53,7 @@ public function testItHandlesIntegersWithUnderscores()
$this->assertSame('1234.50', $model->amount);
}

public function testItThrowsOnNonNumericValues()
public function testItWrapsThrownExceptions()
{
$model = new class extends Model
{
Expand All @@ -84,13 +65,14 @@ public function testItThrowsOnNonNumericValues()
};
$model->amount = 'foo';

if (extension_loaded('bcmath')) {
$this->expectException(ValueError::class);
} else {
$this->expectException(TypeError::class);
try {
$model->amount;
$this->fail();
} catch (MathException $e) {
$this->assertSame('Unable to cast value to a decimal.', $e->getMessage());
$this->assertInstanceOf(NumberFormatException::class, $e->getPrevious());
$this->assertSame('The given value "foo" does not represent a valid number.', $e->getPrevious()->getMessage());
}

$model->amount;
}

public function testItHandlesMissingIntegers()
Expand Down Expand Up @@ -129,6 +111,21 @@ public function testItHandlesLargeNumbers()
$this->assertSame('89898989898989898989.00000000000000000000', $model->amount);
}

public function testItRounds()
{
$model = new class extends Model
{
public $timestamps = false;

protected $casts = [
'amount' => 'decimal:2',
];
};

$model->amount = '0.8989898989';
$this->assertSame('0.90', $model->amount);
}

public function testItTrimsLongValues()
{
$model = new class extends Model
Expand All @@ -141,7 +138,7 @@ public function testItTrimsLongValues()
};

$model->amount = '0.89898989898989898989898989898989898989898989';
$this->assertSame('0.89898989898989898989', $model->amount);
$this->assertSame('0.89898989898989898990', $model->amount);
}

public function testItDoesntRoundNumbers()
Expand All @@ -156,7 +153,7 @@ public function testItDoesntRoundNumbers()
};

$model->amount = '0.99';
$this->assertSame('0.9', $model->amount);
$this->assertSame('1.0', $model->amount);
}

public function testDecimalsAreCastable()
Expand All @@ -180,6 +177,46 @@ public function testDecimalsAreCastable()
$user->decimal_field_4 = '1234.1234';
$this->assertTrue($user->isDirty());
}

public function testRoundingDirection()
{
$model = new class extends Model
{
protected $casts = [
'amount' => 'decimal:2',
];
};

$model->amount = '0.999';
$this->assertSame('1.00', $model->amount);

$model->amount = '-0.999';
$this->assertSame('-1.00', $model->amount);

$model->amount = '0.554';
$this->assertSame('0.55', $model->amount);

$model->amount = '-0.554';
$this->assertSame('-0.55', $model->amount);

$model->amount = '0.555';
$this->assertSame('0.56', $model->amount);

$model->amount = '-0.555';
$this->assertSame('-0.56', $model->amount);

$model->amount = '0.005';
$this->assertSame('0.01', $model->amount);

$model->amount = '-0.005';
$this->assertSame('-0.01', $model->amount);

$model->amount = '0.8989898989';
$this->assertSame('0.90', $model->amount);

$model->amount = '-0.8989898989';
$this->assertSame('-0.90', $model->amount);
}
}

class TestModel1 extends Model
Expand Down