From 90892f99452693d3c76562359cbc683544ea00c8 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Tue, 30 Jun 2020 14:23:27 +0100 Subject: [PATCH] Correct implementation of float casting comparison (#33322) --- .../Database/Eloquent/Concerns/HasAttributes.php | 2 ++ tests/Database/DatabaseEloquentModelTest.php | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php index 986e8a72121f..b6c080a7f2e5 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php @@ -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); diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index b5c0bc8689f2..e918aa2ec35b 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -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; @@ -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) {