Skip to content

Instantly share code, notes, and snippets.

@Sekaiichi
Created November 18, 2021 11:17
Show Gist options
  • Save Sekaiichi/3e4bbb5e2d3fbdeb649be2bf4020c348 to your computer and use it in GitHub Desktop.
Save Sekaiichi/3e4bbb5e2d3fbdeb649be2bf4020c348 to your computer and use it in GitHub Desktop.
<?php
namespace App\Modules\Integration;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7\Response;
use Log;
abstract class ARequest
{
/**
* write info log
* @var boolean
*/
protected $writeLog = false;
/**
* @var string
*/
protected $logChannelName;
/**
* @var Response
*/
protected $response;
/**
* @var string
*/
protected $baseURI;
/**
* @var string
*/
protected $route;
/**
* @var string
*/
protected $method;
/**
* @var array
*/
protected $options = [];
abstract public function perform();
protected $responseContents;
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*/
protected function send(): void
{
$httpClient = new Client(['base_uri' => $this->baseURI]);
try {
$this->response = $httpClient->request($this->method, $this->route, $this->options);
$this->setResponseContents($this->response);
if ($this->writeLog) {
Log::channel($this->logChannelName)->info($this->responseContents);
}
} catch (ClientException $clientException) {
$this->logError($clientException);
} catch (ServerException $serverException) {
$this->logError($serverException);
} catch (BadResponseException $badResponseException) {
$this->logError($badResponseException);
} catch (RequestException $requestException) {
$this->logError($requestException);
}
}
/**
* @param bool $enable
*/
public function enableLog(bool $enable = true): void
{
$this->writeLog = $enable;
}
/**
* @param Response $response
*/
protected function setResponseContents(Response $response): void
{
$this->responseContents = $response->getBody()->getContents();
}
public function getResponseContents()
{
return json_decode($this->responseContents, true);
}
/**
* @return Response $response
*/
public function getResponse(): Response
{
return $this->response;
}
/**
* @param string $baseURI
*/
public function setBaseURI(string $baseURI): void
{
$this->baseURI = $baseURI;
}
/**
* @param string $route
*/
public function setRoute(string $route): void
{
$this->route = $route;
}
/**
* @param array $options
*/
public function setOptions(array $options): void
{
$this->options = $options;
}
/**
* @param string $logChannelName
*/
public function setLogChannelName($logChannelName): void
{
$this->logChannelName = $logChannelName;
}
/**
* @param $exception
*/
protected function logError($exception)
{
Log::channel($this->logChannelName)->error($exception);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment