Skip to content

Fix TypeError in CacheEventListener when event type mismatches#44

Merged
LordSimal merged 1 commit intoLordSimal:3.xfrom
dereuromark:fix-cache-event-listener-type-safety
Jan 12, 2026
Merged

Fix TypeError in CacheEventListener when event type mismatches#44
LordSimal merged 1 commit intoLordSimal:3.xfrom
dereuromark:fix-cache-event-listener-type-safety

Conversation

@dereuromark
Copy link
Contributor

Summary

Fixes a TypeError that occurs when the dispatched cache event class doesn't match the expected type:

CakeSentry\Event\CacheEventListener::onCacheAfterDelete(): Argument #1 ($event) must be of type Cake\Cache\Event\CacheAfterDeleteEvent, Cake\Cache\Event\CacheAfterSetEvent given

This can happen in edge cases when nested cache operations cause the _eventClass property to be out of sync with the dispatched event name.

Changes

  • Changed parameter types from specific event classes to EventInterface
  • Added instanceof checks at the start of each handler
  • Returns early if the event type doesn't match expectations

This is a defensive programming approach that handles potential inconsistencies in the event system gracefully without crashing.

Test plan

  • Run existing tests
  • Verify that cache tracing still works correctly with all cache operations

Use defensive runtime type checking instead of strict PHP type hints
for cache event handlers. This prevents TypeErrors when the dispatched
event class doesn't match the expected type due to edge cases in
CakePHP's cache event dispatching.

The fix:
- Changes parameter types from specific event classes to EventInterface
- Adds instanceof checks at the start of each handler
- Returns early if the event type doesn't match expectations

This is a defensive programming approach that handles potential
inconsistencies in the event system gracefully.
@LordSimal LordSimal changed the base branch from 3.next to 3.x January 12, 2026 07:45
@LordSimal LordSimal merged commit a2b7336 into LordSimal:3.x Jan 12, 2026
5 of 6 checks passed
@LordSimal
Copy link
Owner

LordSimal commented Jan 12, 2026

It feels to me like this is more of a downstream error of a event bug instead of an actual bug in this plugin.
This is just soft fallback if the wrong event was dispatched.

Would be awesome if there is some way to reproduce that.

Especially since I just looked through all the events being dispatched in https://github.com/cakephp/cakephp/pull/18956/files and I can't figure out how something like

$this->dispatchEvent(CacheAfterDeleteEvent::NAME, ['key' => $key, 'success' => true]);

with a wrong $this->_eventClass could be happening.

Do you maybe have a custom CacheEngine?

@dereuromark
Copy link
Contributor Author

I use redis

@LordSimal
Copy link
Owner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants