* @param array $headers * @return array{status: int, body: string, error: string|null} */
( string $url, string $method = 'GET', array $headers = [], ?string $body = null, ?string $basicAuth = null, )
| 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 | ]; |
| 70 | } catch (\Throwable $e) { |
| 71 | $safeUrl = $this->getSafeUrlForLogging($url); |
| 72 | $exceptionMessage = str_replace($url, $safeUrl, $e->getMessage()); |
| 73 | $this->logger->error('Analytics external request failed: ' . $exceptionMessage, [ |
| 74 | 'method' => strtoupper($method), |
| 75 | 'url' => $safeUrl, |
| 76 | 'exceptionClass' => $e::class, |
| 77 | 'exceptionCode' => $e->getCode(), |
| 78 | 'exceptionMessage' => $exceptionMessage, |
| 79 | ]); |
| 80 | return ['status' => 0, 'body' => '', 'error' => 'External request failed']; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | private function getSafeUrlForLogging(string $url): string { |
no test coverage detected