Skip to content

Commit 0a49b23

Browse files
authored
[6.x] Fix originalIsEquivalent with floats (#33259)
* with test * styleci
1 parent d86d34b commit 0a49b23

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,6 +1178,11 @@ public function originalIsEquivalent($key, $current)
11781178
} elseif ($this->hasCast($key, ['object', 'collection'])) {
11791179
return $this->castAttribute($key, $current) ==
11801180
$this->castAttribute($key, $original);
1181+
} elseif ($this->hasCast($key, 'float')) {
1182+
return bccomp(
1183+
$this->castAttribute($key, $current),
1184+
$this->castAttribute($key, $original)
1185+
) === 0;
11811186
} elseif ($this->hasCast($key)) {
11821187
return $this->castAttribute($key, $current) ===
11831188
$this->castAttribute($key, $original);

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,23 @@ public function testCleanAttributes()
148148
$this->assertFalse($model->isClean(['foo', 'bar']));
149149
}
150150

151+
public function testCleanWhenFloatUpdateAttribute()
152+
{
153+
$original = -16.666347;
154+
$new = 20.1 - 36.766347;
155+
156+
// PHP isn't able to compare two floats using === reliably.
157+
// See warning here:
158+
// https://www.php.net/manual/en/language.types.float.php
159+
160+
$this->assertTrue($original !== $new);
161+
$this->assertTrue(bccomp($original, $new) === 0);
162+
163+
$model = new EloquentModelStub(['castedFloat' => $original]);
164+
$model->syncOriginal();
165+
$this->assertTrue($model->originalIsEquivalent('castedFloat', $new));
166+
}
167+
151168
public function testCalculatedAttributes()
152169
{
153170
$model = new EloquentModelStub;
@@ -1992,6 +2009,7 @@ class EloquentModelStub extends Model
19922009
protected $table = 'stub';
19932010
protected $guarded = [];
19942011
protected $morph_to_stub_type = EloquentModelSaveStub::class;
2012+
protected $casts = ['castedFloat' => 'float'];
19952013

19962014
public function getListItemsAttribute($value)
19972015
{

0 commit comments

Comments
 (0)