Skip to content

Commit

Permalink
[6.x] Fix originalIsEquivalent with floats (#33259)
Browse files Browse the repository at this point in the history
* with test

* styleci
  • Loading branch information
CraigHarley authored Jun 18, 2020
1 parent d86d34b commit 0a49b23
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1178,6 +1178,11 @@ public function originalIsEquivalent($key, $current)
} elseif ($this->hasCast($key, ['object', 'collection'])) {
return $this->castAttribute($key, $current) ==
$this->castAttribute($key, $original);
} elseif ($this->hasCast($key, 'float')) {
return bccomp(
$this->castAttribute($key, $current),
$this->castAttribute($key, $original)
) === 0;
} elseif ($this->hasCast($key)) {
return $this->castAttribute($key, $current) ===
$this->castAttribute($key, $original);
Expand Down
18 changes: 18 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,23 @@ public function testCleanAttributes()
$this->assertFalse($model->isClean(['foo', 'bar']));
}

public function testCleanWhenFloatUpdateAttribute()
{
$original = -16.666347;
$new = 20.1 - 36.766347;

// PHP isn't able to compare two floats using === reliably.
// See warning here:
// https://www.php.net/manual/en/language.types.float.php

$this->assertTrue($original !== $new);
$this->assertTrue(bccomp($original, $new) === 0);

$model = new EloquentModelStub(['castedFloat' => $original]);
$model->syncOriginal();
$this->assertTrue($model->originalIsEquivalent('castedFloat', $new));
}

public function testCalculatedAttributes()
{
$model = new EloquentModelStub;
Expand Down Expand Up @@ -1992,6 +2009,7 @@ class EloquentModelStub extends Model
protected $table = 'stub';
protected $guarded = [];
protected $morph_to_stub_type = EloquentModelSaveStub::class;
protected $casts = ['castedFloat' => 'float'];

public function getListItemsAttribute($value)
{
Expand Down

0 comments on commit 0a49b23

Please sign in to comment.