nineskeletor/src/Service/ApiService.php

112 lines
3.1 KiB
PHP
Executable File

<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class ApiService
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function setbody(array $array)
{
return \Unirest\Request\Body::json($array);
}
public function run($method, $url, $query, $header = null, $content = 'json')
{
// Entete
$headerini = null;
switch ($content) {
case 'json':
$headerini = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
if ($query) {
$query = \Unirest\Request\Body::json($query);
}
break;
case 'form':
$headerini = [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
];
if ($query) {
$query = \Unirest\Request\Body::form($query);
}
break;
}
if ($header) {
$header = array_merge($headerini, $header);
} else {
$header = $headerini;
}
// Paramétrage unirest
\Unirest\Request::verifyPeer(false);
\Unirest\Request::verifyHost(false);
\Unirest\Request::timeout(5);
// Déclaration du proxy
$proxyUse = $this->params->get('proxyUse');
if ($proxyUse) {
$proxyHost = $this->params->get('proxyHost');
$proxyPort = $this->params->get('proxyPort');
\Unirest\Request::proxy($proxyHost, $proxyPort, CURLPROXY_HTTP, true);
}
$response = false;
switch ($method) {
case 'POST':
try {
$response = \Unirest\Request::post($url, $header, $query);
} catch (\Exception $e) {
return false;
}
break;
case 'GET':
try {
$response = @\Unirest\Request::get($url, $header, $query);
} catch (\Exception $e) {
return false;
}
break;
case 'PUT':
try {
$response = \Unirest\Request::put($url, $header, $query);
} catch (\Exception $e) {
return false;
}
break;
case 'DELETE':
try {
$response = \Unirest\Request::delete($url, $header, $query);
} catch (\Exception $e) {
return false;
}
break;
case 'PATCH':
try {
$response = \Unirest\Request::patch($url, $header, $query);
} catch (\Exception $e) {
return false;
}
break;
}
return $response;
}
}