Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 35 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
| FloodProtector | |
0.00% |
0 / 35 |
|
0.00% |
0 / 3 |
20 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| canSendMessage | |
0.00% |
0 / 24 |
|
0.00% |
0 / 1 |
6 | |||
| logMessage | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace BuyerKiosk\SMS\TextMessageService; |
| 4 | |
| 5 | class FloodProtector { |
| 6 | private $store; |
| 7 | private $db; |
| 8 | private const MAX_MESSAGES_PER_DAY = 5; |
| 9 | |
| 10 | public function __construct($store) { |
| 11 | $this->store = $store; |
| 12 | $this->db = dbConnectByName($_ENV['DB_NAME']); |
| 13 | } |
| 14 | |
| 15 | public function canSendMessage(string $phone): array { |
| 16 | // Clean phone number |
| 17 | $phone = preg_replace('/[^0-9]/', '', $phone); |
| 18 | |
| 19 | // Convert UTC to store's timezone |
| 20 | $storeTimezone = new \DateTimeZone($this->store->getTimeZone()); |
| 21 | $utcTimezone = new \DateTimeZone('UTC'); |
| 22 | |
| 23 | $dateUtc = new \DateTime('now', $utcTimezone); |
| 24 | $dateStore = $dateUtc->setTimezone($storeTimezone); |
| 25 | |
| 26 | $todayDate = $dateStore->format('Y-m-d'); |
| 27 | |
| 28 | // Count messages sent today for this phone number |
| 29 | $query = "SELECT COUNT(*) as message_count |
| 30 | FROM floodProtector |
| 31 | WHERE phone = ? |
| 32 | AND date = ?"; |
| 33 | |
| 34 | $stmt = $this->db->prepare($query); |
| 35 | $stmt->execute([$phone, $todayDate]); |
| 36 | $result = $stmt->fetch(\PDO::FETCH_ASSOC); |
| 37 | |
| 38 | if ($result['message_count'] >= self::MAX_MESSAGES_PER_DAY) { |
| 39 | return [ |
| 40 | 'provider' => 'flood_protector', |
| 41 | 'status' => 'failed', |
| 42 | 'id' => null, |
| 43 | 'error' => "Daily message limit (".self::MAX_MESSAGES_PER_DAY.") exceeded for phone: {$phone}" |
| 44 | ]; |
| 45 | } |
| 46 | |
| 47 | return [ |
| 48 | 'provider' => 'flood_protector', |
| 49 | 'status' => 'success', |
| 50 | 'id' => null, |
| 51 | 'error' => null |
| 52 | ]; |
| 53 | } |
| 54 | |
| 55 | |
| 56 | public function logMessage(string $phone): void { |
| 57 | // Clean phone number |
| 58 | $phone = preg_replace('/[^0-9]/', '', $phone); |
| 59 | |
| 60 | // Convert UTC to store's timezone |
| 61 | $storeTimezone = new \DateTimeZone($this->store->getTimeZone()); |
| 62 | $utcTimezone = new \DateTimeZone('UTC'); |
| 63 | |
| 64 | $dateUtc = new \DateTime('now', $utcTimezone); |
| 65 | $dateStore = $dateUtc->setTimezone($storeTimezone); |
| 66 | |
| 67 | $todayDate = $dateStore->format('Y-m-d'); |
| 68 | |
| 69 | // Log the message |
| 70 | $query = "INSERT INTO floodProtector (phone, date) VALUES (?, ?)"; |
| 71 | $stmt = $this->db->prepare($query); |
| 72 | $stmt->execute([$phone, $todayDate]); |
| 73 | } |
| 74 | } |