初始化仓库

This commit is contained in:
wangxiaowei
2025-04-22 14:09:52 +08:00
commit 8b100110bb
5155 changed files with 664201 additions and 0 deletions

View File

@ -0,0 +1,451 @@
<?php
namespace AlibabaCloud\Client\Request;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Credentials\Providers\CredentialsProvider;
use AlibabaCloud\Client\Encode;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Filter\ApiFilter;
use AlibabaCloud\Client\Filter\ClientFilter;
use AlibabaCloud\Client\Filter\Filter;
use AlibabaCloud\Client\Filter\HttpFilter;
use AlibabaCloud\Client\Request\Traits\AcsTrait;
use AlibabaCloud\Client\Request\Traits\ClientTrait;
use AlibabaCloud\Client\Request\Traits\DeprecatedTrait;
use AlibabaCloud\Client\Request\Traits\RetryTrait;
use AlibabaCloud\Client\Result\Result;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Traits\ArrayAccessTrait;
use AlibabaCloud\Client\Traits\HttpTrait;
use AlibabaCloud\Client\Traits\ObjectAccessTrait;
use AlibabaCloud\Client\Traits\RegionTrait;
use ArrayAccess;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\ResponseInterface;
/**
* Class Request
*
* @package AlibabaCloud\Client\Request
*
* @method string stringToSign()
* @method string resolveParameter()
*/
abstract class Request implements ArrayAccess
{
use DeprecatedTrait;
use HttpTrait;
use RegionTrait;
use ClientTrait;
use AcsTrait;
use ArrayAccessTrait;
use ObjectAccessTrait;
use RetryTrait;
/**
* Request Connect Timeout
*/
const CONNECT_TIMEOUT = 5;
/**
* Request Timeout
*/
const TIMEOUT = 10;
/**
* @var string HTTP Method
*/
public $method = 'GET';
/**
* @var string
*/
public $format = 'JSON';
/**
* @var string HTTP Scheme
*/
protected $scheme = 'http';
/**
* @var string
*/
public $client;
/**
* @var Uri
*/
public $uri;
/**
* @var array The original parameters of the request.
*/
public $data = [];
/**
* @var array
*/
private $userAgent = [];
/**
* Request constructor.
*
* @param array $options
*
* @throws ClientException
*/
public function __construct(array $options = [])
{
$this->client = CredentialsProvider::getDefaultName();
$this->uri = new Uri();
$this->uri = $this->uri->withScheme($this->scheme);
$this->options['http_errors'] = false;
$this->options['connect_timeout'] = self::CONNECT_TIMEOUT;
$this->options['timeout'] = self::TIMEOUT;
// Turn on debug mode based on environment variable.
if (null !== \AlibabaCloud\Client\env('DEBUG') && strtolower(\AlibabaCloud\Client\env('DEBUG')) === 'sdk') {
$this->options['debug'] = true;
}
// Rewrite configuration if the user has a configuration.
if ($options !== []) {
$this->options($options);
}
}
/**
* @param string $name
* @param string $value
*
* @return $this
* @throws ClientException
*/
public function appendUserAgent($name, $value)
{
$filter_name = Filter::name($name);
if (!UserAgent::isGuarded($filter_name)) {
$this->userAgent[$filter_name] = Filter::value($value);
}
return $this;
}
/**
* @param array $userAgent
*
* @return $this
*/
public function withUserAgent(array $userAgent)
{
$this->userAgent = UserAgent::clean($userAgent);
return $this;
}
/**
* Set Accept format.
*
* @param string $format
*
* @return $this
* @throws ClientException
*/
public function format($format)
{
$this->format = ApiFilter::format($format);
return $this;
}
/**
* @param $contentType
*
* @return $this
* @throws ClientException
*/
public function contentType($contentType)
{
$this->options['headers']['Content-Type'] = HttpFilter::contentType($contentType);
return $this;
}
/**
* @param string $accept
*
* @return $this
* @throws ClientException
*/
public function accept($accept)
{
$this->options['headers']['Accept'] = HttpFilter::accept($accept);
return $this;
}
/**
* Set the request body.
*
* @param string $body
*
* @return $this
* @throws ClientException
*/
public function body($body)
{
$this->options['body'] = HttpFilter::body($body);
return $this;
}
/**
* Set the json as body.
*
* @param array|object $content
*
* @return $this
* @throws ClientException
*/
public function jsonBody($content)
{
if (!\is_array($content) && !\is_object($content)) {
throw new ClientException(
'jsonBody only accepts an array or object',
SDK::INVALID_ARGUMENT
);
}
return $this->body(\json_encode($content));
}
/**
* Set the request scheme.
*
* @param string $scheme
*
* @return $this
* @throws ClientException
*/
public function scheme($scheme)
{
$this->scheme = HttpFilter::scheme($scheme);
$this->uri = $this->uri->withScheme($scheme);
return $this;
}
/**
* Set the request host.
*
* @param string $host
*
* @return $this
* @throws ClientException
*/
public function host($host)
{
$this->uri = $this->uri->withHost(HttpFilter::host($host));
return $this;
}
/**
* @param string $method
*
* @return $this
* @throws ClientException
*/
public function method($method)
{
$this->method = HttpFilter::method($method);
return $this;
}
/**
* @param string $clientName
*
* @return $this
* @throws ClientException
*/
public function client($clientName)
{
$this->client = ClientFilter::clientName($clientName);
return $this;
}
/**
* @return bool
* @throws ClientException
*/
public function isDebug()
{
if (isset($this->options['debug'])) {
return $this->options['debug'] === true;
}
if (isset($this->httpClient()->options['debug'])) {
return $this->httpClient()->options['debug'] === true;
}
return false;
}
/**
* @throws ClientException
* @throws ServerException
*/
public function resolveOption()
{
$this->options['headers']['User-Agent'] = UserAgent::toString($this->userAgent);
$this->cleanQuery();
$this->cleanFormParams();
$this->resolveHost();
$this->resolveParameter();
if (isset($this->options['form_params'])) {
if (function_exists('\GuzzleHttp\Psr7\parse_query')) {
$this->options['form_params'] = \GuzzleHttp\Psr7\parse_query(
Encode::create($this->options['form_params'])->toString()
);
} else {
$this->options['form_params'] = \GuzzleHttp\Psr7\Query::parse(
Encode::create($this->options['form_params'])->toString()
);
}
}
$this->mergeOptionsIntoClient();
}
/**
* @return Result
* @throws ClientException
* @throws ServerException
*/
public function request()
{
$this->resolveOption();
$result = $this->response();
if ($this->shouldServerRetry($result)) {
return $this->request();
}
if (!$result->isSuccess()) {
throw new ServerException($result);
}
return $result;
}
/***
* @return PromiseInterface
* @throws Exception
*/
public function requestAsync()
{
$this->resolveOption();
return self::createClient($this)->requestAsync(
$this->method,
(string)$this->uri,
$this->options
);
}
/**
* @param Request $request
*
* @return Client
* @throws Exception
*/
public static function createClient(Request $request = null)
{
if (AlibabaCloud::hasMock()) {
$stack = HandlerStack::create(AlibabaCloud::getMock());
} else {
$stack = HandlerStack::create();
}
if (AlibabaCloud::isRememberHistory()) {
$stack->push(Middleware::history(AlibabaCloud::referenceHistory()));
}
if (AlibabaCloud::getLogger()) {
$stack->push(Middleware::log(
AlibabaCloud::getLogger(),
new MessageFormatter(AlibabaCloud::getLogFormat())
));
}
$stack->push(Middleware::mapResponse(static function (ResponseInterface $response) use ($request) {
return new Result($response, $request);
}));
self::$config['handler'] = $stack;
return new Client(self::$config);
}
/**
* @throws ClientException
* @throws Exception
*/
private function response()
{
try {
return self::createClient($this)->request(
$this->method,
(string)$this->uri,
$this->options
);
} catch (GuzzleException $exception) {
if ($this->shouldClientRetry($exception)) {
return $this->response();
}
throw new ClientException(
$exception->getMessage(),
SDK::SERVER_UNREACHABLE,
$exception
);
}
}
/**
* Remove redundant Query
*
* @codeCoverageIgnore
*/
private function cleanQuery()
{
if (isset($this->options['query']) && $this->options['query'] === []) {
unset($this->options['query']);
}
}
/**
* Remove redundant Headers
*
* @codeCoverageIgnore
*/
private function cleanFormParams()
{
if (isset($this->options['form_params']) && $this->options['form_params'] === []) {
unset($this->options['form_params']);
}
}
}

