$data * @param array $headersMap */ public function buildRequest( HttpMethod $method, UriInterface $uri, array $data = [], array $headersMap = [], ): RequestInterface { $scheme = $uri->getScheme(); if ($scheme !== 'http' && $scheme !== 'https') { throw new \InvalidArgumentException('Only http(s) is allowed'); } foreach ($headersMap as $headerName => $value) { if (! is_string($headerName)) { throw new \InvalidArgumentException('Header must be a string'); } if (! is_string($value)) { throw new \InvalidArgumentException("Header value '{$headerName}' must be a string"); } } // ! Make sure parameters are on queries when HTTP GET if ($method === HttpMethod::GET) { $this->putAllParamsOnQuery($uri, $data); } else { $this->putAllParamInData($uri, $data); } $timestamp = Utils::getNow(); $request = new Psr7Request( \strtoupper($method->value), $uri, $headersMap ); // NOTE: Dont prodive body content on GET method. $jsonEncodedData = $method !== HttpMethod::GET ? GuzzleHttpUtils::jsonEncode($data) : ''; $alteredUri = $this->transformUriInOrderToMatchLabProxy($uri); $signature = Utils::calculateSignature( $method, $alteredUri, $jsonEncodedData, $this->apiConfig->secret, $timestamp ); $fullApiHeaders = $this->addApiHeaders( $headersMap, $signature, $timestamp ); return Psr7Utils::modifyRequest($request, [ 'set_headers' => $fullApiHeaders, 'body' => $jsonEncodedData, ]); } /** * @param array $headers * @return array */ protected function addApiHeaders( array $headers, string $signature, \DateTimeInterface $timestamp ): array { return array_merge( $headers, [ 'Content-Type' => 'application/json', 'X-API-Key' => $this->apiConfig->apiKey, 'X-API-Signature' => $signature, 'X-Timestamp' => Utils::toRfc3339($timestamp), ] ); } /** * @param array $data */ protected function putAllParamsOnQuery(UriInterface &$uri, array &$data): void { $existingQuery = $uri->getQuery(); $queryArray = []; if ($existingQuery !== '') { parse_str($existingQuery, $queryArray); } $merged = array_merge($queryArray, $data); $newQuery = $merged ? http_build_query($merged) : ''; $uri = $uri->withQuery($newQuery); $data = []; } /** * @param array $data */ protected function putAllParamInData(UriInterface &$uri, array &$data): void { $existingQuery = $uri->getQuery(); if ($existingQuery === '') { return; } $queryArray = []; parse_str($existingQuery, $queryArray); $data = array_merge($queryArray, $data); $uri = $uri->withQuery(''); } /** * FIXME: This should be removed, temp fix */ protected function transformUriInOrderToMatchLabProxy(UriInterface $uri): UriInterface { $scheme = $uri->getScheme(); $authority = str_replace('lesidc', 'svlidc', $uri->getAuthority()); $path = '/gaston/api' . preg_replace('/^\/gaston\/api/', '', $uri->getPath()); $query = ! empty($uri->getQuery()) ? "?{$uri->getQuery()}" : ''; $fragment = ! empty($uri->getFragment()) ? "#{$uri->getFragment()}" : ''; return new Uri( "{$scheme}://{$authority}{$path}{$query}{$fragment}" ); } }