Created
March 21, 2019 04:29
-
-
Save JuanDMeGon/98ae594d668504bfdb2d6333d0227a40 to your computer and use it in GitHub Desktop.
Consumes almost any kind of HTTP service using Guzzle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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