66use Coderflex \LaravelSendy \Resources \Resources \Campaigns ;
77use Coderflex \LaravelSendy \Resources \Resources \Lists ;
88use Coderflex \LaravelSendy \Resources \Resources \Subscribers ;
9+ use Exception ;
10+ use GuzzleHttp \Client ;
11+ use GuzzleHttp \Exception \ClientException ;
912
1013class LaravelSendy
1114{
15+ protected string $ apiKey ;
16+
17+ protected string $ apiUrl ;
18+
19+ public function __construct ()
20+ {
21+ if (blank (config ('laravel-sendy.api_key ' ))) {
22+ throw new Exception ('API Key is not set in the config file. ' );
23+ }
24+
25+ if (blank (config ('laravel-sendy.api_url ' ))) {
26+ throw new Exception ('API URL is not set in the config file. ' );
27+ }
28+
29+ $ this ->apiKey = config ('laravel-sendy.api_key ' );
30+ $ this ->apiUrl = config ('laravel-sendy.api_url ' );
31+ }
32+
1233 public function subscribers (): Subscribers
1334 {
1435 return new Subscribers ;
@@ -28,4 +49,65 @@ public function campaigns(): Campaigns
2849 {
2950 return new Campaigns ;
3051 }
52+
53+ public function __call (string $ function , array $ args )
54+ {
55+ $ options = ['get ' , 'post ' , 'put ' , 'delete ' , 'patch ' ];
56+ $ path = (isset ($ args [0 ])) ? $ args [0 ] : null ;
57+ $ data = (isset ($ args [1 ])) ? $ args [1 ] : [];
58+ $ headers = (isset ($ args [2 ])) ? $ args [2 ] : [];
59+
60+ if (! in_array ($ function , $ options )) {
61+ throw new Exception ("Method {$ function } not found. " );
62+ }
63+
64+ return self ::guzzle (
65+ type: $ function ,
66+ request: $ path ,
67+ data: $ data ,
68+ headers: $ headers
69+ );
70+ }
71+
72+ /**
73+ * @throws \Exception
74+ */
75+ protected function guzzle (string $ type , string $ request , array $ data = [], array $ headers = []): mixed
76+ {
77+ try {
78+ $ client = new Client ;
79+
80+ $ mainHeaders = [
81+ 'Content-Type ' => 'application/json ' ,
82+ 'Accept ' => 'application/json ' ,
83+ 'Authorization ' => 'Bearer ' .$ this ->apiKey ,
84+ ];
85+
86+ $ headers = is_array ($ headers ) && count ($ headers ) > 0
87+ ? array_merge ($ mainHeaders , $ headers )
88+ : $ mainHeaders ;
89+
90+ $ response = $ client ->$ type ($ this ->apiUrl .$ request , [
91+ 'headers ' => $ headers ,
92+ 'body ' => json_encode ($ data ),
93+ ]);
94+
95+ $ responseObject = $ response ->getBody ()->getContents ();
96+
97+ return $ this ->isJson ($ responseObject )
98+ ? json_decode ($ responseObject , true )
99+ : $ responseObject ;
100+
101+ } catch (ClientException $ th ) {
102+ throw new Exception ('Error: ' .$ th ->getMessage ());
103+ } catch (Exception $ th ) {
104+ throw new Exception ('Error: ' .$ th ->getMessage ());
105+ }
106+ }
107+
108+ protected function isJson (string $ string ): bool
109+ {
110+ return is_array (json_decode ($ string )) &&
111+ (json_last_error () === JSON_ERROR_NONE );
112+ }
31113}
0 commit comments