Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 40 |
|
0.00% |
0 / 2 |
CRAP | |
0.00% |
0 / 1 |
| SendgridEmailProvider | |
0.00% |
0 / 40 |
|
0.00% |
0 / 2 |
20 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
2 | |||
| send | |
0.00% |
0 / 36 |
|
0.00% |
0 / 1 |
12 | |||
| 1 | <?php |
| 2 | // App/Services/Communication/Providers/Email/SendgridEmailProvider.php |
| 3 | |
| 4 | namespace App\Services\Communication\Providers\Email; |
| 5 | |
| 6 | use App\Services\Communication\Contracts\EmailProviderInterface; |
| 7 | |
| 8 | class SendgridEmailProvider implements EmailProviderInterface |
| 9 | { |
| 10 | private string $apiUrl; |
| 11 | private string $apiKey; |
| 12 | private string $from; |
| 13 | private string $fromName; |
| 14 | |
| 15 | public function __construct(array $credentials) |
| 16 | { |
| 17 | $this->apiKey = $credentials['api_key'] ?? ''; |
| 18 | $this->from = $credentials['from'] ?? ''; |
| 19 | $this->fromName = $credentials['from_name'] ?? ''; |
| 20 | $this->apiUrl = $credentials['api_url'] ?? 'https://api.sendgrid.com/v3/mail/send'; |
| 21 | } |
| 22 | |
| 23 | public function send(string $to, string $subject, string $content): bool |
| 24 | { |
| 25 | try { |
| 26 | $client = \Config\Services::curlrequest(); |
| 27 | |
| 28 | $response = $client->post($this->apiUrl, [ |
| 29 | 'headers' => [ |
| 30 | 'Authorization' => 'Bearer ' . $this->apiKey, |
| 31 | 'Content-Type' => 'application/json', |
| 32 | ], |
| 33 | 'json' => [ |
| 34 | 'personalizations' => [ |
| 35 | [ |
| 36 | 'to' => [ |
| 37 | ['email' => $to] |
| 38 | ], |
| 39 | ], |
| 40 | ], |
| 41 | 'from' => [ |
| 42 | 'email' => $this->from, |
| 43 | 'name' => $this->fromName, |
| 44 | ], |
| 45 | 'subject' => $subject, |
| 46 | 'content' => [ |
| 47 | [ |
| 48 | 'type' => 'text/html', |
| 49 | 'value' => $content, |
| 50 | ], |
| 51 | ], |
| 52 | ], |
| 53 | ]); |
| 54 | |
| 55 | $status = $response->getStatusCode(); |
| 56 | |
| 57 | // Sendgrid retourne 202 Accepted sur succès |
| 58 | if ($status !== 202) { |
| 59 | log_message('error', '[SendgridEmailProvider] Échec envoi — HTTP ' . $status |
| 60 | . ' — ' . $response->getBody()); |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | return true; |
| 65 | |
| 66 | } catch (\Throwable $e) { |
| 67 | log_message('error', '[SendgridEmailProvider] ' . $e->getMessage()); |
| 68 | return false; |
| 69 | } |
| 70 | } |
| 71 | } |