* @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, )
| 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 | } |
no test coverage detected