Skip to content

Commit

Permalink
Correct implementation of float casting comparison (#33322)
Browse files Browse the repository at this point in the history
  • Loading branch information
GrahamCampbell authored Jun 30, 2020
1 parent 30441e8 commit 90892f9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
2 changes: 2 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,8 @@ public function originalIsEquivalent($key, $current)
} elseif ($this->hasCast($key, ['object', 'collection'])) {
return $this->castAttribute($key, $current) ==
$this->castAttribute($key, $original);
} elseif ($this->hasCast($key, ['real', 'float', 'double'])) {
return abs($this->castAttribute($key, $current) - $this->castAttribute($key, $original)) < PHP_FLOAT_EPSILON * 4;
} elseif ($this->hasCast($key)) {
return $this->castAttribute($key, $current) ===
$this->castAttribute($key, $original);
Expand Down
14 changes: 14 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,19 @@ public function testCleanAttributes()
$this->assertFalse($model->isClean(['foo', 'bar']));
}

public function testCleanWhenFloatUpdateAttribute()
{
// test is equivalent
$model = new EloquentModelStub(['castedFloat' => 8 - 6.4]);
$model->syncOriginal();
$this->assertTrue($model->originalIsEquivalent('castedFloat', 1.6));

// test is not equivalent
$model = new EloquentModelStub(['castedFloat' => 5.6]);
$model->syncOriginal();
$this->assertFalse($model->originalIsEquivalent('castedFloat', 5.5));
}

public function testCalculatedAttributes()
{
$model = new EloquentModelStub;
Expand Down Expand Up @@ -1992,6 +2005,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 90892f9

Please sign in to comment.