From cad6280a45e3831345360b2b766e27af5b686d36 Mon Sep 17 00:00:00 2001 From: David Wheatley Date: Thu, 28 Jul 2022 19:14:32 +0100 Subject: [PATCH] fix: potential static caching memory exhaustion (#3548) * perf: get notification counts through relation, not model filtering * chore: rename `queryUnreadNotifications` to `unreadNotifications` * fix: null coalesce to 0 for notif read time --- framework/core/src/User/User.php | 35 +++++++++++++++++--------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/framework/core/src/User/User.php b/framework/core/src/User/User.php index 05ee35394..2de8037f5 100644 --- a/framework/core/src/User/User.php +++ b/framework/core/src/User/User.php @@ -439,7 +439,21 @@ class User extends AbstractModel */ public function getUnreadNotificationCount() { - return $this->getUnreadNotifications()->count(); + return $this->unreadNotifications()->count(); + } + + /** + * Return query builder for all notifications that have not been read yet. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + protected function unreadNotifications() + { + return $this->notifications() + ->whereIn('type', $this->getAlertableNotificationTypes()) + ->whereNull('read_at') + ->where('is_deleted', false) + ->whereSubjectVisibleTo($this); } /** @@ -449,18 +463,7 @@ class User extends AbstractModel */ protected function getUnreadNotifications() { - static $cached = []; - - if (! isset($cached[$this->id])) { - $cached[$this->id] = $this->notifications() - ->whereIn('type', $this->getAlertableNotificationTypes()) - ->whereNull('read_at') - ->where('is_deleted', false) - ->whereSubjectVisibleTo($this) - ->get(); - } - - return $cached[$this->id]; + return $this->unreadNotifications()->get(); } /** @@ -470,9 +473,9 @@ class User extends AbstractModel */ public function getNewNotificationCount() { - return $this->getUnreadNotifications()->filter(function ($notification) { - return $notification->created_at > $this->read_notifications_at ?: 0; - })->count(); + return $this->unreadNotifications() + ->where('created_at', '>', $this->read_notifications_at ?? 0) + ->count(); } /**