@@ -108,7 +108,7 @@ public function addBatch(array $metrics, int $batchSize = 1000): bool
108108 $ this ->db ->getAuthorization ()->skip (function () use ($ metrics , $ batchSize ) {
109109 $ documents = [];
110110 foreach ($ metrics as $ metric ) {
111- $ type = $ metric ['type ' ] ?? ' event ' ;
111+ $ type = $ metric ['type ' ];
112112
113113 if ($ type !== 'event ' && $ type !== 'gauge ' ) {
114114 throw new \InvalidArgumentException ("Invalid type ' {$ type }'. Allowed: event, gauge " );
@@ -164,30 +164,65 @@ public function getTimeSeries(array $metrics, string $interval, string $startDat
164164 /**
165165 * Get total value for a single metric.
166166 *
167- * Stub implementation for Database adapter .
167+ * Returns SUM for event metrics, latest value for gauge metrics .
168168 *
169169 * @param string $metric
170170 * @param array<Query> $queries
171171 * @return int
172172 */
173173 public function getTotal (string $ metric , array $ queries = []): int
174174 {
175- // Stub: not yet implemented
176- return 0 ;
175+ $ allQueries = array_merge ($ queries , [
176+ Query::equal ('metric ' , [$ metric ]),
177+ ]);
178+
179+ /** @var array<Metric> $results */
180+ $ results = $ this ->find ($ allQueries );
181+
182+ if (empty ($ results )) {
183+ return 0 ;
184+ }
185+
186+ // Determine type from first result
187+ $ type = $ results [0 ]->getType ();
188+
189+ if ($ type === 'gauge ' ) {
190+ // For gauge, return the last (most recently inserted) value
191+ $ lastResult = end ($ results );
192+ return $ lastResult !== false ? ($ lastResult ->getValue (0 ) ?? 0 ) : 0 ;
193+ }
194+
195+ // For events, SUM all values
196+ $ sum = 0 ;
197+ foreach ($ results as $ result ) {
198+ $ sum += (int ) ($ result ->getValue (0 ) ?? 0 );
199+ }
200+
201+ return $ sum ;
177202 }
178203
179204 /**
180205 * Get totals for multiple metrics.
181206 *
182- * Stub implementation for Database adapter .
207+ * Returns SUM for event metrics, latest value for gauge metrics .
183208 *
184209 * @param array<string> $metrics
185210 * @param array<Query> $queries
186211 * @return array<string, int>
187212 */
188213 public function getTotalBatch (array $ metrics , array $ queries = []): array
189214 {
190- return \array_fill_keys ($ metrics , 0 );
215+ if (empty ($ metrics )) {
216+ return [];
217+ }
218+
219+ $ totals = \array_fill_keys ($ metrics , 0 );
220+
221+ foreach ($ metrics as $ metric ) {
222+ $ totals [$ metric ] = $ this ->getTotal ($ metric , $ queries );
223+ }
224+
225+ return $ totals ;
191226 }
192227
193228 /**
@@ -377,7 +412,7 @@ public function setNamespace(string $namespace): self
377412 */
378413 public function setTenant (?string $ tenant ): self
379414 {
380- $ this ->db ->setTenant ($ tenant );
415+ $ this ->db ->setTenant ($ tenant !== null ? ( int ) $ tenant : null );
381416 return $ this ;
382417 }
383418
0 commit comments