Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 24 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
| SmsRateLimiterService | |
0.00% |
0 / 24 |
|
0.00% |
0 / 3 |
30 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| allow | |
0.00% |
0 / 22 |
|
0.00% |
0 / 1 |
12 | |||
| sleepForThrottle | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Modules\NotificationModule\Services; |
| 4 | |
| 5 | use App\Modules\NotificationModule\Models\SmsRateLimitModel; |
| 6 | |
| 7 | class SmsRateLimiterService |
| 8 | { |
| 9 | protected SmsRateLimitModel $model; |
| 10 | |
| 11 | public function __construct() |
| 12 | { |
| 13 | $this->model = new SmsRateLimitModel(); |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * Vérifie si le provider peut encore envoyer |
| 18 | */ |
| 19 | public function allow(string $provider, int $limitPerMinute = 60): bool |
| 20 | { |
| 21 | $windowStart = date('Y-m-d H:i:00'); |
| 22 | |
| 23 | $row = $this->model |
| 24 | ->where('provider', $provider) |
| 25 | ->where('window_start', $windowStart) |
| 26 | ->first(); |
| 27 | |
| 28 | /** |
| 29 | * Première entrée fenêtre |
| 30 | */ |
| 31 | if (!$row) { |
| 32 | |
| 33 | $this->model->insert([ |
| 34 | 'provider' => $provider, |
| 35 | 'window_start' => $windowStart, |
| 36 | 'sent_count' => 1, |
| 37 | ]); |
| 38 | |
| 39 | return true; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Limite atteinte |
| 44 | */ |
| 45 | if ((int) $row->sent_count >= $limitPerMinute) { |
| 46 | |
| 47 | log_message( |
| 48 | 'warning', |
| 49 | "[RATE_LIMIT_BLOCKED] provider={$provider} limit={$limitPerMinute}" |
| 50 | ); |
| 51 | |
| 52 | return false; |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Incrément compteur |
| 57 | */ |
| 58 | $this->model->update($row->id, [ |
| 59 | 'sent_count' => (int) $row->sent_count + 1, |
| 60 | ]); |
| 61 | |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | |
| 66 | public function sleepForThrottle(): void |
| 67 | { |
| 68 | usleep(200000); // 0.2 sec |
| 69 | } |
| 70 | } |