@@ -27,6 +27,15 @@ class User extends Entity
2727{
2828 use LocatorAwareTrait;
2929
30+ /**
31+ * Cached per-request statistics.
32+ *
33+ * @var array<string, int|null>
34+ */
35+ protected array $ statsCache = [
36+ 'potato_sent_today ' => null ,
37+ ];
38+
3039 /**
3140 * Fields that can be mass assigned using newEntity() or patchEntity().
3241 *
@@ -121,6 +130,10 @@ public function potatoReceived(): int
121130 */
122131 public function potatoSentToday (): int
123132 {
133+ if ($ this ->statsCache ['potato_sent_today ' ] !== null ) {
134+ return (int )$ this ->statsCache ['potato_sent_today ' ];
135+ }
136+
124137 $ messagesTable = $ this ->fetchTable ('Messages ' );
125138
126139 $ query = $ messagesTable ->find ();
@@ -135,7 +148,10 @@ public function potatoSentToday(): int
135148 ])
136149 ->first ();
137150
138- return (int )$ result ->sent ;
151+ $ sentToday = (int )($ result ->sent ?? 0 );
152+ $ this ->statsCache ['potato_sent_today ' ] = $ sentToday ;
153+
154+ return $ sentToday ;
139155 }
140156
141157 /**
@@ -165,21 +181,9 @@ public function potatoReceivedToday(): int
165181 */
166182 public function potatoLeftToday (): int
167183 {
168- $ messagesTable = $ this ->fetchTable ('Messages ' );
169-
170- $ query = $ messagesTable ->find ();
171- $ result = $ query
172- ->select ([
173- 'sent ' => $ query ->func ()->sum ('amount ' ),
174- ])
175- ->where ([
176- 'sender_user_id ' => $ this ->id ,
177- 'type ' => Message::TYPE_POTATO ,
178- 'created >= ' => $ this ->getStartOfDay (),
179- ])
180- ->first ();
184+ $ sentToday = $ this ->potatoSentToday ();
181185
182- return Message::MAX_AMOUNT - ( int ) $ result -> sent ;
186+ return Message::MAX_AMOUNT - $ sentToday ;
183187 }
184188
185189 /**
0 commit comments