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

[6.x] Correct implementation of float casting comparison #33322

Merged
merged 1 commit into from
Jun 30, 2020
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
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