Skip to content

Instantly share code, notes, and snippets.

@JuanDMeGon
Created March 21, 2019 04:29
Show Gist options
  • Save JuanDMeGon/98ae594d668504bfdb2d6333d0227a40 to your computer and use it in GitHub Desktop.
Save JuanDMeGon/98ae594d668504bfdb2d6333d0227a40 to your computer and use it in GitHub Desktop.
Consumes almost any kind of HTTP service using Guzzle
<?php
namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
/**
* Send a request to any service
* @return string
*/
public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
{
$client = new Client([
'base_uri' => $this->baseUri,
]);
if (method_exists($this, 'resolveAuthorization')) {
$this->resolveAuthorization($queryParams, $formParams, $headers);
}
$bodyType = 'form_params';
if ($hasFile) {
$bodyType = 'multipart';
$multipart = [];
foreach ($formParams as $name => $contents) {
$multipart[] = ['name' => $name, 'contents' => $contents];
}
}
$response = $client->request($method, $requestUrl, ['query' => $queryParams, $bodyType => $hasFile ? $multipart : $formParams, 'headers' => $headers]);
$response = $response->getBody()->getContents();
if (method_exists($this, 'decodeResponse')) {
$response = $this->decodeResponse($response);
}
if (method_exists($this, 'checkIfErrorResponse')) {
$this->checkIfErrorResponse($response);
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment