Skip to content

Commit

Permalink
Extract value check into shouldFireAttributeEvent method
Browse files Browse the repository at this point in the history
  • Loading branch information
jpkleemans committed Dec 14, 2023
1 parent de18768 commit d9478f9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 21 deletions.
53 changes: 32 additions & 21 deletions src/AttributeEvents.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,43 @@ private function fireAttributeEvents(): void
continue; // Not changed
}

if (
$expected === '*'
|| $value instanceof \UnitEnum && ($value->name === $expected)
|| $expected === 'true' && $value === true
|| $expected === 'false' && $value === false
|| is_numeric($expected) && Str::contains($expected, '.') && $value === (float) $expected // float
|| is_numeric($expected) && $value === (int) $expected // int
|| $this->canBeCastedToString($value) && (string) $value === $expected
) {
if ($this->shouldFireAttributeEvent($value, $expected)) {
$this->fireModelEvent($change, false);
}
}
}

private function shouldFireAttributeEvent($value, $expected)
{
if ($expected === '*') {
return true;
}

if ($value instanceof \UnitEnum) {
return $value->name === $expected;
}

if ($expected === 'true') {
return $value === true;
}

if ($expected === 'false') {
return $value === false;
}

// Float
if (is_numeric($expected) && Str::contains($expected, '.')) {
return $value === (float) $expected;
}

// Int
if (is_numeric($expected)) {
return $value === (int) $expected;
}

return (string) $value === $expected;
}

private function syncOriginalAccessors(): void
{
foreach ($this->getAttributeEvents() as $change => $event) {
Expand Down Expand Up @@ -137,16 +160,4 @@ 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');
}
}
14 changes: 14 additions & 0 deletions tests/AttributeEventsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,20 @@ public function it_works_with_enumerated_casts()
$this->dispatcher->assertDispatched(Fake\Events\EnumOrderShipped::class);
}

/** @test */
public function it_ignores_non_matching_enums()
{
$order = new Fake\Order();
$order->status_enum = OrderStatus::PROCESSING;
$order->save();

$order = Fake\Order::find($order->id);
$order->status_enum = OrderStatus::CANCELLED;
$order->save();

$this->dispatcher->assertNotDispatched(Fake\Events\EnumOrderShipped::class);
}

// Setup methods

private function initEventDispatcher()
Expand Down

0 comments on commit d9478f9

Please sign in to comment.