-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
712 lines (649 loc) · 15.8 KB
/
Client.php
File metadata and controls
712 lines (649 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<?php
/**
* @author : Jakiboy
* @package : FloatPHP
* @subpackage : Classes Http Component
* @version : 1.5.x
* @copyright : (c) 2018 - 2025 Jihad Sinnaour <me@jihadsinnaour.com>
* @link : https://floatphp.com
* @license : MIT
*
* This file is a part of FloatPHP Framework.
*/
declare(strict_types=1);
namespace FloatPHP\Classes\Http;
use FloatPHP\Classes\Filesystem\{Stringify, Arrayify, Converter, TypeCheck, Json};
use FloatPHP\Classes\Server\System;
use FloatPHP\Exceptions\Classes\ClientException;
/**
* Advanced HTTP request client (cURL|Stream).
*/
class Client
{
/**
* @access public
*/
public const GET = 'GET';
public const POST = 'POST';
public const HEAD = 'HEAD';
public const PUT = 'PUT';
public const PATCH = 'PATCH';
public const OPTIONS = 'OPTIONS';
public const DELETE = 'DELETE';
public const TIMEOUT = 10;
public const REDIRECT = 3;
public const PATTERN = [
'status' => '/^\s*HTTP\/\d+(\.\d+)?\s+(?P<code>\d+)\s*(?P<message>.*)?\r?\n?$/',
'attribute' => '/^\s*(?P<name>[a-zA-Z0-9\-]+)\s*:\s*(?P<value>.*?)\s*(?:\r?\n|$)/',
'location' => "/Location:\s*(.+)/i"
];
public const USERAGENT = [
'Mozilla/5.0',
'(X11; Linux x86_64)',
'AppleWebKit/537.36',
'(KHTML, like Gecko)',
'Chrome/114.0.5735.199',
'Safari/537.36'
];
/**
* @access protected
*/
protected $method;
protected $params = [];
protected $header = [];
protected $body = [];
protected $response = [];
protected $baseUrl;
protected $url;
protected $gateway;
protected const CURL = 'Curl';
protected const STREAM = 'Stream';
/**
* @access protected
* @var array $pattern Parser pattern
*/
private static $pattern = [];
/**
* Init client.
*
* @access public
* @param ?string $baseUrl
* @param array $params
*/
public function __construct(?string $baseUrl = null, array $params = [])
{
$this->baseUrl = $baseUrl;
$this->params = self::getParams($params);
$this->setGateway();
self::setPattern();
}
/**
* Make Http request.
*
* @access public
* @param string $method
* @param array $body
* @param array $header
* @param ?string $url
* @return object
*/
public function request(string $method, array $body = [], array $header = [], ?string $url = null) : self
{
// Reset client
$this->reset();
// Set method
$this->setMethod($method);
// Set body
$this->setBody($body);
// Set header
$this->setHeader($header);
// Set URL
$this->setUrl($url);
// Execute request
$this->execute();
return $this;
}
/**
* Make Http GET request.
*
* @access public
* @param ?string $url
* @param array $body
* @param array $header
* @return object
*/
public function get(?string $url = null, array $body = [], array $header = []) : self
{
return $this->request(self::GET, $body, $header, $url);
}
/**
* Make Http POST request.
*
* @access public
* @param ?string $url
* @param array $body
* @param array $header
* @return object
*/
public function post(?string $url = null, array $body = [], array $header = []) : self
{
return $this->request(self::POST, $body, $header, $url);
}
/**
* Make Http HEAD request.
*
* @access public
* @param ?string $url
* @param array $body
* @param array $header
* @return object
*/
public function head(?string $url = null, array $body = [], array $header = []) : self
{
return $this->request(self::HEAD, $body, $header, $url);
}
/**
* Make Http PUT request.
*
* @access public
* @param ?string $url
* @param array $body
* @param array $header
* @return object
*/
public function put(?string $url = null, array $body = [], array $header = []) : self
{
return $this->request(self::PUT, $body, $header, $url);
}
/**
* Make Http PATCH request.
*
* @access public
* @param ?string $url
* @param array $body
* @param array $header
* @return object
*/
public function patch(?string $url = null, array $body = [], array $header = []) : self
{
return $this->request(self::PATCH, $body, $header, $url);
}
/**
* Make Http DELETE request.
*
* @access public
* @param ?string $url
* @param array $body
* @param array $header
* @return object
*/
public function delete(?string $url = null, array $body = [], array $header = []) : self
{
return $this->request(self::DELETE, $body, $header, $url);
}
/**
* Set request method.
*
* @access public
* @param string $method
* @return object
*/
public function setMethod(string $method) : self
{
$this->method = Stringify::uppercase($method);
return $this;
}
/**
* Set request header.
*
* @access public
* @param array $header
* @return object
*/
public function setHeader(array $header = []) : self
{
$this->header = Arrayify::merge(
$this->header,
$header
);
return $this;
}
/**
* Set request body (Data).
*
* @access public
* @param array $body
* @return object
*/
public function setBody(array $body = []) : self
{
$this->body = Arrayify::merge(
$this->body,
$body
);
return $this;
}
/**
* Set request URL (Append to base URL).
*
* @access public
* @param ?string $url
* @return object
*/
public function setUrl(?string $url = null) : self
{
$url = (string)$url;
$baseUrl = (string)$this->baseUrl;
$this->url = Stringify::formatPath("{$baseUrl}/{$url}", true);
return $this;
}
/**
* Set request timeout.
*
* @access public
* @param int $timeout
* @return object
*/
public function setTimeout(int $timeout) : self
{
$this->params['timeout'] = $timeout;
return $this;
}
/**
* Set request max redirections.
*
* @access public
* @param int $redirect
* @return object
*/
public function setRedirect(int $redirect) : self
{
$this->params['redirect'] = $redirect;
return $this;
}
/**
* Set request encoding.
*
* @access public
* @param string $encoding
* @return object
*/
public function setEncoding(string $encoding) : self
{
$this->params['encoding'] = $encoding;
return $this;
}
/**
* Set User-Agent.
*
* @access public
* @param ?string $ua
* @return object
*/
public function setUserAgent(?string $ua = null) : self
{
$this->params['ua'] = $ua;
return $this;
}
/**
* Allow cURL transfer return.
*
* @access public
* @return object
*/
public function return() : self
{
$this->params['return'] = true;
return $this;
}
/**
* Allow cURL redirection follow.
*
* @access public
* @return object
*/
public function follow() : self
{
$this->params['follow'] = true;
return $this;
}
/**
* Allow cURL header in reponse.
*
* @access public
* @return object
*/
public function headerIn() : self
{
$this->params['headerIn'] = true;
return $this;
}
/**
* Get response data.
*
* @access public
* @return array
*/
public function getResponse() : array
{
return $this->response;
}
/**
* Get response status (code, message).
*
* @access public
* @return array
*/
public function getStatus() : array
{
return $this->getResponse()['status'] ?? [];
}
/**
* Get response status code.
*
* @access public
* @return int
*/
public function getStatusCode() : int
{
return $this->getStatus()['code'] ?? -1;
}
/**
* Get response status message.
*
* @access public
* @return string
*/
public function getStatusMessage() : string
{
return $this->getStatus()['message'] ?? '';
}
/**
* Get response header.
*
* @access public
* @return array
*/
public function getHeader() : array
{
return $this->getResponse()['header'] ?? [];
}
/**
* Get response body.
*
* @access public
* @param bool $decode JSON
* @return mixed
*/
public function getBody(bool $decode = true) : mixed
{
$body = $this->getResponse()['body'] ?? '';
if ( $decode ) {
return Json::decode($body, isArray: true) ?: [];
}
return $body;
}
/**
* Check client error (Http|Gateway).
*
* @access public
* @param int $httpCode
* @return bool
*/
public function hasError(int $httpCode = 400) : bool
{
// Check for Gateway error
$error = $this->getResponse()['error'] ?? false;
if ( $error ) return true;
// Check for Http error
return $this->getStatusCode() >= $httpCode;
}
/**
* Check curl gateway.
*
* @access public
* @return bool
*/
public function isCurl() : bool
{
return $this->gateway == self::CURL;
}
/**
* Check stream gateway.
*
* @access public
* @return bool
*/
public function isStream() : bool
{
return $this->gateway == self::STREAM;
}
/**
* Get effective URL.
*
* @access public
* @param ?string $url
* @param bool $parse
* @return string
*/
public function getLocation(?string $url = null, bool $parse = true) : string
{
// Set url
$this->setUrl($url);
// Get location
$location = $this->gateway::getLocation($this->url, [
'header' => $this->header,
'body' => $this->body,
'method' => $this->method,
'timeout' => $this->params['timeout'],
'redirect' => $this->params['redirect'],
'encoding' => $this->params['encoding'],
'ssl' => Server::isSsl()
]);
return $parse ? self::parseUrl($location) : $location;
}
/**
* Parse URL (clean).
*
* @access public
* @param string $url
* @return string
*/
public static function parseUrl(string $url) : string
{
$scheme = Stringify::parseUrl($url, 0);
$host = Stringify::parseUrl($url, 1);
$path = Stringify::parseUrl($url, 5);
return Stringify::formatPath("{$scheme}://{$host}/{$path}");
}
/**
* Check cURL status.
*
* @access public
* @return bool
*/
public static function hasCurl() : bool
{
return TypeCheck::isFunction('curl-init');
}
/**
* Check stream status.
*
* @access public
* @return bool
*/
public static function hasStream() : bool
{
$val = intval(System::getIni('allow-url-fopen'));
return (bool)$val;
}
/**
* Set Http parser patterns.
*
* @access public
* @param array $pattern
* @return void
*/
public static function setPattern(array $pattern = []) : void
{
self::$pattern = Arrayify::merge(self::PATTERN, $pattern);
}
/**
* Get Http parser patterns.
*
* @access public
* @param string $name
* @return string
*/
public static function getPattern(string $name) : string
{
return self::$pattern[$name] ?? '';
}
/**
* Get request body data (query).
*
* @access public
* @param array $body
* @param string $url
* @return string
*/
public static function getQuery(array $body, ?string $url = null) : string
{
$query = [];
foreach ($body as $key => $value) {
$value = Converter::toString($value);
if ( TypeCheck::isInt($key) ) {
$query[$value] = '';
} else {
$query[$key] = $value;
}
}
$query = Stringify::buildQuery($query, '', '$', 2);
$query = Stringify::replace('=&', '&', $query);
$query = rtrim($query, '=');
if ( $url && $query ) {
$query = "{$url}?{$query}";
}
return $query;
}
/**
* Format inline Http header.
*
* @access public
* @param array $header
* @return string
*/
public static function formatHeader(array $header) : string
{
$format = '';
foreach ($header as $key => $value) {
$format .= "{$key}: {$value}\r\n";
}
return $format;
}
/**
* Get default User-Agent.
*
* @access public
* @return string
*/
public static function getUserAgent() : string
{
return implode(', ', static::USERAGENT);
}
/**
* Get default Http client parameters.
*
* @access public
* @param array $params
* @return array
*/
public static function getParams(array $params = []) : array
{
return Arrayify::merge([
'header' => [],
'body' => [],
'method' => null,
'timeout' => self::TIMEOUT,
'redirect' => self::REDIRECT,
'ua' => self::getUserAgent(),
'ssl' => true,
'encoding' => null,
'return' => false,
'follow' => false,
'headerIn' => false
], $params);
}
/**
* Get default extra params (crawler).
*
* @access public
* @param array $params
* @return array
*/
public static function getExtra(array $params = []) : array
{
return Arrayify::merge([
'path' => null,
'signature' => null,
'ext' => null
], $params);
}
/**
* Execute request.
*
* @access protected
* @return void
*/
protected function execute() : void
{
$this->response = $this->gateway::request($this->url, [
'header' => $this->header,
'body' => $this->body,
'method' => $this->method,
'timeout' => $this->params['timeout'],
'redirect' => $this->params['redirect'],
'encoding' => $this->params['encoding'],
'return' => $this->params['return'],
'follow' => $this->params['follow'],
'headerIn' => $this->params['headerIn'],
'ua' => $this->params['ua'],
'ssl' => Server::isSsl()
]);
}
/**
* Set gateway.
*
* @access protected
* @return void
* @throws ClientException
*/
protected function setGateway() : void
{
$this->gateway = match (true) {
self::hasCurl() => self::CURL,
self::hasStream() => self::STREAM,
default => 'undefined'
};
if ( $this->gateway == 'undefined' ) {
throw new ClientException(
ClientException::invalidGateway()
);
}
$ns = __NAMESPACE__;
$gateway = "{$ns}\\{$this->gateway}";
$this->gateway = new $gateway;
}
/**
* Reset client.
*
* @access protected
* @return void
*/
protected function reset() : void
{
$this->header = [];
$this->body = [];
$this->response = [];
}
}