92 lines
2.6 KiB
PHP
Executable File
92 lines
2.6 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\Psr7\Request;
|
|
use GuzzleHttp\Psr7\MultipartStream;
|
|
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
|
|
*/
|
|
public function perfomRequest($method, $requestUrl, $body = [], $headers = [], $formParams = [])
|
|
{
|
|
$client = new Client([
|
|
'base_uri' => $this->baseUri,
|
|
]);
|
|
|
|
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)) {
|
|
unset($headers['authorization']);
|
|
$headers['Authorization'] = $this->key;
|
|
}
|
|
|
|
$headers['Content-Type'] = 'multipart/form-data';
|
|
|
|
$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();
|
|
}
|
|
|
|
private function bodyToMultipart(array $body)
|
|
{
|
|
$multipart = [];
|
|
foreach ($body as $key => $value) {
|
|
if(is_array($value)){
|
|
foreach ($value as $v){
|
|
$multipart[] = $this->convertToMultiFormArray($key . '[]', $v);
|
|
}
|
|
}else{
|
|
$multipart[] = $this->convertToMultiFormArray($key, $value);
|
|
}
|
|
}
|
|
return $multipart;
|
|
}
|
|
|
|
private function convertToMultiFormArray($key , $value): array
|
|
{
|
|
if ($value instanceof UploadedFile) {
|
|
return [
|
|
'name' => $key,
|
|
'contents' => file_get_contents($value->getRealPath()),
|
|
'mine-type' => $value->getMimeType(),
|
|
'filename' => $value->getClientOriginalName(),
|
|
// 'headers' => [ 'Content-type' => 'application/octet-stream']
|
|
// 'Content-type' => 'multipart/form-data',
|
|
];
|
|
} else {
|
|
return[
|
|
'name' => $key,
|
|
'contents' => $value,
|
|
];
|
|
}
|
|
}
|
|
}
|