View File

@ -0,0 +1,333 @@
<?php
namespace AlibabaCloud\Client\Request;
use Exception;
use AlibabaCloud\Client\Support\Stringy;
use RuntimeException;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Encode;
use AlibabaCloud\Client\Accept;
use AlibabaCloud\Client\Support\Path;
use AlibabaCloud\Client\Support\Sign;
use AlibabaCloud\Client\Filter\Filter;
use AlibabaCloud\Client\Support\Arrays;
use AlibabaCloud\Client\Filter\ApiFilter;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\AccessKeyCredential;
use AlibabaCloud\Client\Credentials\BearerTokenCredential;
use AlibabaCloud\Client\Request\Traits\DeprecatedRoaTrait;
/**
* RESTful ROA Request.
*
* @package AlibabaCloud\Client\Request
* @method setParameter()
*/
class RoaRequest extends Request
{
use DeprecatedRoaTrait;
/**
* @var string
*/
public $pathPattern = '/';
/**
* @var array
*/
public $pathParameters = [];
/**
* @var string
*/
private $dateTimeFormat = "D, d M Y H:i:s \G\M\T";
/**
* Resolve request parameter.
*
* @throws ClientException
* @throws Exception
*/
public function resolveParameter()
{
$this->resolveQuery();
$this->resolveHeaders();
$this->resolveBody();
$this->resolveUri();
$this->resolveSignature();
}
private function resolveQuery()
{
if (!isset($this->options['query']['Version'])) {
$this->options['query']['Version'] = $this->version;
}
}
private function resolveBody()
{
// If the body has already been specified, it will not be resolved.
if (isset($this->options['body'])) {
return;
}
if (!isset($this->options['form_params'])) {
return;
}
// Merge data, compatible with parameters set from constructor.
$params = Arrays::merge(
[
$this->data,
$this->options['form_params']
]
);
$this->encodeBody($params);
unset($this->options['form_params']);
}
/**
* Determine the body format based on the Content-Type and calculate the MD5 value.
*
* @param array $params
*/
private function encodeBody(array $params)
{
if (Stringy::contains($this->options['headers']['Content-Type'], 'application/json', false)) {
$this->options['body'] = json_encode($params);
$this->options['headers']['Content-MD5'] = base64_encode(md5($this->options['body'], true));
return;
}
$this->options['body'] = Encode::create($params)->ksort()->toString();
$this->options['headers']['Content-MD5'] = base64_encode(md5($this->options['body'], true));
$this->options['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
/**
* @throws ClientException
* @throws ServerException
* @throws Exception
*/
private function resolveHeaders()
{
$this->options['headers']['x-acs-version'] = $this->version;
$this->options['headers']['x-acs-region-id'] = $this->realRegionId();
$this->options['headers']['Date'] = gmdate($this->dateTimeFormat);
$signature = $this->httpClient()->getSignature();
$this->options['headers']['x-acs-signature-method'] = $signature->getMethod();
$this->options['headers']['x-acs-signature-nonce'] = Sign::uuid($this->product . $this->action);
$this->options['headers']['x-acs-signature-version'] = $signature->getVersion();
if ($signature->getType()) {
$this->options['headers']['x-acs-signature-type'] = $signature->getType();
}
$this->resolveAccept();
$this->resolveContentType();
$this->resolveSecurityToken();
$this->resolveBearerToken();
}
/**
* @throws ClientException
* @throws Exception
*/
private function resolveSignature()
{
$this->options['headers']['Authorization'] = $this->signature();
}
/**
* If accept is not specified, it is determined by format.
*/
private function resolveAccept()
{
if (!isset($this->options['headers']['Accept'])) {
$this->options['headers']['Accept'] = Accept::create($this->format)->toString();
}
}
/**
* If the Content-Type is not specified, it is determined according to accept.
*/
private function resolveContentType()
{
if (!isset($this->options['headers']['Content-Type'])) {
$this->options['headers']['Content-Type'] = "{$this->options['headers']['Accept']}; charset=utf-8";
}
}
/**
* @throws ClientException
* @throws ServerException
*/
private function resolveSecurityToken()
{
if (!$this->credential() instanceof StsCredential) {
return;
}
if (!$this->credential()->getSecurityToken()) {
return;
}
$this->options['headers']['x-acs-security-token'] = $this->credential()->getSecurityToken();
}
/**
* @throws ClientException
* @throws ServerException
*/
private function resolveBearerToken()
{
if ($this->credential() instanceof BearerTokenCredential) {
$this->options['headers']['x-acs-bearer-token'] = $this->credential()->getBearerToken();
}
}
/**
* Sign the request message.
*
* @return string
* @throws ClientException
* @throws ServerException
*/
private function signature()
{
/**
* @var AccessKeyCredential $credential
*/
$credential = $this->credential();
$access_key_id = $credential->getAccessKeyId();
$signature = $this->httpClient()
->getSignature()
->sign(
$this->stringToSign(),
$credential->getAccessKeySecret()
);
return "acs $access_key_id:$signature";
}
/**
* @return void
*/
private function resolveUri()
{
$path = Path::assign($this->pathPattern, $this->pathParameters);
$this->uri = $this->uri->withPath($path)
->withQuery(
$this->queryString()
);
}
/**
* @return string
*/
public function stringToSign()
{
$request = new \GuzzleHttp\Psr7\Request(
$this->method,
$this->uri,
$this->options['headers']
);
return Sign::roaString($request);
}
/**
* @return bool|string
*/
private function queryString()
{
$query = isset($this->options['query'])
? $this->options['query']
: [];
return Encode::create($query)->ksort()->toString();
}
/**
* Set path parameter by name.
*
* @param string $name
* @param string $value
*
* @return RoaRequest
* @throws ClientException
*/
public function pathParameter($name, $value)
{
Filter::name($name);
if ($value === '') {
throw new ClientException(
'Value cannot be empty',
SDK::INVALID_ARGUMENT
);
}
$this->pathParameters[$name] = $value;
return $this;
}
/**
* Set path pattern.
*
* @param string $pattern
*
* @return self
* @throws ClientException
*/
public function pathPattern($pattern)
{
ApiFilter::pattern($pattern);
$this->pathPattern = $pattern;
return $this;
}
/**
* Magic method for set or get request parameters.
*
* @param string $name
* @param mixed $arguments
*
* @return $this
*/
public function __call($name, $arguments)
{
if (strncmp($name, 'get', 3) === 0) {
$parameter_name = \mb_strcut($name, 3);
return $this->__get($parameter_name);
}
if (strncmp($name, 'with', 4) === 0) {
$parameter_name = \mb_strcut($name, 4);
$this->__set($parameter_name, $arguments[0]);
$this->pathParameters[$parameter_name] = $arguments[0];
return $this;
}
if (strncmp($name, 'set', 3) === 0) {
$parameter_name = \mb_strcut($name, 3);
$with_method = "with$parameter_name";
throw new RuntimeException("Please use $with_method instead of $name");
}
throw new RuntimeException('Call to undefined method ' . __CLASS__ . '::' . $name . '()');
}
}

View File

@ -0,0 +1,203 @@
<?php
namespace AlibabaCloud\Client\Request;
use Exception;
use RuntimeException;
use AlibabaCloud\Client\Support\Sign;
use AlibabaCloud\Client\Support\Arrays;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\BearerTokenCredential;
/**
* RESTful RPC Request.
*
* @package AlibabaCloud\Client\Request
*/
class RpcRequest extends Request
{
/**
* @var string
*/
private $dateTimeFormat = 'Y-m-d\TH:i:s\Z';
/**
* Resolve request parameter.
*
* @throws ClientException
*/
public function resolveParameter()
{
$this->resolveBoolInParameters();
$this->resolveCommonParameters();
$this->repositionParameters();
}
/**
* Convert a Boolean value to a string
*/
private function resolveBoolInParameters()
{
if (isset($this->options['query'])) {
$this->options['query'] = array_map(
static function ($value) {
return self::boolToString($value);
},
$this->options['query']
);
}
}
/**
* Convert a Boolean value to a string.
*
* @param bool|string $value
*
* @return string
*/
public static function boolToString($value)
{
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
return $value;
}
/**
* Resolve Common Parameters.
*
* @throws ClientException
* @throws Exception
*/
private function resolveCommonParameters()
{
$signature = $this->httpClient()->getSignature();
$this->options['query']['RegionId'] = $this->realRegionId();
$this->options['query']['Format'] = $this->format;
$this->options['query']['SignatureMethod'] = $signature->getMethod();
$this->options['query']['SignatureVersion'] = $signature->getVersion();
$this->options['query']['SignatureNonce'] = Sign::uuid($this->product . $this->action);
$this->options['query']['Timestamp'] = gmdate($this->dateTimeFormat);
$this->options['query']['Action'] = $this->action;
if ($this->credential()->getAccessKeyId()) {
$this->options['query']['AccessKeyId'] = $this->credential()->getAccessKeyId();
}
if ($signature->getType()) {
$this->options['query']['SignatureType'] = $signature->getType();
}
if (!isset($this->options['query']['Version'])) {
$this->options['query']['Version'] = $this->version;
}
$this->resolveSecurityToken();
$this->resolveBearerToken();
$this->options['query']['Signature'] = $this->signature();
}
/**
* @throws ClientException
* @throws ServerException
*/
private function resolveSecurityToken()
{
if (!$this->credential() instanceof StsCredential) {
return;
}
if (!$this->credential()->getSecurityToken()) {
return;
}
$this->options['query']['SecurityToken'] = $this->credential()->getSecurityToken();
}
/**
* @throws ClientException
* @throws ServerException
*/
private function resolveBearerToken()
{
if ($this->credential() instanceof BearerTokenCredential) {
$this->options['query']['BearerToken'] = $this->credential()->getBearerToken();
}
}
/**
* Sign the parameters.
*
* @return mixed
* @throws ClientException
* @throws ServerException
*/
private function signature()
{
return $this->httpClient()
->getSignature()
->sign(
$this->stringToSign(),
$this->credential()->getAccessKeySecret() . '&'
);
}
/**
* @return string
*/
public function stringToSign()
{
$query = isset($this->options['query']) ? $this->options['query'] : [];
$form_params = isset($this->options['form_params']) ? $this->options['form_params'] : [];
$parameters = Arrays::merge([$query, $form_params]);
return Sign::rpcString($this->method, $parameters);
}
/**
* Adjust parameter position
*/
private function repositionParameters()
{
if ($this->method === 'POST' || $this->method === 'PUT') {
foreach ($this->options['query'] as $api_key => $api_value) {
$this->options['form_params'][$api_key] = $api_value;
}
unset($this->options['query']);
}
}
/**
* Magic method for set or get request parameters.
*
* @param string $name
* @param mixed $arguments
*
* @return $this
*/
public function __call($name, $arguments)
{
if (strncmp($name, 'get', 3) === 0) {
$parameter_name = \mb_strcut($name, 3);
return $this->__get($parameter_name);
}
if (strncmp($name, 'with', 4) === 0) {
$parameter_name = \mb_strcut($name, 4);
$this->__set($parameter_name, $arguments[0]);
$this->options['query'][$parameter_name] = $arguments[0];
return $this;
}
if (strncmp($name, 'set', 3) === 0) {
$parameter_name = \mb_strcut($name, 3);
$with_method = "with$parameter_name";
throw new RuntimeException("Please use $with_method instead of $name");
}
throw new RuntimeException('Call to undefined method ' . __CLASS__ . '::' . $name . '()');
}
}

View File

@ -0,0 +1,259 @@
<?php
namespace AlibabaCloud\Client\Request\Traits;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Filter\ApiFilter;
use AlibabaCloud\Client\Regions\LocationService;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\SDK;
use GuzzleHttp\Psr7\Uri;
/**
* Trait AcsTrait
*
* @package AlibabaCloud\Client\Request\Traits
* @property Uri $uri
* @mixin Request
*/
trait AcsTrait
{
/**
* @var string
*/
public $version;
/**
* @var string
*/
public $product;
/**
* @var string
*/
public $action;
/**
* @var string
*/
public $serviceCode = '';
/**
* @var string
*/
public $endpointType = 'openAPI';
/**
* @var string|null
*/
public $network = 'public';
/**
* @var array|null
*/
public $endpointMap;
/**
* @var string|null
*/
public $endpointRegional;
/**
* @var string
*/
public $endpointSuffix = '';
/**
* @param string $action
*
* @return $this
* @throws ClientException
*/
public function action($action)
{
$this->action = ApiFilter::action($action);
return $this;
}
/**
* @codeCoverageIgnore
*
* @param string $endpointSuffix
*
* @return AcsTrait
* @throws ClientException
*/
public function endpointSuffix($endpointSuffix)
{
$this->endpointSuffix = ApiFilter::endpointSuffix($endpointSuffix);
return $this;
}
/**
* @param string $network
*/
public function network($network)
{
$this->network = ApiFilter::network($network);
return $this;
}
/**
* @param string $version
*
* @return $this
* @throws ClientException
*/
public function version($version)
{
$this->version = ApiFilter::version($version);
return $this;
}
/**
* @param string $product
*
* @return $this
* @throws ClientException
*/
public function product($product)
{
$this->product = ApiFilter::product($product);
return $this;
}
/**
* @param string $endpointType
*
* @return $this
* @throws ClientException
*/
public function endpointType($endpointType)
{
$this->endpointType = ApiFilter::endpointType($endpointType);
return $this;
}
/**
* @param string $serviceCode
*
* @return $this
* @throws ClientException
*/
public function serviceCode($serviceCode)
{
$this->serviceCode = ApiFilter::serviceCode($serviceCode);
return $this;
}
/**
* Resolve Host.
*
* @throws ClientException
* @throws ServerException
*/
public function resolveHost()
{
// Return if specified
if ($this->uri->getHost() !== 'localhost') {
return;
}
$region_id = $this->realRegionId();
$host = '';
$this->resolveHostWays($host, $region_id);
if (!$host) {
throw new ClientException(
"No host found for {$this->product} in the {$region_id}, you can specify host by host() method. " .
'Like $request->host(\'xxx.xxx.aliyuncs.com\')',
SDK::HOST_NOT_FOUND
);
}
$this->uri = $this->uri->withHost($host);
}
/**
* @param string $host
* @param string $region_id
*
* @throws ClientException
* @throws ServerException
*/
private function resolveHostWays(&$host, $region_id)
{
$host = AlibabaCloud::resolveHostByStatic($this->product, $region_id);
// 1. Find host by map.
if (!$host && $this->network === 'public' && isset($this->endpointMap[$region_id])) {
$host = $this->endpointMap[$region_id];
}
if (!$host) {
$this->hostResolver($host, $region_id);
}
}
/**
* @codeCoverageIgnore
*
* @param string $host
* @param string $region_id
*
* @throws ClientException
* @throws ServerException
*/
private function hostResolver(&$host, $region_id)
{
// 2. Find host by rules.
if ($this->endpointRegional !== null) {
$host = AlibabaCloud::resolveHostByRule($this);
}
// 3. Find in the local array file.
if (!$host) {
$host = AlibabaCloud::resolveHost($this->product, $region_id);
}
// 4. Find in the Location service.
if (!$host && $this->serviceCode) {
$host = LocationService::resolveHost($this);
}
}
/**
* @return string
* @throws ClientException
*/
public function realRegionId()
{
if ($this->regionId !== null) {
return $this->regionId;
}
if ($this->httpClient()->regionId !== null) {
return $this->httpClient()->regionId;
}
if (AlibabaCloud::getDefaultRegionId() !== null) {
return AlibabaCloud::getDefaultRegionId();
}
if ($this->product && AlibabaCloud::isGlobalProduct($this->product)) {
return 'global';
}
throw new ClientException("Missing required 'RegionId' for Request", SDK::INVALID_REGION_ID);
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace AlibabaCloud\Client\Request\Traits;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Support\Arrays;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\AccessKeyCredential;
use AlibabaCloud\Client\Credentials\Requests\AssumeRole;
use AlibabaCloud\Client\Credentials\CredentialsInterface;
use AlibabaCloud\Client\Credentials\BearerTokenCredential;
use AlibabaCloud\Client\Credentials\Providers\CredentialsProvider;
use AlibabaCloud\Client\Credentials\Requests\GenerateSessionAccessKey;
/**
* Trait ClientTrait
*
* @package AlibabaCloud\Client\Request\Traits
*
* @mixin Request
*/
trait ClientTrait
{
/**
* @var array
*/
private static $config = [];
/**
* @param array $config
*/
public static function config(array $config)
{
self::$config = $config;
}
/**
* Return credentials directly if it is an AssumeRole or GenerateSessionAccessKey.
*
* @return AccessKeyCredential|BearerTokenCredential|CredentialsInterface|StsCredential
* @throws ClientException
* @throws ServerException
*/
public function credential()
{
if ($this instanceof AssumeRole || $this instanceof GenerateSessionAccessKey) {
return $this->httpClient()->getCredential();
}
$timeout = isset($this->options['timeout'])
? $this->options['timeout']
: Request::TIMEOUT;
$connectTimeout = isset($this->options['connect_timeout'])
? $this->options['connect_timeout']
: Request::CONNECT_TIMEOUT;
return $this->httpClient()->getSessionCredential($timeout, $connectTimeout);
}
/**
* Get the client based on the request's settings.
*
* @return Client
* @throws ClientException
*/
public function httpClient()
{
if (!AlibabaCloud::all()) {
if (CredentialsProvider::hasCustomChain()) {
CredentialsProvider::customProvider($this->client);
} else {
CredentialsProvider::defaultProvider($this->client);
}
}
return AlibabaCloud::get($this->client);
}
/**
* Merged with the client's options, the same name will be overwritten.
*
* @throws ClientException
*/
public function mergeOptionsIntoClient()
{
$this->options = Arrays::merge(
[
$this->httpClient()->options,
$this->options
]
);
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace AlibabaCloud\Client\Request\Traits;
/**
* @package AlibabaCloud\Client\Request\Traits
* @codeCoverageIgnore
*/
trait DeprecatedRoaTrait
{
/**
* @param $name
* @param $value
*
* @return $this
* @deprecated
* @codeCoverageIgnore
*/
public function putPathParameter($name, $value)
{
return $this->pathParameter($name, $value);
}
/**
* @param $pathPattern
*
* @return $this
* @deprecated
* @codeCoverageIgnore
*/
public function setUriPattern($pathPattern)
{
return $this->pathPattern($pathPattern);
}
/**
* @return string
* @deprecated
* @codeCoverageIgnore
*/
public function getUriPattern()
{
return $this->pathPattern;
}
/**
* @return array
* @deprecated
* @codeCoverageIgnore
*/
public function getPathParameters()
{
return $this->pathParameters;
}
}

View File

@ -0,0 +1,246 @@
<?php
namespace AlibabaCloud\Client\Request\Traits;
use AlibabaCloud\Client\Exception\ClientException;
use RuntimeException;
use AlibabaCloud\Client\Request\Request;
/**
* @package AlibabaCloud\Client\Request\Traits
*
* @mixin Request
*/
trait DeprecatedTrait
{
/**
* @param $content
*
* @return $this
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function setContent($content)
{
return $this->body($content);
}
/**
* @param $method
*
* @return $this
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function setMethod($method)
{
return $this->method($method);
}
/**
* @param $scheme
*
* @return $this
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function setProtocol($scheme)
{
return $this->scheme($scheme);
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getProtocolType()
{
return $this->uri->getScheme();
}
/**
* @param $scheme
*
* @return $this
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function setProtocolType($scheme)
{
return $this->scheme($scheme);
}
/**
* @param $actionName
*
* @return $this
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function setActionName($actionName)
{
return $this->action($actionName);
}
/**
* @param $format
*
* @return $this
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function setAcceptFormat($format)
{
return $this->format($format);
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getProtocol()
{
return $this->uri->getScheme();
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getContent()
{
return isset($this->options['body'])
? $this->options['body']
: null;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getMethod()
{
return $this->method;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getHeaders()
{
return isset($this->options['headers'])
? $this->options['headers']
: [];
}
/**
* @param $headerKey
* @param $headerValue
*
* @return $this
* @deprecated
* @codeCoverageIgnore
*/
public function addHeader($headerKey, $headerValue)
{
$this->options['headers'][$headerKey] = $headerValue;
return $this;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getQueryParameters()
{
return isset($this->options['query'])
? $this->options['query']
: [];
}
/**
* @param $name
* @param $value
*
* @return $this
* @deprecated
* @codeCoverageIgnore
*/
public function setQueryParameters($name, $value)
{
$this->options['query'][$name] = $value;
return $this;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getDomainParameter()
{
return isset($this->options['form_params'])
? $this->options['form_params']
: [];
}
/**
* @param $name
* @param $value
*
* @return $this
* @deprecated
* @codeCoverageIgnore
*/
public function putDomainParameters($name, $value)
{
$this->options['form_params'][$name] = $value;
return $this;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getActionName()
{
return $this->action;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getAcceptFormat()
{
return $this->format;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getLocationEndpointType()
{
return $this->endpointType;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getLocationServiceCode()
{
return $this->serviceCode;
}
}

View File

@ -0,0 +1,149 @@
<?php
namespace AlibabaCloud\Client\Request\Traits;
use Exception;
use AlibabaCloud\Client\Support\Stringy;
use AlibabaCloud\Client\Result\Result;
use AlibabaCloud\Client\Filter\ClientFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Trait RetryTrait
*
* @package AlibabaCloud\Client\Request\Traits
*/
trait RetryTrait
{
/**
* Server Retry Times
*
* @var int
*/
private $serverRetry = 0;
/**
* Server Retry Strings
*
* @var string[]
*/
private $serverRetryStrings = [];
/**
* Server Retry Codes
*
* @var int[]
*/
private $serverRetryStatusCodes = [];
/**
* Client Retry Times
*
* @var int
*/
private $clientRetry = 0;
/**
* Client Retry Strings
*
* @var string[]
*/
private $clientRetryStrings = [];
/**
* Client Retry Codes
*
* @var int[]
*/
private $clientRetryStatusCodes = [];
/**
* @param int $times
* @param array $strings
* @param array $statusCodes
*
* @return $this
* @throws ClientException
*/
public function retryByServer($times, array $strings, array $statusCodes = [])
{
$this->serverRetry = ClientFilter::retry($times);
$this->serverRetryStrings = $strings;
$this->serverRetryStatusCodes = $statusCodes;
return $this;
}
/**
* @param int $times
* @param array $strings
* @param array $codes
*
* @return $this
* @throws ClientException
*/
public function retryByClient($times, array $strings, array $codes = [])
{
$this->clientRetry = ClientFilter::retry($times);
$this->clientRetryStrings = $strings;
$this->clientRetryStatusCodes = $codes;
return $this;
}
/**
* @param Result $result
*
* @return bool
*/
private function shouldServerRetry(Result $result)
{
if ($this->serverRetry <= 0) {
return false;
}
if (in_array($result->getStatusCode(), $this->serverRetryStatusCodes)) {
$this->serverRetry--;
return true;
}
foreach ($this->serverRetryStrings as $message) {
if (Stringy::contains($result->getBody(), $message)) {
$this->serverRetry--;
return true;
}
}
return false;
}
/**
* @param Exception $exception
*
* @return bool
*/
private function shouldClientRetry(Exception $exception)
{
if ($this->clientRetry <= 0) {
return false;
}
if (in_array($exception->getCode(), $this->clientRetryStatusCodes, true)) {
$this->clientRetry--;
return true;
}
foreach ($this->clientRetryStrings as $message) {
if (Stringy::contains($exception->getMessage(), $message)) {
$this->clientRetry--;
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,142 @@
<?php
namespace AlibabaCloud\Client\Request;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Filter\Filter;
use AlibabaCloud\Client\Support\Arrays;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class UserAgent
*
* @package AlibabaCloud\Client\Request
*/
class UserAgent
{
/**
* @var array
*/
private static $userAgent = [];
/**
* @var array
*/
private static $guard = [
'client',
'php',
];
/**
* @param array $append
*
* @return string
*/
public static function toString(array $append = [])
{
self::defaultFields();
$os = \PHP_OS;
$osVersion = php_uname('r');
$osMode = php_uname('m');
$userAgent = "AlibabaCloud ($os $osVersion; $osMode) ";
$newUserAgent = [];
$append = self::clean($append);
$append = Arrays::merge(
[
self::$userAgent,
$append,
]
);
foreach ($append as $key => $value) {
if ($value === null) {
$newUserAgent[] = $key;
continue;
}
$newUserAgent[] = "$key/$value";
}
return $userAgent . \implode(' ', $newUserAgent);
}
/**
* UserAgent constructor.
*/
private static function defaultFields()
{
if (self::$userAgent === []) {
self::$userAgent = [
'Client' => AlibabaCloud::VERSION,
'PHP' => \PHP_VERSION,
];
}
}
/**
* @param array $append
*
* @return array
*/
public static function clean(array $append)
{
foreach ($append as $key => $value) {
if (self::isGuarded($key)) {
unset($append[$key]);
continue;
}
}
return $append;
}
/**
* @param $name
*
* @return bool
*/
public static function isGuarded($name)
{
return in_array(strtolower($name), self::$guard, true);
}
/**
* set User Agent of Alibaba Cloud.
*
* @param string $name
* @param string $value
*
* @throws ClientException
*/
public static function append($name, $value)
{
Filter::name($name);
Filter::value($value);
self::defaultFields();
if (!self::isGuarded($name)) {
self::$userAgent[$name] = $value;
}
}
/**
* @param array $userAgent
*/
public static function with(array $userAgent)
{
self::$userAgent = self::clean($userAgent);
}
/**
* Clear all of the User Agent.
*/
public static function clear()
{
self::$userAgent = [];
}
}