22
33namespace Coderflex \LaravelSendy ;
44
5- use Exception ;
6- use Illuminate \Support \Facades \Http ;
5+ use Coderflex \LaravelSendy \Concerns \InteractsWithHttpRequests ;
76
87class LaravelSendy
98{
10- protected string $ apiKey ;
11-
12- protected string $ apiUrl ;
13-
14- public function __construct ()
15- {
16- if (blank (config ('laravel-sendy.api_key ' ))) {
17- throw new Exception ('API Key is not set in the config file. ' );
18- }
19-
20- if (blank (config ('laravel-sendy.api_url ' ))) {
21- throw new Exception ('API URL is not set in the config file. ' );
22- }
23-
24- $ this ->apiKey = config ('laravel-sendy.api_key ' );
25- $ this ->apiUrl = config ('laravel-sendy.api_url ' );
26- }
9+ use InteractsWithHttpRequests;
2710
2811 public function subscribers (): Resources \Subscribers
2912 {
@@ -44,59 +27,4 @@ public function campaigns(): Resources\Campaigns
4427 {
4528 return new Resources \Campaigns ;
4629 }
47-
48- public function __call (string $ function , array $ args ): mixed
49- {
50- $ options = ['get ' , 'post ' , 'put ' , 'delete ' , 'patch ' ];
51- $ path = $ args [0 ] ?? null ;
52- $ data = $ args [1 ] ?? [];
53- $ async = $ args [2 ] ?? false ;
54- $ headers = $ args [3 ] ?? [];
55-
56- if (! in_array ($ function , $ options )) {
57- throw new Exception ("Method {$ function } not found. " );
58- }
59-
60- return self ::sendRequest (
61- type: $ function ,
62- request: $ path ,
63- data: $ data ,
64- headers: $ headers ,
65- async: $ async
66- );
67- }
68-
69- /**
70- * @throws \Exception
71- */
72- protected function sendRequest (string $ type , string $ request , array $ data = [], array $ headers = [], bool $ async = false ): mixed
73- {
74- try {
75- $ mainHeaders = array_merge ([
76- 'Content-Type ' => 'application/json ' ,
77- 'Accept ' => 'application/json ' ,
78- ], $ headers ?? []);
79-
80- $ payload = array_merge ($ data , [
81- 'api_key ' => $ this ->apiKey ,
82- ]);
83-
84- $ url = rtrim ($ this ->apiUrl , '/ ' ).'/ ' .ltrim ($ request , '/ ' );
85-
86- $ client = Http::withHeaders ($ headers );
87-
88- return $ async
89- ? $ client ->async ()->{$ type }($ url , $ payload )
90- : $ client ->{$ type }($ url , $ payload );
91-
92- } catch (Exception $ th ) {
93- throw new Exception ('Error: ' .$ th ->getMessage ());
94- }
95- }
96-
97- protected function isJson (string $ string ): bool
98- {
99- return is_array (json_decode ($ string )) &&
100- (json_last_error () === JSON_ERROR_NONE );
101- }
10230}
0 commit comments