Skip to content

Instantly share code, notes, and snippets.

@TheGeekyM
Last active November 20, 2018 16:03
Show Gist options
  • Save TheGeekyM/3e41e71be7a2f77ec7a39bac9d0e75cb to your computer and use it in GitHub Desktop.
Save TheGeekyM/3e41e71be7a2f77ec7a39bac9d0e75cb to your computer and use it in GitHub Desktop.
RestClient To make communication between services so easy
<?php namespace App\Libs;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
/**
* Class RestClient
*
* @package App\Services
*/
class RestClient
{
/**
* @var array
*/
protected $guzzleParams = [
'timeout' => 40,
'headers' => [],
'json' => []
];
/**
* @var Client
*/
protected $client;
/**
* @var
*/
protected $service;
/**
* @var
*/
protected $action;
/**
* @var
*/
protected $method;
/**
* @var
*/
protected $config;
/**
* @var int
*/
const USER_ID_ANONYMOUS = -1;
/**
* RestClient constructor.
*
* @param Client $client
* @param Request $request
*/
public function __construct(Client $client, Request $request)
{
$this->client = $client;
$this->__injectHeaders($request);
}
/**
* @param bool $debug
*
* @return mixed
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function communicate($debug = FALSE)
{
$this->__prepareConfiguration();
$url = $this->__buildUrl();
$response = $this->client->request($this->method, $url, $this->guzzleParams);
$response = $response->getBody()->getContents();
(!$debug) ?: print_r($response) ;
return json_decode($response);
}
private function __prepareConfiguration()
{
$this->config = config("microservice.{$this->service}");
$this->method = ($this->method) ?: 'GET';
}
/**
* @param Request $request
*/
private function __injectHeaders(Request $request)
{
$this->guzzleParams['headers'] =
[
'X-User' => $request->user()->id ?? self::USER_ID_ANONYMOUS,
'X-Token-Scopes' => $request->user() && !empty($request->user()->token()) ? implode(',', $request->user()->token()->scopes) : '',
'X-Client-Ip' => $request->getClientIp(),
'User-Agent' => $request->header('User-Agent'),
'Content-Type' => $this->config["headers"]['Content-Type'] ?: 'application/json',
'Accept' => $this->config["headers"]['Accept'] ?: 'application/json'
];
}
/**3
* @param $service
*
* @return $this
*/
public function service($service)
{
$this->service = $service;
return $this;
}
/**3
* @param $action
*
* @return $this
*/
public function action($action)
{
$this->action = $action;
return $this;
}
/**
* @param $method
*
* @return $this
*/
public function method($method)
{
$this->method = $method;
return $this;
}
/**
* @param array $data
*
* @return $this
*/
public function params(array $data)
{
$this->guzzleParams['json'] = $data;
return $this;
}
/**
* @return Client
*/
public function getConfig()
{
return $this->config;
}
/**
* @param array $headers
*/
public function setHeaders(array $headers)
{
$this->guzzleParams['headers'] = array_merge($this->getHeaders(), $headers);
}
/**
* @return array
*/
public function getHeaders()
{
return $this->guzzleParams['headers'];
}
/**
* @param $contentType
*
* @return $this
*/
public function contentType($contentType)
{
$this->guzzleParams['headers']['Content-Type'] = $this->guzzleParams['headers']['Content-Type'] ?: $contentType;
return $this;
}
/**
* @param $acceptType
*
* @return $this
*/
public function acceptType($acceptType)
{
$this->guzzleParams['headers']['Accept'] = $acceptType;
return $this;
}
/**
* @param string $body
*
* @return $this
*/
public function setBody($body)
{
$this->guzzleParams['body'] = $body;
return $this;
}
/**
* @param array $files
*
* @return $this
*/
public function setFiles($files)
{
// Get rid of everything else
$this->setHeaders(array_intersect_key($this->getHeaders(), [ 'X-User' => NULL, 'X-Token-Scopes' => NULL ]));
if (isset($this->guzzleParams['body'])) unset($this->guzzleParams['body']);
$this->guzzleParams['timeout'] = 20;
$this->guzzleParams['multipart'] = [];
foreach ($files as $key => $file) {
$this->guzzleParams['multipart'][] = [
'name' => $key,
'contents' => fopen($file->getRealPath(), 'r'),
'filename' => $file->getClientOriginalName()
];
}
return $this;
}
/**
* @return string
*/
private function __buildUrl()
{
return $this->config['host'] . '/' . $this->config['suffix'] . '/' . $this->action;
}
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function dd()
{
$this->communicate(TRUE);
}
}
<?php
// List of microservices behind the gateway
return [
'service_name' => [
'host' => 'http://172.17.0.5',
'suffix' => 'api',
'headers' => [
'Accept' => 'application/vnd.subtype.v3+json',
],
]
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment