mobilebackendgateway/app/Traits/ConsumesExternalService.php

63 lines
2.0 KiB
PHP
Executable File

<?php
namespace App\Traits;
use GuzzleHttp\Client;
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;
}
$contentType = $headers['content-type'][0];
if(strpos($contentType, 'multipart/form-data') !== false){
// $headers['content-type'] = 'multipart/form-data';
// dd($body);
$response = $client->request($method ,$requestUrl , ['multipart' => $this->bodyToMultipart($body),'headers' => $headers]);
}else{
$response = $client->request($method , $requestUrl , ['json'=> $body ,'form_params' => $formParams , 'headers' => $headers]);
}
return $response->getBody()->getContents();
}
private function bodyToMultipart(array $body){
$multipart = [];
foreach ($body as $key => $value){
if( $value instanceof UploadedFile){
array_push($multipart , [
'name' => $key,
'contents' => file_get_contents($value->getRealPath()),
'mine-type'=>$value->getMimeType(),
'filename' => $value->getClientOriginalName(),
// 'contents' => fopen( './test.txt', 'r' ),
'headers' => [ 'Content-type' => 'multipart/form-data']
]);
}else{
array_push($multipart , [
'name' => $key,
'contents' => $value,
]);
}
}
return $multipart;
}
}