MCPcopy Create free account
hub / github.com/Rello/analytics / ExternalHttpClient

Class ExternalHttpClient

lib/Security/ExternalHttpClient.php:11–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9use OCP\Http\Client\IClientService;
10
11class ExternalHttpClient {
12 public const CONNECT_TIMEOUT_SECONDS = 10;
13 public const TIMEOUT_SECONDS = 60;
14
15 public function __construct(private IClientService $clientService) {
16 }
17
18 /**
19 * @param array<string, string> $headers
20 * @return array{status: int, body: string, error: string|null}
21 */
22 public function request(
23 string $url,
24 string $method = 'GET',
25 array $headers = [],
26 ?string $body = null,
27 ?string $basicAuth = null,
28 ): array {
29 $urlError = ExternalUrlValidator::validate($url);
30 if ($urlError !== null) {
31 return ['status' => 0, 'body' => '', 'error' => $urlError];
32 }
33
34 foreach ($headers as $name => $value) {
35 if (!is_string($name) || preg_match('/[\r\n:]/', $name) || preg_match('/[\r\n]/', $value)) {
36 return ['status' => 0, 'body' => '', 'error' => 'External request headers are invalid'];
37 }
38 }
39
40 $options = [
41 'allow_redirects' => false,
42 'connect_timeout' => self::CONNECT_TIMEOUT_SECONDS,
43 'timeout' => self::TIMEOUT_SECONDS,
44 'verify' => true,
45 'headers' => $headers,
46 ];
47 if ($body !== null) {
48 $options['body'] = $body;
49 }
50 if ($basicAuth !== null && $basicAuth !== '') {
51 [$username, $password] = array_pad(explode(':', $basicAuth, 2), 2, '');
52 $options['auth'] = [$username, $password];
53 }
54
55 try {
56 $response = $this->clientService->newClient()->request(strtoupper($method), $url, $options);
57 return [
58 'status' => $response->getStatusCode(),
59 'body' => (string)$response->getBody(),
60 'error' => null,
61 ];
62 } catch (\Throwable $e) {
63 return ['status' => 0, 'body' => '', 'error' => 'External request failed'];
64 }
65 }
66}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected