1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117:
<?php
namespace Baguette\Mastodon;
use Baguette\Mastodon;
use Baguette\Mastodon\Service\SessionStorage;
use Psr\Http\Message\ResponseInterface;
final class Client
{
const USER_AGENT = 'PhpMastodon/0.0.1(+https://github.com/zonuexe/php-mastodon-client)';
private $instance;
private $client_name;
private $api_http_client;
private $oauth_http_client;
public function __construct($instance, array $options = [])
{
$this->instance = $instance;
if (isset($options['client_name'])) {
$this->client_name = $options['client_name'];
}
}
public function requestAPI($method, $path, array $options, SessionStorage $session)
{
$request_options = $options + $this->getRequestAPIOptions($session);
return $this->getAPIHttpClient()->request($method, $path, $request_options);
}
public function setAPIHttpClient(\GuzzleHttp\Client $client)
{
$this->api_http_client = $client;
}
private function getAPIHttpClient()
{
if (empty($this->api_http_client)) {
$this->api_http_client = new \GuzzleHttp\Client([
'base_uri' => sprintf('%s://%s', $this->getScheme(), $this->getHostname()),
]);
}
return $this->api_http_client;
}
private function getRequestAPIOptions(SessionStorage $session)
{
if (isset($this->client_name)) {
$user_agent = sprintf('%s; %s; %s', self::USER_AGENT, $this->client_name, \GuzzleHttp\default_user_agent());
} else {
$user_agent = sprintf('%s; %s', self::USER_AGENT, \GuzzleHttp\default_user_agent());
}
return [
'headers' => [
'Authorization' => "Bearer {$session->getAccessToken()}",
'User-Agent' => $user_agent,
],
];
}
public function getScheme()
{
return parse_url($this->instance, PHP_URL_SCHEME) ?: 'https';
}
public function getHostname()
{
$host = parse_url($this->instance, PHP_URL_HOST) ?: $this->instance;
$port = parse_url($this->instance, PHP_URL_PORT) ?: false;
return ($port === false) ? $host : "{$host}:{$port}";
}
}