22
33namespace PhpMonsters \LaravelPostalDriver ;
44
5- use Illuminate \Mail \Transport \Transport ;
6- use Swift_Mime_SimpleMessage ;
5+ use Symfony \Component \Mailer \Envelope ;
6+ use Symfony \Component \Mailer \SentMessage ;
7+ use Symfony \Component \Mailer \Transport \TransportInterface ;
8+ use Symfony \Component \Mime \RawMessage ;
9+ use Symfony \Component \Mime \Email ;
710use GuzzleHttp \Client ;
811
9- class PostalTransport extends Transport
12+ class PostalTransport implements TransportInterface
1013{
11- protected string $ key ;
12- protected string $ endpoint ;
1314 protected Client $ client ;
15+ protected string $ apiKey ;
16+ protected string $ baseUrl ;
1417
15- public function __construct (string $ key , string $ endpoint )
18+ public function __construct (Client $ client , string $ apiKey , string $ baseUrl )
1619 {
17- $ this ->key = $ key ;
18- $ this ->endpoint = rtrim ( $ endpoint , ' / ' ) ;
19- $ this ->client = new Client ( );
20+ $ this ->client = $ client ;
21+ $ this ->apiKey = $ apiKey ;
22+ $ this ->baseUrl = rtrim ( $ baseUrl , ' / ' );
2023 }
2124
22- public function send (Swift_Mime_SimpleMessage $ message , & $ failedRecipients = null ): int
25+ public function send (RawMessage $ message , Envelope $ envelope = null ): SentMessage
2326 {
24- $ to = array_keys ($ message ->getTo ())[0 ];
25- $ from = array_keys ($ message ->getFrom ())[0 ];
26- $ subject = $ message ->getSubject ();
27- $ html = $ message ->getBody ();
28- $ plain = strip_tags ($ html );
27+ if (!$ message instanceof Email) {
28+ throw new \InvalidArgumentException ('PostalTransport only supports Email messages. ' );
29+ }
2930
30- $ response = $ this -> client -> post ( $ this -> endpoint . ' /api/v1/send/message ' , [
31+ $ payload = [
3132 'headers ' => [
32- 'X-Server-API-Key ' => $ this ->key ,
33- 'Content-Type ' => 'application/json '
33+ 'X-Server-API-Key ' => $ this ->apiKey ,
34+ 'Accept ' => 'application/json ' ,
35+ 'Content-Type ' => 'application/json ' ,
3436 ],
3537 'json ' => [
36- 'to ' => $ to ,
37- 'from ' => $ from ,
38- 'subject ' => $ subject ,
39- 'plain_body ' => $ plain ,
40- 'html_body ' => $ html
41- ]
42- ]);
43-
44- return $ this ->numberOfRecipients ($ message );
38+ 'from ' => $ message ->getFrom ()[0 ]->getAddress (),
39+ 'to ' => array_map (fn ($ to ) => $ to ->getAddress (), $ message ->getTo ()),
40+ 'subject ' => $ message ->getSubject (),
41+ 'plain_body ' => $ message ->getTextBody (),
42+ 'html_body ' => $ message ->getHtmlBody (),
43+ ],
44+ ];
45+
46+ $ this ->client ->post ("{$ this ->baseUrl }/send/message " , $ payload );
47+
48+ return new SentMessage ($ message , $ envelope );
49+ }
50+
51+ public function __toString (): string
52+ {
53+ return 'postal ' ;
4554 }
46- }
55+ }
0 commit comments