Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
sms
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 summary
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2// This file is part of Moodle - https://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
16
17namespace message_notifyhub\local;
18
19/**
20 * SMS results per gateway, read from core_sms's own table (core routes SMS between gateways itself).
21 *
22 * @package    message_notifyhub
23 * @copyright  2026 DevLMS
24 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26final class sms {
27    /**
28     * Sent, failed and pending counts per gateway since a time.
29     *
30     * @param int $since
31     * @return array[] name, sent, failed, pending
32     */
33    public static function summary(int $since): array {
34        global $DB;
35        $sql = 'SELECT m.gatewayid, m.status, COUNT(1) AS n
36                  FROM {sms_messages} m
37                 WHERE m.timecreated >= ? AND m.gatewayid IS NOT NULL
38              GROUP BY m.gatewayid, m.status';
39        $counts = [];
40        $rows = $DB->get_recordset_sql($sql, [$since]);
41        foreach ($rows as $row) {
42            $status = \core_sms\message_status::tryFrom((string) $row->status) ?? \core_sms\message_status::UNKNOWN;
43            $bucket = $status->is_sent() ? 'sent' : ($status->is_failed() ? 'failed' : 'pending');
44            $counts[$row->gatewayid][$bucket] = ($counts[$row->gatewayid][$bucket] ?? 0) + (int) $row->n;
45        }
46        $rows->close();
47        if (!$counts) {
48            return [];
49        }
50        $names = $DB->get_records_list('sms_gateways', 'id', array_keys($counts), 'name', 'id, name');
51        $summary = [];
52        foreach ($names as $id => $gateway) {
53            $summary[] = [
54                'name' => format_string($gateway->name),
55                'sent' => $counts[$id]['sent'] ?? 0,
56                'failed' => $counts[$id]['failed'] ?? 0,
57                'pending' => $counts[$id]['pending'] ?? 0,
58            ];
59        }
60        return $summary;
61    }
62}