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

Class ExternalHttpClient

lib/Security/ExternalHttpClient.php:12–94  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected