Skip to content

Commit

Permalink
Add a check before casting $value to string when firing events
Browse files Browse the repository at this point in the history
This was necessray because some types cannot be converted to string,
and it was throwing an exception when casting an Enum.

This work was done based on the PR opened by @patrocle on
#16
  • Loading branch information
DennyLoko committed Sep 29, 2023
1 parent 9847a70 commit 59ec28b
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/AttributeEvents.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private function fireAttributeEvents(): void
|| $expected === 'false' && $value === false
|| is_numeric($expected) && Str::contains($expected, '.') && $value === (float) $expected // float
|| is_numeric($expected) && $value === (int) $expected // int
|| (string) $value === $expected
|| $this->canBeCastedToString($value) && (string) $value === $expected
) {
$this->fireModelEvent($change, false);
}
Expand Down Expand Up @@ -137,4 +137,16 @@ private function hasAccessor(string $attribute): bool

return false;
}

private function canBeCastedToString($value): bool
{
if ($value instanceof \UnitEnum) {
return false;
}

return is_scalar($value)
|| is_null($value)
|| is_array($value)
|| is_object($value) && method_exists($value, '__toString');
}
}

0 comments on commit 59ec28b

Please sign in to comment.