|
1
|
|
|
<?php /** @noinspection PhpComposerExtensionStubsInspection */ |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Jasny\SSO\Broker; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Wrapper for cURL. |
|
9
|
|
|
* |
|
10
|
|
|
* @codeCoverageIgnore |
|
11
|
|
|
*/ |
|
12
|
|
|
class Curl |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Curl constructor. |
|
16
|
|
|
* |
|
17
|
|
|
* @throws \Exception if curl extension isn't loaded |
|
18
|
|
|
*/ |
|
19
|
|
|
public function __construct() |
|
20
|
|
|
{ |
|
21
|
|
|
if (!extension_loaded('curl')) { |
|
22
|
|
|
throw new \Exception("cURL extension not loaded"); |
|
23
|
|
|
} |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Send an HTTP request to the SSO server. |
|
28
|
|
|
* |
|
29
|
|
|
* @param string $method HTTP method: 'GET', 'POST', 'DELETE' |
|
30
|
|
|
* @param string $url Full URL |
|
31
|
|
|
* @param string[] $headers HTTP headers |
|
32
|
|
|
* @param array<string,mixed>|string $data Query or post parameters |
|
33
|
|
|
* @return array{httpCode:int,contentType:string,body:string} |
|
34
|
|
|
* @throws RequestException |
|
35
|
|
|
*/ |
|
36
|
|
|
public function request(string $method, string $url, array $headers, $data = '') |
|
37
|
|
|
{ |
|
38
|
|
|
$ch = curl_init($url); |
|
39
|
|
|
|
|
40
|
|
|
if ($ch === false) { |
|
41
|
|
|
throw new \RuntimeException("Failed to initialize a cURL session"); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if ($data !== [] && $data !== '') { |
|
45
|
|
|
$post = is_string($data) ? $data : http_build_query($data); |
|
46
|
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
50
|
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); |
|
51
|
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); |
|
52
|
|
|
|
|
53
|
|
|
$responseBody = (string)curl_exec($ch); |
|
54
|
|
|
|
|
55
|
|
|
if (curl_errno($ch) != 0) { |
|
56
|
|
|
throw new RequestException('Server request failed: ' . curl_error($ch)); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
|
60
|
|
|
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ?? 'text/html'; |
|
61
|
|
|
|
|
62
|
|
|
return ['httpCode' => $httpCode, 'contentType' => $contentType, 'body' => $responseBody]; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|