Skip to content

Instantly share code, notes, and snippets.

@ger86
Last active April 3, 2019 22:00
Show Gist options
  • Save ger86/fdcece18887fdfbf368be361c9faff96 to your computer and use it in GitHub Desktop.
Save ger86/fdcece18887fdfbf368be361c9faff96 to your computer and use it in GitHub Desktop.
<?php
namespace App\Service\Api;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\RequestException as GuzzleRequestException;
use App\Model\Exception\RequestException;
class GuzzleApiRequest implements ApiRequestInterface {
/**
* Constructor
*
* @param string $backendUrl
* @param string $apiPath
*/
public function __construct(string $backendUrl, string $apiPath) {
$this->client = new Client([
'base_uri' => sprintf('%s/%s/', $backendUrl, $apiPath),
'cookies' => $jar,
'defaults' => [
'exceptions' => false,
'allow_redirects' => false
]
]);
}
/**
* Get request
*
* @param string $path
* @param array $queryParams
* @return array
*/
public function get(string $path, array $queryParams = []): array {
try {
$response = $this->client->request(
'GET',
$path,
[
'allow_redirects' => false,
'query' => $queryParams
]
);
return json_decode($response->getBody(), true);
} catch (GuzzleRequestException $exception) {
$requestException = new RequestException();
// set exception
throw $requestException;
}
}
/**
* Post request
*
* @param string $path
* @param array $postData
* @return array
*/
public function post(string $path, array $postData = [], $files = []): array {
$formType = empty($files) ? 'form_params' : 'multipart';
try {
$this->session->save();
$response = $this->client->request(
'POST',
$path,
[
$formType => empty($files) ? $postData : $this->prepareMultipartData($postData, $files)
]
);
return json_decode((string)$response->getBody(), true);
return json_decode($response->getBody(), true);
} catch (GuzzleRequestException $exception) {
$requestException = new RequestException($exception);
// set exception
throw $requestException;
}
}
private function prepareMultipartData(array $postData, array $files): array {
$postData = array_merge_recursive($postData, $files);
return $this->flatten($postData);
}
protected function flatten(array $array, string $prefix = '', string $suffix = ''): array
{
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $this->flatten($value, $prefix . $key . $suffix . '[', ']'));
} else {
if ($value instanceof UploadedFile) {
$result[] = [
'name' => $prefix . $key . $suffix,
'filename' => $value->getClientOriginalName(),
'Mime-Type' => $value->getClientMimeType(),
'contents' => file_get_contents($value->getPathname()),
];
} else {
$result[] = [
'name' => $prefix . $key . $suffix,
'contents' => $value,
];
}
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment