sslVerify = $sslVerify; $this->timeout = $timeout; $this->retries = $retries; } /** * Do a GET request to retrieve the contents of a remote URL. * * @param string $url URL to get. * @return Response Response for the executed request. * @throws FailedRemoteRequest If retrieving the contents from the URL failed. */ public function get($url) { $retriesLeft = $this->retries; do { $curlHandle = curl_init(); $headers = []; curl_setopt($curlHandle, CURLOPT_URL, $url); curl_setopt($curlHandle, CURLOPT_HEADER, 0); curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, $this->sslVerify ? 1 : 0); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, $this->sslVerify ? 2 : 0); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, $this->timeout); curl_setopt($curlHandle, CURLOPT_TIMEOUT, $this->timeout); curl_setopt( $curlHandle, CURLOPT_HEADERFUNCTION, static function ($curl, $header) use (&$headers) { $length = strlen($header); $header = array_map('trim', explode(':', $header, 2)); // Only store valid headers, discard invalid ones that choke on the explode. if (count($header) === 2) { $headers[$header[0]][] = $header[1]; } return $length; } ); $body = curl_exec($curlHandle); $status = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE); $curlErrno = curl_errno($curlHandle); curl_close($curlHandle); if ($body === false) { if (! $retriesLeft || in_array($curlErrno, self::RETRYABLE_ERROR_CODES, true) === false) { if (! empty($status) && is_numeric($status)) { throw FailedToGetFromRemoteUrl::withHttpStatus($url, (int) $status); } throw FailedToGetFromRemoteUrl::withoutHttpStatus($url); } continue; } return new RemoteGetRequestResponse($body, $headers, (int) $status); } while ($retriesLeft--); // This should never be triggered, but we want to ensure we always have a typed return value, // to make PHPStan happy. return new RemoteGetRequestResponse('', [], 500); } }