mobilebackendgateway/app/Traits/ConsumesExternalService.php

79 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace App\Traits;
2020-06-20 15:09:37 +00:00
use GuzzleHttp\Client;
2020-06-20 15:09:37 +00:00
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\MultipartStream;
2020-06-11 13:44:34 +00:00
use Illuminate\Http\UploadedFile;
trait ConsumesExternalService
{
/**
* Envoie une requete a un service
* @param $method
* @param $requestUrl
* @param array $body
* @param array $formParams
* @param array $headers
* @return string
*/
2020-04-28 17:35:28 +00:00
public function perfomRequest($method, $requestUrl, $body = [], $headers = [], $formParams = [])
{
2020-06-20 15:09:37 +00:00
$client = new Client([
'base_uri' => $this->baseUri,
]);
2020-06-20 15:09:37 +00:00
if (isset($this->key)) {
unset($headers['authorization']);
$headers['Authorization'] = $this->key;
}
$response = $client->request($method, $requestUrl, ['json' => $body, 'form_params' => $formParams, 'headers' => $headers]);
return $response->getBody()->getContents();
}
public function perfomRequestWithFiles($method, $requestUrl, $body = [], $headers = [], $formParams = [])
{
if (isset($this->key)) {
2020-04-28 17:35:28 +00:00
unset($headers['authorization']);
2020-04-15 23:09:27 +00:00
$headers['Authorization'] = $this->key;
2020-06-11 13:44:34 +00:00
}
2020-06-20 15:09:37 +00:00
$client = new Client([
'base_uri' => $this->baseUri,
'headers' => $headers
]);
$request = new Request($method, $requestUrl, [], new MultipartStream($this->bodyToMultipart($body)));
$response = $client->send($request);
return $response->getBody()->getContents();
}
2020-06-11 13:44:34 +00:00
2020-06-20 15:09:37 +00:00
private function bodyToMultipart(array $body)
{
2020-06-11 13:44:34 +00:00
$multipart = [];
2020-06-20 15:09:37 +00:00
foreach ($body as $key => $value) {
if ($value instanceof UploadedFile) {
array_push($multipart, [
'name' => $key,
2020-06-11 13:44:34 +00:00
'contents' => file_get_contents($value->getRealPath()),
2020-06-20 15:09:37 +00:00
'mine-type' => $value->getMimeType(),
2020-06-11 13:44:34 +00:00
'filename' => $value->getClientOriginalName(),
2020-06-20 15:09:37 +00:00
// 'headers' => [ 'Content-type' => 'application/octet-stream']
// 'Content-type' => 'multipart/form-data',
2020-06-11 13:44:34 +00:00
]);
2020-06-20 15:09:37 +00:00
} else {
array_push($multipart, [
'name' => $key,
2020-06-11 13:44:34 +00:00
'contents' => $value,
]);
}
}
return $multipart;
}
}