reedaw测试版多语言

This commit is contained in:
tiansf 2025-04-25 19:02:06 +08:00
parent 075de75020
commit 3791828a0b
249 changed files with 28250 additions and 213 deletions

View File

@ -88,7 +88,7 @@ class Card extends Base{
// 详细卡片信息
// $data = ['id'=>'2']
public function card_data_detailed($data=['aud_id'=>'144']){
public function card_data_detailed($data=['aud_id'=>'61']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -543,7 +543,9 @@ class Card extends Base{
"list"=>[],
"key_name"=>"weight",
"desc"=>"反映和衡量一个人健康状况的重要标志之一",
"offset"=>"0"
"offset"=>"0",
"standard_val"=>"",
"difference_val"=>"",
],
[
"name"=>"身高",
@ -554,7 +556,9 @@ class Card extends Base{
"list"=>[],
"key_name"=>"height",
"desc"=>"人体纵向部分的长度,源于人体的纵向生长,受遗传因素的影响较大",
"offset"=>"0"
"offset"=>"0",
"standard_val"=>"",
"difference_val"=>"",
],
[
"name"=>"BMI",
@ -565,7 +569,9 @@ class Card extends Base{
"list"=>[],
"key_name"=>"bmi",
"desc"=>"BMI是身体质量指数,是目前国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。",
"offset"=>"0"
"offset"=>"0",
"standard_val"=>"",
"difference_val"=>"",
],
],
'bottom_list' => [],
@ -660,12 +666,13 @@ class Card extends Base{
// 加入曲线板块底部的减肥计划数据end
// 添加头围数据如果有的话start
if($head_circumference !== false && $this->calculate_age($result[0]['birthday']) < 3){
if($head_circumference['level'] == '异常' || $head_circumference['value'] == 0){
$offset = 0;
}else{
$offset = $cardparts->calculate_landing_point($head_circumference['list2'],$head_circumference['value'],$head_circumference['level']);
}
array_push($result_end['top_list'],[
$touwei_array = [
'name'=>'头围',
'value'=>$head_circumference['value'],
'unit'=>'CM',
@ -675,9 +682,56 @@ class Card extends Base{
'key_name'=>'head_circumference',
'desc'=>'头围是指绕头部一周的最大长度,头围的大小与脑的发育密切相关',
'offset'=>$offset
]);
];
$touwei_data = $this->touwei_temporary_use($result[0]['birthday'],$result[0]['gender']);
if(count($touwei_data)){
$touwei_array['standard_val'] = $touwei_data['middle'];
$touwei_array['difference_val'] = bcsub($touwei_array['value'],$touwei_data['middle'],2);
}else{
$touwei_array['standard_val'] = '';
$touwei_array['difference_val'] = '';
}
array_push($result_end['top_list'],$touwei_array);
}
// 添加头围数据如果有的话end
// 这段业务处理可以删除是做的临时的假的start
$biaozhun_val = $this->body_temporary_use($result[0]['birthday'],$result[0]['gender']);
// dump($biaozhun_val);
// $biaozhun_val_weight = 50;
// $biaozhun_val_height = 170;
// $biaozhun_val_bmi = 22;
foreach ($result_end['top_list'] as $key => $value) {
if($value['key_name'] == 'weight'){
if($biaozhun_val['weight'] == ''){
$result_end['top_list'][$key]['standard_val'] = '';
$result_end['top_list'][$key]['difference_val'] = '';
}else{
$result_end['top_list'][$key]['standard_val'] = $biaozhun_val['weight'];
$result_end['top_list'][$key]['difference_val'] = bcsub($value['value'],$biaozhun_val['weight'],2);
}
}else if($value['key_name'] == 'height'){
if($biaozhun_val['height'] == ''){
$result_end['top_list'][$key]['standard_val'] = '';
$result_end['top_list'][$key]['difference_val'] = '';
}else{
$result_end['top_list'][$key]['standard_val'] = $biaozhun_val['height'];
$result_end['top_list'][$key]['difference_val'] = bcsub($value['value'],$biaozhun_val['height'],2);
}
}else if($value['key_name'] == 'bmi'){
if($biaozhun_val['bmi'] == ''){
$result_end['top_list'][$key]['standard_val'] = '';
$result_end['top_list'][$key]['difference_val'] = '';
}else{
$result_end['top_list'][$key]['standard_val'] = $biaozhun_val['bmi'];
$result_end['top_list'][$key]['difference_val'] = bcsub($value['value'],$biaozhun_val['bmi'],2);
}
}
}
// 这段业务处理可以删除是做的临时的假的end
return $this->msg($result_end);
}
@ -1253,6 +1307,174 @@ class Card extends Base{
################################################################其他接口################################################################
################################################################其他接口################################################################
public function body_temporary_use($age,$gender){
$return_data = [
'height'=>'',
'weight'=>'',
'bmi'=>'',
];
if(!in_array($gender,['1','2'])){
return $return_data;
}
$age_m = $this->calculateAgeInMonthsWithPrecision($age);
if($age_m < 228){//月龄小于19岁
// dump($age_m);
// $height_date = Db::table('ws_height')->where("age <= $age_m and gender = '$gender'")->order('age desc')->limit(1)->field('middle')->select();
$height_date = Db::query("select * from ws_height where age <= $age_m and gender = '$gender' order by age desc");
// $weight_date = Db::table('ws_weight')->where("age <= $month_num and Sex = '$gender'")->order('age desc')->limit(1)->field('middle')->select();
$weight_date = Db::query("select * from ws_weight where age <= $age_m and gender = '$gender' order by age desc");
// $bmi_date = Db::table('ws_bmi')->where("age <= $month_num and Sex = '$gender'")->order('age desc')->limit(1)->field('middle')->select();
$bmi_date = Db::query("select * from ws_bmi where age <= $age_m and gender = '$gender' order by age desc");
$return_data = array(
'height' => $height_date[0]['middle'],
'weight' => $weight_date[0]['middle'],
'bmi' => $bmi_date[0]['middle'],
);
}else{
$bmi_data = [
'1' => [ // 男性
[
'age' => ['min' => 216, 'max' => 299], // 18-24岁216-299月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '20.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '20.5', 'max_val' => '23.9', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.0', 'max_val' => '27.9', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.0', 'max_val' => '31.9', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.0', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 300, 'max' => 419], // 25-34岁300-419月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '20.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.0', 'max_val' => '24.4', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.5', 'max_val' => '28.4', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.5', 'max_val' => '32.4', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.5', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 420, 'max' => 539], // 35-44岁420-539月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '21.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.5', 'max_val' => '25.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '25.1', 'max_val' => '29.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '29.1', 'max_val' => '33.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '33.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 540, 'max' => 719], // 45-59岁540-719月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '21.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '22.0', 'max_val' => '25.5', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '25.6', 'max_val' => '29.5', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '29.6', 'max_val' => '33.5', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '33.6', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 720, 'max' => '99999'], // ≥60岁720+月龄)
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '22.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '22.5', 'max_val' => '26.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '26.1', 'max_val' => '29.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '29.1', 'max_val' => '33.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '33.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
]
],
'2' => [ // 女性
[
'age' => ['min' => 216, 'max' => 299], // 18-24岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '19.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '20.0', 'max_val' => '22.9', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '23.0', 'max_val' => '26.9', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '27.0', 'max_val' => '30.9', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '31.0', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 300, 'max' => 419], // 25-34岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '20.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '20.5', 'max_val' => '23.4', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '23.5', 'max_val' => '27.4', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '27.5', 'max_val' => '31.4', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '31.5', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 420, 'max' => 539], // 35-44岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '20.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.0', 'max_val' => '24.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.1', 'max_val' => '28.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.1', 'max_val' => '32.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 540, 'max' => 719], // 45-59岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '21.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.5', 'max_val' => '24.5', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.6', 'max_val' => '28.5', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.6', 'max_val' => '32.5', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.6', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 720, 'max' => 99999], // ≥60岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '21.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '22.0', 'max_val' => '25.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '25.1', 'max_val' => '28.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.1', 'max_val' => '32.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
]
]
];
foreach ($bmi_data[$gender] as $group) {
if ($age_m >= $group['age']['min'] && $age_m <= $group['age']['max']) {
$return_data['bmi'] = bcdiv(bcadd($group['list'][2]['min_val'],$group['list'][2]['max_val'],20),2,1);
}
}
}
return $return_data;
}
public function touwei_temporary_use($age,$gender){
$return_data = [
];
if(!in_array($gender,['1','2'])){
return $return_data;
}
$age_m = $this->calculateAgeInMonthsWithPrecision($age);
if($age_m <= 36){
// $touwei_date = Db::table('ws_touwei')->where("age <= $age_m and gender = '$gender'")->order('age desc')->limit(1)->field('middle')->fetchSql(true)->select();
$touwei_date = Db::query("select * from ws_touwei where age <= $age_m and gender = '$gender' order by age desc");
$return_data = $touwei_date[0];
}
return $return_data;
}

View File

@ -103,7 +103,7 @@ class Index extends Base{
// 检测版本及判断是否登录失效
public function login_invalid_version($data = ['token'=>'2d4ea9b3f44b169ddf64b2f3d2725ceb']){
try {
// try {
// 获取客户端IP
$ip = request()->ip();
// 调用IP识别方法
@ -150,25 +150,25 @@ class Index extends Base{
$language_data = $this->pd_language($user_token_state['language'],$isSupportedLanguage,$language);
if($user_token_state['state'] === false){
return $this->msg(-1,'未登录',['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->language_country]);
return $this->msg(-1,'未登录',['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->process_Language()]);
}else{
return $this->msg(['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->language_country]);
return $this->msg(['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->process_Language()]);
}
} catch (\Exception $e) {
// 捕获异常
$logContent["flie"] = $e->getFile();
$logContent["line"] = $e->getLine();
$logContent['all_content'] = "异常信息:\n";
$logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
$logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
$logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
$logContent['all_content'] .= "方法: " . __METHOD__ . "\n";
$logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
$logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
$this->record_api_log($data, $logContent, null);
return $this->msg(99999);
}
// } catch (\Exception $e) {
// // 捕获异常
// $logContent["flie"] = $e->getFile();
// $logContent["line"] = $e->getLine();
// $logContent['all_content'] = "异常信息:\n";
// $logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
// $logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
// $logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
// $logContent['all_content'] .= "方法: " . __METHOD__ . "\n";
// $logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
// $logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
// $this->record_api_log($data, $logContent, null);
// return $this->msg(99999);
// }
}
// 添加IP信息获取方法
@ -185,7 +185,7 @@ class Index extends Base{
}
}
public function set_language_country($data = ['token'=>'caadd1be045a65f30b92aa805f1de54a','language'=>'zh']){
public function set_language_country($data = ['token'=>'caadd1be045a65f30b92aa805f1de54a','language'=>'zh-Hans']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -1155,6 +1155,16 @@ class Index extends Base{
return $result;
}
// 处理返回的语言数组
public function process_Language(){
$temporary_arr = [];
foreach ($this->language_country as $key => $value) {
array_push($temporary_arr,['key'=>$key,'value'=>$value]);
}
return $temporary_arr;
}

View File

@ -413,6 +413,7 @@ class Login extends Base{
* $type验证类型是注册用还是其他用途 字符串 默认register注册register、login、reset_password
* $road是手机还是邮箱还是其他 字符串 默认tel或email
*/
//18736019909
public function send_phone_email_code($data = ['data'=>'18736019909']){
if(count(input('post.')) > 0){
@ -428,8 +429,12 @@ class Login extends Base{
$num = mt_rand(100000,999999);
if (preg_match('/^\d{11}$/', $data['data'])) {
// 本公司短信
$result = $this->send_tel_code($data['data'],$num);
// return $this->msg($result);
// 阿里云短信
// $sms_all = new Smsaliyun;
// $result = $sms_all->send_sms($data['data'],$num);
// dump($result);
$road = 'tel';
}else{
$result = $this->send_email_code([$data['data']],['title'=>'体测APP验证码','from_user_name'=>'体测APP','content'=>$num]);
@ -473,7 +478,6 @@ class Login extends Base{
// 'content' => '【小白秤】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
// 'content' => '【品传科技】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
// 'content' => '【巨天】您好,欢迎使用巨天,您的手机验证码是:'.$code.',验证码一分钟内有效,若非本人操作,请忽略!'
);
$postData = json_encode($postData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
@ -481,6 +485,7 @@ class Login extends Base{
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 发送请求并获取响应
$response = curl_exec($ch);
// dump($response);
// 检查是否有错误发生
if (curl_errno($ch)) {
$error_message = curl_error($ch);
@ -489,7 +494,7 @@ class Login extends Base{
// 关闭cURL会话
curl_close($ch);
// 处理响应
// dump(json_decode($response,true));
if ($response) {
return json_decode($response,true);
} else {

View File

@ -112,7 +112,7 @@ class Pagingcontrast extends Base{
}
// 获取详细历史数据信息(包含身体、跳绳、肺活量)
public function get_all_record_detailed_information($data = ['id'=>'36','type'=>'8','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
public function get_all_record_detailed_information($data = ['id'=>'3802','type'=>'2','aan_id'=>'1841','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -458,6 +458,8 @@ class Pagingcontrast extends Base{
// $for_data_arr = ['height'=>['身高','cm'],'weight'=>['体重','kg'],'age'=>['年龄','岁'],'bmi'=>['BMI','']];
// }
$result_data = [];
// dump($result);
// dump($for_data_arr);
foreach ($for_data_arr as $key => $value) {
$temporary_arr['key_name'] = $key;
$temporary_arr['name'] = $value[0];
@ -471,10 +473,16 @@ class Pagingcontrast extends Base{
$temporary_arr['value'] = explode(',',$result[$key])[0];
}
}else{
if($key == 'un_fat_w_weight'){
$temporary_arr['value'] = bcsub(explode(',',$result['weight'])[0],explode(',',$result['fat_w'])[0],2);
}else{
$temporary_arr['value'] = explode(',',$result[$key])[0];
// dump($key);
// dump($result[$key]);
if(array_key_exists($key,$result)){
$temporary_arr['value'] = explode(',',$result[$key])[0];
}
}
}

View File

@ -0,0 +1,84 @@
<?php
namespace app\app\controller;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Controller;
class Smsaliyun extends Controller
{
// 阿里云短信配置
private $smsConfig = [
'accessKeyId' => 'LTAI5tQCdWe9Epir3ydXWbzp',
'accessKeySecret' => 'JKLzF0b5AXw2ajhwtem2fhPSUZVOZ5',
'signName' => '郑州巨天信息',
'templateCode' => 'SMS_484085215',
'regionId' => 'cn-hangzhou'
];
/**
* 发送短信接口
* @param string $phone 手机号
* @param string $code 验证码
*/
public function send_sms($phone='18530934717', $code='0932')
{
try {
// 初始化阿里云客户端
AlibabaCloud::accessKeyClient(
$this->smsConfig['accessKeyId'],
$this->smsConfig['accessKeySecret']
)
->regionId($this->smsConfig['regionId'])
->asDefaultClient();
// 发送短信请求
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => $this->smsConfig['regionId'],
'PhoneNumbers' => $phone,
'SignName' => $this->smsConfig['signName'],
'TemplateCode' => $this->smsConfig['templateCode'],
'TemplateParam' => json_encode(['code' => $code]),
],
])
->request();
$result = $result->toArray();
if ($result['Code'] == 'OK') {
return [
'code' => 0,
'message' => '短信发送成功',
'data' => $result
];
} else {
return [
'code' => 99999,
'message' => $result['Message'],
'error' => $result
];
}
} catch (ClientException $e) {
return [
'code' => 99998,
'message' => '客户端异常: ' . $e->getErrorMessage(),
'error' => $e->getMessage()
];
} catch (ServerException $e) {
return [
'code' => 99997,
'message' => '服务端异常: ' . $e->getErrorMessage(),
'error' => $e->getMessage()
];
}
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Controller;
use think\Db;
@ -11,12 +11,12 @@ use PHPMailer\PHPMailer\PHPMailer;
class Base extends Controller{
protected $base_use_db_name = [
'1'=>'app_data_log',
'2'=>'app_card_data',
'3'=>'app_user_data',
'4'=>'pc_vitalcapacity_standard',
'5'=>'admin_estimate',
'6'=>'app_account_number'
'1'=>'app_data_log_copy1',
'2'=>'app_card_data_copy1',
'3'=>'app_user_data_copy1',
'4'=>'pc_vitalcapacity_standard_copy1',
'5'=>'admin_estimate_copy1',
'6'=>'app_account_number_copy1'
];
protected $ceshiyong_token = ['57bd45e3a963b372ea2d873e4bd8d1f8','e0966788d02cc93290d9d674921d9715'];

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Controller;

View File

@ -1,25 +1,26 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
use app\app\controller\Calculatebody;
use app\app\controller\Cardparts;
use app\testapp\controller\Calculatebody;
use app\testapp\controller\Cardparts;
class Card extends Base{
protected $color = ['#FF5656','#FFAB00','#5AD06D','#6492F6','#3967D6'];
protected $card_use_db_name = [
'1'=>'app_card_body_data',
'2'=>'app_user_data',
'3'=>'pc_bmistand',
'4'=>'pc_heightstand',
'5'=>'pc_weightstand',
'6'=>'pc_childrenprescription',
'7'=>'pc_childprescriptionbyage',
'8'=>'pc_heightstand',
'9'=>'pc_weightstand',
'10'=>'pc_bmistand',
'1'=>'app_card_body_data_copy1',
'2'=>'app_user_data_copy1',
'3'=>'pc_bmistand_copy1',
'4'=>'pc_heightstand_copy1',
'5'=>'pc_weightstand_copy1',
'6'=>'pc_childrenprescription_copy1',
'7'=>'pc_childprescriptionbyage_copy1',
'8'=>'pc_heightstand_copy1',
'9'=>'pc_weightstand_copy1',
'10'=>'pc_bmistand_copy1',
'11'=>'app_account_number_copy1',
];
protected $age_limit = 16;
protected $unit_symbol = ['score'=>'分','height'=>'CM','weight'=>'公斤','bmi'=>'','fat_r'=>'%','fat_w'=>'kg','muscle'=>'%','muscleval'=>'kg','water'=>'kg','bone'=>'kg','protein'=>'%','proteinval'=>'kg','kcal'=>'kcal','visceral'=>'','sfr'=>'%',];
@ -89,7 +90,7 @@ class Card extends Base{
// 详细卡片信息
// $data = ['id'=>'2']
public function card_data_detailed($data=['aud_id'=>'144']){
try {
// try {
// 你的业务逻辑
if(count(input('post.')) > 0){
$data = input('post.');
@ -102,22 +103,21 @@ class Card extends Base{
}
// $return_data;
$return_data = $this->get_user_body_data($data);
// $language_data = new Language();
// $return_data = $language_data->handling_languages_from_multiple_countries('en', $return_data->getData());
return $return_data;
} catch (\Exception $e) {
// 捕获异常
$logContent["flie"] = $e->getFile();
$logContent["line"] = $e->getLine();
$logContent['all_content'] = "异常信息:\n";
$logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
$logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
$logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
$logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
$logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
$this->record_api_log($data, $logContent, null);
return $this->msg(99999);
}
// } catch (\Exception $e) {
// // 捕获异常
// $logContent["flie"] = $e->getFile();
// $logContent["line"] = $e->getLine();
// $logContent['all_content'] = "异常信息:\n";
// $logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
// $logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
// $logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
// $logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
// $logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
// $this->record_api_log($data, $logContent, null);
// return $this->msg(99999);
// }
}
@ -422,8 +422,8 @@ class Card extends Base{
}
// BMI测评
public function card_bmi_evaluation($cbe_data = ['height'=>'177','weight'=>'177','birthday'=>'2024-10-03','sex'=>'1'],$type = false){
try {
public function card_bmi_evaluation($cbe_data = ['height'=>'177','weight'=>'177','birthday'=>'2024-10-03','sex'=>'1','token'=>'caadd1be045a65f30b92aa805f1de54a'],$type = false){
// try {
// 你的业务逻辑
if(count(input('post.')) > 0 && $type == false){
$cbe_data = input('post.');
@ -431,9 +431,10 @@ class Card extends Base{
if(!is_array($cbe_data)){
return $this->msg(10005);
}
if(!array_key_exists('height', $cbe_data) || !array_key_exists('weight', $cbe_data) || !array_key_exists('birthday', $cbe_data) || !array_key_exists('sex', $cbe_data)){
if(!array_key_exists('height', $cbe_data) || !array_key_exists('token', $cbe_data) || !array_key_exists('weight', $cbe_data) || !array_key_exists('birthday', $cbe_data) || !array_key_exists('sex', $cbe_data)){
return $this->msg(10001);
}
$token = $cbe_data['token'];
unset($cbe_data['token']);
if(!$this->verify_data_is_ok($cbe_data['birthday'],'datetime')){
return $this->msg(10005);
@ -459,23 +460,31 @@ class Card extends Base{
$request_result = $this->postRequest($url,$temporary_parameter,array('Content-Type:application/json','Origin:http://ybdevice.pcxbc.com'));
// 直接开始业务请求外部接口end
// 处理进度点
$request_result =$this->bmi_evaluation_action($request_result);
$this->record_api_log($cbe_data, null, $request_result);
return $request_result;
} catch (\Exception $e) {
// 捕获异常
$logContent["flie"] = $e->getFile();
$logContent["line"] = $e->getLine();
$logContent['all_content'] = "异常信息:\n";
$logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
$logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
$logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
$logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
$logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
$this->record_api_log($cbe_data, $logContent, null);
return $this->msg(99999);
}
$language_str = Db::table($this->card_use_db_name['11'])->where(['token'=>$token])->field('language')->find();
$language_data = new Language();
if(!$language_str['language']){
$language_str['language'] = 'zh-Hans';
}
$request_result = $language_data->handling_languages_from_multiple_countries($language_str['language'], $request_result->getData()['data']);
// $this->record_api_log($cbe_data, null, $request_result);
return $this->msg($request_result);
// } catch (\Exception $e) {
// // 捕获异常
// $logContent["flie"] = $e->getFile();
// $logContent["line"] = $e->getLine();
// $logContent['all_content'] = "异常信息:\n";
// $logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
// $logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
// $logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
// $logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
// $logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
// $this->record_api_log($cbe_data, $logContent, null);
// return $this->msg(99999);
// }
}
################################################################业务接口################################################################
@ -517,7 +526,7 @@ class Card extends Base{
acbd.bmi,
acbd.body_age,
acbd.head_circumference,
aud.birthday,aud.gender,aud.target_weight,aud.initial_weight,aud.initial_date
aud.birthday,aud.gender,aud.target_weight,aud.initial_weight,aud.initial_date,aud.aan_id
from ".$this->card_use_db_name['1']." as acbd
left join ".$this->card_use_db_name['2']." as aud on acbd.aud_id=aud.id
where acbd.is_del=0 and acbd.aud_id='".$data['aud_id']."'
@ -543,7 +552,9 @@ class Card extends Base{
"list"=>[],
"key_name"=>"weight",
"desc"=>"反映和衡量一个人健康状况的重要标志之一",
"offset"=>"0"
"offset"=>"0",
"standard_val"=>"",
"difference_val"=>"",
],
[
"name"=>"身高",
@ -554,7 +565,9 @@ class Card extends Base{
"list"=>[],
"key_name"=>"height",
"desc"=>"人体纵向部分的长度,源于人体的纵向生长,受遗传因素的影响较大",
"offset"=>"0"
"offset"=>"0",
"standard_val"=>"",
"difference_val"=>"",
],
[
"name"=>"BMI",
@ -565,7 +578,9 @@ class Card extends Base{
"list"=>[],
"key_name"=>"bmi",
"desc"=>"BMI是身体质量指数,是目前国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。",
"offset"=>"0"
"offset"=>"0",
"standard_val"=>"",
"difference_val"=>"",
],
],
'bottom_list' => [],
@ -583,8 +598,11 @@ class Card extends Base{
'cumulative_day'=>'0'
],
];
$language_data = new Language();
$result_return = $language_data->handling_languages_from_multiple_countries('zh-Hans', $result_return);
return $this->msg($result_return);
}else{
// 存储头围数据
$head_circumference = $result[0]['head_circumference']?json_decode($result[0]['head_circumference'],true):false;
unset($result[0]['head_circumference']);
@ -660,12 +678,13 @@ class Card extends Base{
// 加入曲线板块底部的减肥计划数据end
// 添加头围数据如果有的话start
if($head_circumference !== false && $this->calculate_age($result[0]['birthday']) < 3){
if($head_circumference['level'] == '异常' || $head_circumference['value'] == 0){
$offset = 0;
}else{
$offset = $cardparts->calculate_landing_point($head_circumference['list2'],$head_circumference['value'],$head_circumference['level']);
}
array_push($result_end['top_list'],[
$touwei_array = [
'name'=>'头围',
'value'=>$head_circumference['value'],
'unit'=>'CM',
@ -675,10 +694,63 @@ class Card extends Base{
'key_name'=>'head_circumference',
'desc'=>'头围是指绕头部一周的最大长度,头围的大小与脑的发育密切相关',
'offset'=>$offset
]);
];
$touwei_data = $this->touwei_temporary_use($result[0]['birthday'],$result[0]['gender']);
if(count($touwei_data)){
$touwei_array['standard_val'] = $touwei_data['middle'];
$touwei_array['difference_val'] = bcsub($touwei_array['value'],$touwei_data['middle'],2);
}else{
$touwei_array['standard_val'] = '';
$touwei_array['difference_val'] = '';
}
array_push($result_end['top_list'],$touwei_array);
}
// 添加头围数据如果有的话end
// 这段业务处理可以删除是做的临时的假的start
$biaozhun_val = $this->body_temporary_use($result[0]['birthday'],$result[0]['gender']);
// dump($biaozhun_val);
// $biaozhun_val_weight = 50;
// $biaozhun_val_height = 170;
// $biaozhun_val_bmi = 22;
foreach ($result_end['top_list'] as $key => $value) {
if($value['key_name'] == 'weight'){
if($biaozhun_val['weight'] == ''){
$result_end['top_list'][$key]['standard_val'] = '';
$result_end['top_list'][$key]['difference_val'] = '';
}else{
$result_end['top_list'][$key]['standard_val'] = $biaozhun_val['weight'];
$result_end['top_list'][$key]['difference_val'] = bcsub($value['value'],$biaozhun_val['weight'],2);
}
}else if($value['key_name'] == 'height'){
if($biaozhun_val['height'] == ''){
$result_end['top_list'][$key]['standard_val'] = '';
$result_end['top_list'][$key]['difference_val'] = '';
}else{
$result_end['top_list'][$key]['standard_val'] = $biaozhun_val['height'];
$result_end['top_list'][$key]['difference_val'] = bcsub($value['value'],$biaozhun_val['height'],2);
}
}else if($value['key_name'] == 'bmi'){
if($biaozhun_val['bmi'] == ''){
$result_end['top_list'][$key]['standard_val'] = '';
$result_end['top_list'][$key]['difference_val'] = '';
}else{
$result_end['top_list'][$key]['standard_val'] = $biaozhun_val['bmi'];
$result_end['top_list'][$key]['difference_val'] = bcsub($value['value'],$biaozhun_val['bmi'],2);
}
}
}
// 这段业务处理可以删除是做的临时的假的end
// dump($result);
$language_str = Db::table($this->card_use_db_name['11'])->where(['id'=>$result[0]['aan_id']])->field('language')->find();
$language_data = new Language();
if(!$language_str['language']){
$language_str['language'] = 'zh-Hans';
}
$result_end = $language_data->handling_languages_from_multiple_countries($language_str['language'], $result_end);
return $this->msg($result_end);
}
}
@ -1253,6 +1325,174 @@ class Card extends Base{
################################################################其他接口################################################################
################################################################其他接口################################################################
public function body_temporary_use($age,$gender){
$return_data = [
'height'=>'',
'weight'=>'',
'bmi'=>'',
];
if(!in_array($gender,['1','2'])){
return $return_data;
}
$age_m = $this->calculateAgeInMonthsWithPrecision($age);
if($age_m < 228){//月龄小于19岁
// dump($age_m);
// $height_date = Db::table('ws_height')->where("age <= $age_m and gender = '$gender'")->order('age desc')->limit(1)->field('middle')->select();
$height_date = Db::query("select * from ws_height where age <= $age_m and gender = '$gender' order by age desc");
// $weight_date = Db::table('ws_weight')->where("age <= $month_num and Sex = '$gender'")->order('age desc')->limit(1)->field('middle')->select();
$weight_date = Db::query("select * from ws_weight where age <= $age_m and gender = '$gender' order by age desc");
// $bmi_date = Db::table('ws_bmi')->where("age <= $month_num and Sex = '$gender'")->order('age desc')->limit(1)->field('middle')->select();
$bmi_date = Db::query("select * from ws_bmi where age <= $age_m and gender = '$gender' order by age desc");
$return_data = array(
'height' => $height_date[0]['middle'],
'weight' => $weight_date[0]['middle'],
'bmi' => $bmi_date[0]['middle'],
);
}else{
$bmi_data = [
'1' => [ // 男性
[
'age' => ['min' => 216, 'max' => 299], // 18-24岁216-299月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '20.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '20.5', 'max_val' => '23.9', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.0', 'max_val' => '27.9', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.0', 'max_val' => '31.9', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.0', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 300, 'max' => 419], // 25-34岁300-419月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '20.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.0', 'max_val' => '24.4', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.5', 'max_val' => '28.4', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.5', 'max_val' => '32.4', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.5', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 420, 'max' => 539], // 35-44岁420-539月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '21.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.5', 'max_val' => '25.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '25.1', 'max_val' => '29.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '29.1', 'max_val' => '33.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '33.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 540, 'max' => 719], // 45-59岁540-719月龄
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '21.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '22.0', 'max_val' => '25.5', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '25.6', 'max_val' => '29.5', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '29.6', 'max_val' => '33.5', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '33.6', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 720, 'max' => '99999'], // ≥60岁720+月龄)
'list'=>[
['min_val' => '0', 'max_val' => '18.5', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.5', 'max_val' => '22.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '22.5', 'max_val' => '26.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '26.1', 'max_val' => '29.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '29.1', 'max_val' => '33.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '33.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
]
],
'2' => [ // 女性
[
'age' => ['min' => 216, 'max' => 299], // 18-24岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '19.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '20.0', 'max_val' => '22.9', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '23.0', 'max_val' => '26.9', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '27.0', 'max_val' => '30.9', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '31.0', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 300, 'max' => 419], // 25-34岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '20.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '20.5', 'max_val' => '23.4', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '23.5', 'max_val' => '27.4', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '27.5', 'max_val' => '31.4', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '31.5', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 420, 'max' => 539], // 35-44岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '20.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.0', 'max_val' => '24.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.1', 'max_val' => '28.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.1', 'max_val' => '32.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 540, 'max' => 719], // 45-59岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '21.4', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '21.5', 'max_val' => '24.5', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '24.6', 'max_val' => '28.5', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.6', 'max_val' => '32.5', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.6', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
],
[
'age' => ['min' => 720, 'max' => 99999], // ≥60岁
'list'=>[
['min_val' => '0', 'max_val' => '18.0', 'text' => '低体重', 'color' => '#8BC8FB'],
['min_val' => '18.0', 'max_val' => '21.9', 'text' => '偏瘦', 'color' => '#B4E3FD'],
['min_val' => '22.0', 'max_val' => '25.0', 'text' => '正常', 'color' => '#6CD86F'],
['min_val' => '25.1', 'max_val' => '28.0', 'text' => '超重', 'color' => '#FFD166'],
['min_val' => '28.1', 'max_val' => '32.0', 'text' => '肥胖', 'color' => '#FF9A5A'],
['min_val' => '32.1', 'max_val' => '99999', 'text' => '重度肥胖', 'color' => '#FF6B6B']
]
]
]
];
foreach ($bmi_data[$gender] as $group) {
if ($age_m >= $group['age']['min'] && $age_m <= $group['age']['max']) {
$return_data['bmi'] = bcdiv(bcadd($group['list'][2]['min_val'],$group['list'][2]['max_val'],20),2,1);
}
}
}
return $return_data;
}
public function touwei_temporary_use($age,$gender){
$return_data = [
];
if(!in_array($gender,['1','2'])){
return $return_data;
}
$age_m = $this->calculateAgeInMonthsWithPrecision($age);
if($age_m <= 36){
// $touwei_date = Db::table('ws_touwei')->where("age <= $age_m and gender = '$gender'")->order('age desc')->limit(1)->field('middle')->fetchSql(true)->select();
$touwei_date = Db::query("select * from ws_touwei where age <= $age_m and gender = '$gender' order by age desc");
$return_data = $touwei_date[0];
}
return $return_data;
}

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
class Cardparts extends Base{

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
use Exception;
@ -8,11 +8,11 @@ use Exception;
class Cardpublic extends Base{
protected $cardpublic_use_db_name = [
'1'=>'app_user_data',
'2'=>'app_card_data_sub_item',
'3'=>'app_card_data_sub_item_data',
'4'=>'admin_estimate',
'5'=>'app_card_data'
'1'=>'app_user_data_copy1',
'2'=>'app_card_data_sub_item_copy1',
'3'=>'app_card_data_sub_item_data_copy1',
'4'=>'admin_estimate_copy1',
'5'=>'app_card_data_copy1'
];
protected $curve_color = ['#f7b03e','#fb7b92','#ff9f40','#3fcba7',];

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
@ -8,10 +8,10 @@ use think\Db;
class Deepseek extends Base{
protected $msginformation_use_db_name = [
'1'=>'admin_editor_text_content',
'2'=>'admin_editor_text_like_up_log',
'3'=>'admin_notice_banner',
'4'=>'admin_business_cooperation'
'1'=>'admin_editor_text_content_copy1',
'2'=>'admin_editor_text_like_up_log_copy1',
'3'=>'admin_notice_banner_copy1',
'4'=>'admin_business_cooperation_copy1'
];
protected $page_num = 10;
// 加 bcadd(,,20)

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
use think\Log;
@ -10,9 +10,9 @@ class Device extends Base{
protected $color = ['#FF5656','#FFAB00','#5AD06D','#6492F6','#3967D6'];
protected $device_use_db_name = [
'1'=>'app_device_data',
'2'=>'app_account_number',
'3'=>'app_device_code_data',
'1'=>'app_device_data_copy1',
'2'=>'app_account_number_copy1',
'3'=>'app_device_code_data_copy1',
];

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Controller;
use think\Db;

View File

@ -1,26 +1,26 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
use \think\Validate;
use app\app\controller\Language;
use app\testapp\controller\Language;
// use ip2region\Ip2Region;
class Index extends Base{
protected $moren_gufen_diqu = '北京,北京';
protected $db_name = ['2'=>'app_card_body_data','6'=>'app_card_skip_data','8'=>'app_card_vitalcapacity_data','10'=>'app_card_data_sub_item_data'];
protected $db_name = ['2'=>'app_card_body_data_copy1','6'=>'app_card_skip_data_copy1','8'=>'app_card_vitalcapacity_data_copy1','10'=>'app_card_data_sub_item_data_copy1'];
protected $index_use_db_name = [
'1'=>'app_version_log',
'2'=>'app_user_data',
'3'=>'app_card_body_data',
'4'=>'app_device_code_data',
'5'=>'app_device_data',
'6'=>'app_card_data',
'7'=>'app_account_number',
'8'=>'app_card_data_sub_item',
'9'=>'app_card_data_sub_item_data',
'10'=>'admin_estimate'
'1'=>'app_version_log_copy1',
'2'=>'app_user_data_copy1',
'3'=>'app_card_body_data_copy1',
'4'=>'app_device_code_data_copy1',
'5'=>'app_device_data_copy1',
'6'=>'app_card_data_copy1',
'7'=>'app_account_number_copy1',
'8'=>'app_card_data_sub_item_copy1',
'9'=>'app_card_data_sub_item_data_copy1',
'10'=>'admin_estimate_copy1'
];
// protected $card_key = ['2'=>'body','6'=>'skip','8'=>'vitalcapacity'];
protected $default_card = ['2','6','8'];
@ -65,7 +65,7 @@ class Index extends Base{
protected $language_country = [
'en' => 'English', // 英语(通用)★
'zh' => '中文', // 中文(简体)★
'zh-Hans' => '中文', // 中文(简体)★
// 'es' => 'Español', // 西班牙语(西班牙)★
// 'fr' => 'Français', // 法语(法国)★
// 'pt' => 'Português', // 葡萄牙语(巴西)★
@ -103,7 +103,7 @@ class Index extends Base{
// 检测版本及判断是否登录失效
public function login_invalid_version($data = ['token'=>'caadd1be045a65f30b92aa805f1de54a']){
try {
// try {
// 获取客户端IP
$ip = request()->ip();
// 调用IP识别方法
@ -147,33 +147,28 @@ class Index extends Base{
$url = '';
}
$user_token_state = $this->token_time_validate($data['token']);
$user_language_data = Db::table($this->index_use_db_name['7'])->where(['token'=>$data['token']])->field('language')->find();
if($user_language_data != null){
$language_data = $user_language_data['language'];
}else{
$language_data = $this->pd_language($user_token_state['language'],$isSupportedLanguage,$language);
}
$language_data = $this->pd_language($user_token_state['language'],$isSupportedLanguage,$language);
if($user_token_state['state'] === false){
return $this->msg(-1,'未登录',['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->language_country]);
return $this->msg(-1,'未登录',['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->process_Language()]);
}else{
return $this->msg(['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->language_country]);
return $this->msg(['version'=>$version,'url'=>$url,'language'=>$language_data,'language_arr'=>$this->process_Language()]);
}
} catch (\Exception $e) {
// 捕获异常
$logContent["flie"] = $e->getFile();
$logContent["line"] = $e->getLine();
$logContent['all_content'] = "异常信息:\n";
$logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
$logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
$logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
$logContent['all_content'] .= "方法: " . __METHOD__ . "\n";
$logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
$logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
$this->record_api_log($data, $logContent, null);
return $this->msg(99999);
}
// } catch (\Exception $e) {
// // 捕获异常
// $logContent["flie"] = $e->getFile();
// $logContent["line"] = $e->getLine();
// $logContent['all_content'] = "异常信息:\n";
// $logContent['all_content'] .= "消息: " . $e->getMessage() . "\n";
// $logContent['all_content'] .= "代码: " . $e->getCode() . "\n";
// $logContent['all_content'] .= "文件: " . $e->getFile() . "\n";
// $logContent['all_content'] .= "方法: " . __METHOD__ . "\n";
// $logContent['all_content'] .= "行号: " . $e->getLine() . "\n";
// $logContent['all_content'] .= "跟踪信息:\n" . $e->getTraceAsString() . "\n";
// $this->record_api_log($data, $logContent, null);
// return $this->msg(99999);
// }
}
// 添加IP信息获取方法
@ -190,7 +185,7 @@ class Index extends Base{
}
}
public function set_language_country($data = ['token'=>'caadd1be045a65f30b92aa805f1de54a','language'=>'zh']){
public function set_language_country($data = ['token'=>'caadd1be045a65f30b92aa805f1de54a','language'=>'zh-Hans']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -358,7 +353,7 @@ class Index extends Base{
// 获取账号下用户列表
// $type 1获取列表2获取详细信息
public function get_user_card_list($data = ['aan_id'=>4,'type'=>2,'token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
public function get_user_card_list($data = ['aan_id'=>87,'type'=>2,'token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -366,7 +361,6 @@ class Index extends Base{
}
if(!array_key_exists('token', $data) || !array_key_exists('aan_id', $data) || !array_key_exists('type', $data)){
// 失败
$this->record_api_log($data, null, ['code'=>10001,'msg'=>'',[]]);
return $this->msg(10001);
}
if(!$this->verify_data_is_ok($data['aan_id'],'intnum')){
@ -425,7 +419,7 @@ class Index extends Base{
}
// 获取指定用户详细信息
public function get_user_data_information($data = ['aud_id'=>61]){
public function get_user_data_information($data = ['aud_id'=>144]){
// try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -1152,7 +1146,7 @@ class Index extends Base{
if($isSupportedLanguage){
$result = $language;
}else{
$result = 'en'; // 默认语言为中文
$result = 'zh-Hans'; // 默认语言为中文
}
}else{
$result = $user_language;
@ -1160,6 +1154,16 @@ class Index extends Base{
return $result;
}
// 处理返回的语言数组
public function process_Language(){
$temporary_arr = [];
foreach ($this->language_country as $key => $value) {
array_push($temporary_arr,['key'=>$key,'value'=>$value]);
}
return $temporary_arr;
}

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
class Language extends Base
{
@ -16,6 +16,12 @@ class Language extends Base
'de' => 'German'
];
// $language_data = new Language();
// if(!$language_str['language']){
// $language_str['language'] = 'zh-Hans';
// }
// $result_end = $language_data->handling_languages_from_multiple_countries($language_str['language'], $result_end);
// 语言映射表
protected $languageMap = [
'en' => [
@ -74,19 +80,122 @@ class Language extends Base
'肥胖等级' => "Obesity Level",
'体重不足' => "Underweight",
'肥胖的程度,表现实际体重与理想体重的差距。肥胖等级是判定肥胖症的一个指标。' => "Obesity level indicates the disparity between actual and ideal weight, serving as a diagnostic criterion for obesity.",
'孩子可能存在营养不良对于处在生长发育期的孩子而言蛋白质、碳水化合物、维生素和矿物质这四类营养素非常重要。建议补充足够的蛋白质、锌、钙、铁、维生素D、赖氨酸等营养。建议补充含鸡内金山楂膏健脾开胃类药食同源食物。' => "The child may be malnourished: For growing children, protein, carbohydrates, vitamins, and minerals are critical. Ensure adequate intake of protein, zinc, calcium, iron, vitamin D, lysine, etc. Consider herbal foods like chicken gizzard-hawthorn paste to improve digestion and appetite.",
'孩子可能存在营养不良对于处在生长发育期的孩子而言最有利于长高的营养素是蛋白质、碳水化合物、维生素和矿物质四类。建议补充足够的蛋白质、锌、铁、钙、维生素D、赖氨酸等营养。' => "The child may be malnourished: For children in their growth and development stage, the most beneficial nutrients for height growth are proteins, carbohydrates, vitamins, and minerals. It is recommended to ensure adequate intake of nutrients such as protein, zinc, iron, calcium, vitamin D, and lysine.",
'坚持适当、科学的跳跃运动能够科学地增加学生体重,能够改善学 生体重过低的情况;同时运动会消耗能量并加速胃肠蠕动,这会使孩子的食欲大开,再配合均衡的营养有利于孩子增重。' => "Moderate, scientifically designed jumping exercises can help underweight students gain weight by boosting energy expenditure and gastrointestinal motility, thereby increasing appetite. Combined with balanced nutrition, this supports healthy weight gain.",
'3-7岁的孩子骑两轮车、拍踢球、打篮球、游泳、爬山每天高强度运动不超过30分钟。' => "Ages 37: Bicycling, ball games, basketball, swimming, hiking. Limit high-intensity exercise to 30 minutes daily.",
'该年龄段睡眠时间建议9-11小时' => "Recommended sleep duration for this age group: 911 hours.",
'孩子开始对于赞赏、鼓励、认同和肯定有需求,而且此阶段父亲在孩子的性格塑造、情绪控制以及责任感培养方面扮演着重要的角色,必须告诉孩子什么事应该做、什么事不应该做,并经常性地给孩子一些积极地暗示。例如,可以时常向孩子表达“我会一直在你身边,不要害怕””我对你的进步都看在眼里等类似的话语。' => "Children begin to crave praise, encouragement, and validation. Fathers play a key role in shaping character, emotional regulation, and responsibility during this phase. Clearly define boundaries while offering positive affirmations (e.g., 'Im always here for you,' 'I see your progress').",
'孩子开始对于赞赏、鼓励、认同和肯定有需求,而且此阶段父亲在孩子的性格塑造、情绪控制以及责任感培养方面扮演着重要的角色,必须告诉孩子什么事应该做、什么事不应该做,并经常性地给孩子一些积极地暗示。例如,可以时常向孩子表达“我会一直在你身边,不要害怕””我对你的进步都看在眼里等类似的话语。' => 'Children begin developing needs for praise, encouragement, recognition and affirmation. During this phase, fathers play a vital role in character formation, emotional regulation and responsibility cultivation. Clearly communicate appropriate behaviors while providing consistent positive reinforcement, such as saying: "I\'ll always be here for you" or "I see your progress."',
'步入最佳学习期,除了文化课的学习更多的还有情绪调节、人际交往的学习,会模仿父母、老师同学。此阶段需要的不仅是尊重和信任,还需要更多自由选择的权利,变管制为引导。' => 'Entering the optimal learning period, children develop emotional regulation and social skills beyond academics, mimicking parents, teachers and peers. They require not just respect and trust, but also increased autonomy - transitioning from control to guidance.',
'该年龄段睡眠时间建议11-14小时' => 'Recommended sleep duration: 11-14 hours',
'0-1岁的孩子6个月之前多练习趴着、抬头、翻身等6个月后练习爬行8个月后可尝试坐着。充分的爬行运动有利于孩子协调性和平衡力的培养。' => '0-1 year olds: Practice tummy time, head lifting and rolling before 6 months; crawling after 6 months; attempt sitting at 8 months. Ample crawling enhances coordination and balance.',
'3-7岁的孩子骑两轮车、拍踢球、打篮球、游泳、爬山每天高强度运动不超过30分钟。' => '3-7 year olds: Bicycle riding, ball games, basketball, swimming, mountain climbing. Limit high-intensity exercise to 30 minutes daily.',
'正值青春期,生理的特点决定了情绪的跌宕起伏。当孩子出现情绪问题时,父母可以告诉孩子一些解决的办法,然后让他自行体悟和理解,教会孩子接纳情绪的方法而不是如何对抗情绪。' => 'Adolescents experience physiological mood fluctuations. When emotional issues arise, parents should teach coping strategies for self-discovery, emphasizing emotional acceptance over resistance.',
'该年龄段睡眠时间建议8-10小时' => 'Recommended sleep duration: 8-10 hours',
'睡眠时间建议晚上9点到凌晨1点、早上5点到7点是孩子生长激素分泌最多的时间段此时进入深度睡眠生长激素的分泌就会最大化建议处在生长发育期的孩子尽量在9点前睡觉。' => 'Optimal sleep window: 9pm-1am and 5-7am when growth hormone peaks. Maximize secretion through deep sleep. Growing children should sleep before 9pm.',
'1、情绪的不稳定影响了下丘脑及垂体系统的正常工作进而使垂体生长激素分泌减少长期的情绪障碍除了影响身高同时还会造成孩子智力增长慢、多动、人际关系不协调等异常现象。' => '1. Emotional instability disrupts hypothalamic-pituitary function, reducing growth hormone secretion. Chronic emotional issues may impair height development, cognitive growth, and cause hyperactivity or social maladjustment.',
'1-3岁的孩子此年龄段实现了由走到跑的转变神经系统也得到了发育。鼓励孩子有利于生长发育的活动即可踩图案、绕障碍行走、学小动物走路如青蛙跳、猴子跑、老虎匍匐前进等、仰卧起坐等。' => '1-3 year olds: Transitioning from walking to running with developing nervous systems. Encourage developmental activities: pattern stepping, obstacle courses, animal walks (frog jumps, monkey runs, tiger crawls), and sit-ups.',
'该年龄段睡眠时间建议14-17小时' => 'Recommended sleep duration: 14-17 hours',
'该年龄段睡眠时间建议10-13小时' => 'Recommended sleep duration: 10-13 hours',
'该年龄段睡眠时间建议12-15小时' => 'Recommended sleep duration: 12-15 hours',
'除了满足食物等生理需求,需要建立足够的安全感,充分陪伴、呵护。还要在排除一些安全隐患后适当满足孩子的探索需求。' => 'Beyond physiological needs like food, provide security through attentive care while enabling safe exploration after risk assessment.',
'该年龄段睡眠时间建议9-11小时' => 'Recommended sleep duration: 9-11 hours',
'8-16岁的孩子1、每周3-5次跳绳50-100次左右/组每天做5组每组间隔5分钟2、立定跳远每周5-7次每次20-50次3、慢跑500-1000米3、20个俯卧撑30个上下蹲、30个仰卧起坐。' => '8-16 year olds: 1) Rope skipping 3-5x/week: 5 sets of 50-100 skips daily with 5-minute intervals; 2) Standing long jumps 5-7x/week (20-50 reps); 3) Jogging 500-1000m; 4) 20 push-ups, 30 squats, 30 sit-ups.',
'这个阶段的孩子最调皮,一方面非常依赖父母,另一方面又相对独立。这个阶段仍然需要安全感,并且父母本身的心理状态对孩子的影响依然深远,当他们情绪不稳定,孩子也极有可能受到影响。' => 'Children at this stage exhibit mischievousness while balancing dependence and independence. They still require security, and parental emotional stability profoundly impacts them - children often mirror parental emotional turbulence.',
'孩子可能存在营养不良对于处在生长发育期的孩子而言蛋白质、碳水化合物、维生素和矿物质这四类营养素非常重要。建议补充足够的蛋白质、锌、钙、铁、维生素D、赖氨酸等营养。' => 'The child may be malnourished: For growing children, four key nutrients - proteins, carbohydrates, vitamins and minerals - are crucial. Recommend supplementing adequate protein, zinc, calcium, iron, vitamin D, and lysine.',
'孩子可能存在营养不良对于处在生长发育期的孩子而言最有利于长高的营养素是蛋白质、碳水化合物、维生素和矿物质四类。建议补充足够的蛋白质、锌、铁、钙、维生素D、赖氨酸等营养。' => 'The child may be malnourished: The most height-beneficial nutrients for growing children are proteins, carbohydrates, vitamins and minerals. Recommend supplementing adequate protein, zinc, iron, calcium, vitamin D, and lysine.',
'对于处在生长发育期的孩子而言最有利于长高的营养素是蛋白质、碳水化合物、维生素和矿物质四类。建议补充足够的蛋白质、锌、铁、钙、维生素D、赖氨酸等营养预防营养不良。' => 'For growing children, the most height-promoting nutrients are proteins, carbohydrates, vitamins and minerals. Recommend supplementing adequate protein, zinc, iron, calcium, vitamin D, and lysine to prevent malnutrition.',
'超重的孩子如不加以控制,则极易向肥胖转变。超重的孩子饮食注意事项:控制食量,吃八分饱;三餐规律,避免暴饮暴食;细嚼慢咽;营养均衡搭配,拒绝高油、高盐、高糖的食物,养成清淡的口味。' => 'Overweight children easily progress to obesity without intervention. Dietary guidelines: 80% fullness; regular meals; thorough chewing; balanced nutrition; avoiding greasy/salty/sugary foods; developing light tastes.',
'孩子可能存在中度营养不良对于处在生长发育期的孩子而言最有利于长高的营养素是蛋白质、碳水化合物、维生素和矿物质四类。建议补充足够的蛋白质、锌、铁、钙、维生素D、赖氨酸等营养。' => 'The child may have moderate malnutrition: The most height-beneficial nutrients are proteins, carbohydrates, vitamins and minerals. Recommend supplementing adequate protein, zinc, iron, calcium, vitamin D, and lysine.',
'孩子可能存在重度营养不良对于处在生长发育期的孩子而言最有利于长高的营养素是蛋白质、碳水化合物、维生素和矿物质四类。建议补充足够的蛋白质、锌、铁、钙、维生素D、赖氨酸等营养。' => 'The child may have severe malnutrition: The most height-beneficial nutrients are proteins, carbohydrates, vitamins and minerals. Recommend supplementing adequate protein, zinc, iron, calcium, vitamin D, and lysine.',
'1、肥胖在某种意义来说是隐性的营养不良由于摄入热量过高孩子虽然看着胖但营养的摄入是不均衡的尤其对于8-14岁的孩子来说肥胖会极大地提高性早熟的概率。肥胖的孩子过度进食甜食、油腻的食物极易出现血糖高、高脂血症从而影响生长激素的分泌影响终身高。肥胖的孩子更容易缺乏维生素D影响骨骼的钙化和成长。2、肥胖的孩子饮食注意事项控制食量吃八分饱三餐规律避免暴饮暴食细嚼慢咽营养均衡搭配拒绝高油、高盐、高糖的食物养成清淡的口味。' => '1. Obesity represents hidden malnutrition - while calorie intake is excessive, nutrition remains unbalanced. Particularly for 8-14 year olds, obesity significantly increases precocious puberty risks. Overconsumption of sweets/greasy foods elevates blood sugar/lipids, impairing growth hormone secretion and final height. Obese children also face higher vitamin D deficiency risks, affecting bone calcification. 2. Dietary guidelines: 80% fullness; regular meals; thorough chewing; balanced nutrition; avoiding greasy/salty/sugary foods; developing light tastes.',
'对于处在生长发育期的孩子而言蛋白质、碳水化合物、维生素和矿物质这四类营养素非常重要。建议补充足够的蛋白质、锌、铁、钙、维生素D、赖氨酸等营养预防营养不良造成体型偏瘦。' => 'For growing children, four key nutrients - proteins, carbohydrates, vitamins and minerals - are essential. Recommend supplementing adequate protein, zinc, iron, calcium, vitamin D, and lysine to prevent underweight malnutrition.',
'超重或肥胖的孩子如不加以控制,则极易向肥胖转变。超重或肥胖的孩子饮食注意事项:控制食量,吃八分饱;三餐规律,避免暴饮暴食;细嚼慢咽;营养均衡搭配,拒绝高油、高盐、高糖的食物,养成清淡的口味。建议补充含鸡内金山楂膏健脾开胃类药食同源食物。' => 'Overweight/obese children easily progress to worse obesity without control. Dietary guidelines: 80% fullness; regular meals; thorough chewing; balanced nutrition; avoiding greasy/salty/sugary foods; developing light tastes. Recommend supplementing with chicken gizzard-hawthorn paste (a food-grade herbal digestant).',
'对于处在生长发育期的孩子而言蛋白质、碳水化合物、维生素和矿物质这四类营养素非常重要。建议补充足够的蛋白质、锌、钙、维生素D、赖氨酸等营养预防营养不良造成体型偏瘦。建议补充含鸡内金山楂膏健脾开胃类药食同源食物。' => 'For growing children, four key nutrients - proteins, carbohydrates, vitamins and minerals - are essential. Recommend supplementing adequate protein, zinc, calcium, vitamin D, and lysine to prevent underweight malnutrition, along with chicken gizzard-hawthorn paste (a food-grade herbal digestant).',
'对于处在生长发育期的孩子而言最有利于长高的营养素是蛋白质、碳水化合物、维生素和矿物质四类。建议补充足够的蛋白质、锌、钙、维生素D、赖氨酸等营养预防营养不良。铁' => 'For growing children, the most height-promoting nutrients are proteins, carbohydrates, vitamins and minerals. Recommend supplementing adequate protein, zinc, calcium, vitamin D, and lysine to prevent malnutrition. Iron.',
'运动会消耗能量并加速胃肠蠕动,这会使孩子的食欲大开,再配合均衡的营养有利于孩子增重。'=> 'Physical activity burns calories and enhances gastrointestinal motility, significantly stimulating children\'s appetite. When combined with balanced nutrition, this effectively supports healthy weight gain.',
'体育运动可以有效刺激骨骼与全身关节,从而促进生长激素分泌,加速软骨细胞分裂,从而促进了身高的增长。跳绳运动是一项非常健康的运动方式,可以促进青少年的骨骼生长和发育,促进青少年的体质健康。' => 'Exercise actively stimulates bones and joints throughout the body, promoting growth hormone secretion and accelerating chondrocyte division to facilitate height increase. Rope skipping is an exceptionally beneficial exercise that enhances adolescents\' bone development and overall physical fitness.',
'适宜的运动,能促进全身及骨的钙磷代谢,促进骨生长,长期的户外运动,加速骨细胞的生长,使管状骨变长,横径增粗,促进生长发育。'=> 'Moderate exercise optimizes whole-body calcium-phosphorus metabolism and bone growth. Regular outdoor activities accelerate osteocyte proliferation, lengthening long bones while increasing their diameter to promote healthy development.',
'运动会消耗能量培养运动习惯减少静坐时间建议每天参加体育运动的时间至少30分钟不贪睡睡得越久人体代谢速度就会越慢极易囤积脂肪。'=> 'Exercise consumes energy, establishes active habits and reduces sedentary behavior. We recommend minimum 30 minutes of daily physical activity. Excessive sleep slows metabolic rate and promotes fat accumulation.',
'体育运动可以有效刺激骨骼与全身关节,从而促进生长激素分泌,加速软骨细胞分裂,从而促进了身高的增长。长期科学地坚持跳绳,可以在很大程度上增加骨强度和骨密度,促进骨生长,从而改善青少年的骨健康情况。跳绳运动是一项非常健康的运动方式,可以促进青少年的骨骼生长和发育,促进青少年的体质健康。' => 'Physical training effectively activates skeletal and articular systems, boosting growth hormone production and chondrocyte multiplication to enhance height. Scientifically-guided long-term rope skipping significantly improves bone mineral density and strength, optimizing adolescents\' skeletal health. This exercise is particularly effective for promoting bone development and physical conditioning.',
'体育运动可以有效刺激骨骼与全身关节,从而促进生长激素分泌,加速软骨细胞分裂,从而促进了身高的增长。补救身高的最好方式就是长期坚持适当的体育运动,只要是采取科学的锻炼方法,都能促进骨骼的生长。在所有的运动项目中,全身运动、动力性跳跃运动和伸展运动这三类运动最能够促进身高增长。' => 'Exercise stimulates osseous and joint systems to enhance growth hormone release and cartilage cell division, facilitating height development. The most effective height-correction method involves sustained, moderate physical activity - any scientifically-designed regimen promotes bone growth. Among all exercises, full-body movements, plyometric jumps and stretching prove most beneficial for height improvement.',
'运动会消耗能量会增加体内脂肪的消耗减少储存量起到帮助控制体重的作用培养运动习惯减少静坐时间建议每天参加体育运动的时间至少30分钟不贪睡睡得越久人体代谢速度就会越慢极易囤积脂肪。' => 'Physical exertion increases calorie expenditure and fat utilization while reducing adipose storage, effectively aiding weight management. Establish consistent exercise routines and minimize inactivity with at least 30 minutes daily movement. Prolonged sleep decreases metabolic efficiency and encourages fat deposition.',
'运动会消耗能量并加速胃肠蠕动,这会使孩子的食欲大开,再配合均衡的营养有利于孩子维持合格的体重。' => 'Exercise burns calories and stimulates digestive peristalsis, markedly improving children\'s appetite. Paired with nutritional balance, this helps maintain optimal body weight parameters.',
'建议多做跳跃运动立定跳远跳绳中跳跃刺激的频率以及速度都对于机体中过多脂肪的消耗起到促进作用能够一定程度上起到预防和控制肥胖、降低体重的作用同时培养运动习惯减少静坐时间建议每天参加体育运动的时间至少30分钟不贪睡睡得越久人体代谢速度就会越慢极易囤积脂肪。' => 'Prioritize jumping exercises (standing broad jumps, rope skipping) as their impact frequency and velocity significantly enhance fat oxidation, effectively preventing obesity and aiding weight control. Cultivate regular workout habits and limit sedentary periods to minimum 30 minutes daily activity. Excessive sleep duration reduces metabolic rate and promotes lipid accumulation.',
'运动会消耗能量并加速胃肠蠕动,这会使孩子的食欲大开,再配合均衡的营养有利于孩子维持合格的体重。' => 'Physical activity expends energy and intensifies gastrointestinal motility, substantially boosting children\'s appetite. Combined with balanced nutrition, this assists in maintaining healthy weight standards.',
'体育运动可以有效刺激骨骼与全身关节,从而促进生长激素分泌,加速软骨细胞分裂,从而促进了身高的增长。' => 'Systematic exercise effectively activates skeletal and articular systems, stimulating growth hormone secretion and accelerating cartilage cell proliferation to optimize height development.',
'坚持适当、科学的跳跃运动能够科学地增加学生体重,能够改善学生体重过低的情况;同时运动会消耗能量并加速胃肠蠕动,这会使孩子的食欲大开,再配合均衡的营养有利于孩子增重。' => 'Consistent, properly-designed jumping exercises can scientifically increase students\' body mass and correct underweight conditions. Concurrently, physical training consumes energy and enhances digestive motility, stimulating appetite which - when supported by nutritional balance - promotes healthy weight gain.',
'《中华人民共和国卫生行业标准WS 423-2013》' => "《Chinese Health Industry Standard WS 423-2013》",
'《中华人民共和国卫生行业标准WS/T 612-2018》' => "《Chinese Health Industry Standard WS/T 612-2018》",
'《中华人民共和国卫生行业标准WS/T1586-2018》' => "《Chinese Health Industry Standard WS/T 1586-2018》",
'《WHO 5~19岁身高/体重判定标准》' => "《WHO Growth Reference for Children and Adolescents (519 Years)》",
'头围' => "Head Circumference",
'头围是指绕头部一周的最大长度,头围的大小与脑的发育密切相关' => "Head circumference refers to the maximum length around the head. Its measurement is closely related to brain development.",
'跳绳数量或者分钟、秒钟值必须为整数' => 'The number of jump ropes, minutes, or seconds must be integers.',
'跳绳数不能小于等于0' => 'The jump rope count cannot be less than or equal to 0.',
'秒钟值不能大于60' => 'The seconds value cannot exceed 60.',
'跳绳个数(个)' => 'Jump rope count (times)',
'跳绳时长(分钟)' => 'Jump rope duration (minutes)',
'消耗卡路里(kcal)' => 'Calories burned (kcal)',
'个数' => 'Count',
'时长' => 'Duration',
'卡路里' => 'Calories',
'第一次' => 'First try',
'第二次' => 'Second try',
'第三次' => 'Third try',
'三次平均' => 'Average of three',
'最后成绩' => 'Final score',
'分' => 'Score',
'平均' => 'Average',
'成绩' => 'Score',
'时间(天)' => 'Time (days)',
'增重(kg)' => 'Weight gain (kg)',
'减脂(kg)' => 'Fat loss (kg)',
'数据变化' => 'Data changes',
'趋势' => 'Trend',
'之前' => 'Before',
'之后' => 'After',
'异常' => 'Abnormal',
],
// 可以添加更多语言映射
];
@ -104,14 +213,14 @@ class Language extends Base
// dump($data);
// 验证语言是否支持
if (!$this->isLanguageSupported($language)) {
return $this->msg($data['data']);
return $data;
}
// 如果是数组,递归处理每个元素
if (is_array($data)) {
// dump(2);
$data = $this->translateArray($language, $data);
return $this->msg($data['data']);
return $data;
}
// 如果是字符串,直接翻译
@ -122,7 +231,7 @@ class Language extends Base
// dump($data);
// 其他类型直接返回
return $this->msg($data['data']);
return $data;
}
/**

View File

@ -1,11 +1,11 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
use PHPMailer\PHPMailer\PHPMailer;
use app\app\controller\Wechat;// 引入Wechat服务类
use app\testapp\controller\Wechat;// 引入Wechat服务类
class Login extends Base{
@ -13,7 +13,7 @@ class Login extends Base{
// protected $token_time = 2592000;//30天的秒数
protected $default_head_pic = 'http://tc.pcxbc.com/tsf/head_pic.png';
protected $login_use_db_name = [
'1'=>'app_account_number',
'1'=>'app_account_number_copy1',
];
################################################################接口################################################################
@ -413,7 +413,8 @@ class Login extends Base{
* $type验证类型是注册用还是其他用途 字符串 默认register注册register、login、reset_password
* $road是手机还是邮箱还是其他 字符串 默认tel或email
*/
public function send_phone_email_code($data = ['data'=>'18736019909']){
//18736019909 18530934717
public function send_phone_email_code($data = ['data'=>'18530934717']){
if(count(input('post.')) > 0){
$data = input('post.');
@ -428,8 +429,12 @@ class Login extends Base{
$num = mt_rand(100000,999999);
if (preg_match('/^\d{11}$/', $data['data'])) {
// 本公司短信
$result = $this->send_tel_code($data['data'],$num);
// return $this->msg($result);
// 阿里云短信
// $sms_all = new Smsaliyun;
// $result = $sms_all->send_sms($data['data'],$num);
// dump($result);
$road = 'tel';
}else{
$result = $this->send_email_code([$data['data']],['title'=>'体测APP验证码','from_user_name'=>'体测APP','content'=>$num]);
@ -467,13 +472,10 @@ class Login extends Base{
// 设置POST数据
$postData = array(
'phone' => $tel,
// 'content' => '您好欢迎使用Reedaw,您的手机验证码是:'.$code.',验证码三分钟内有效,若非本人操作,请忽略!'
// 'content' => '【Reedaw】您好欢迎使用Reedaw您的验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
'content' => '【巨天】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
// 'content' => '【郑州品传科技】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
// 'content' => '【小白秤】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
// 'content' => '【品传科技】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
// 'content' => '【巨天】您好,欢迎使用巨天,您的手机验证码是:'.$code.',验证码一分钟内有效,若非本人操作,请忽略!'
// 'content' => '【郑州巨天信息】您好欢迎使用Reedaw您的手机验证码是'.$code.',验证码一分钟内有效,若非本人操作,请忽略本短信'
);
$postData = json_encode($postData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
@ -481,6 +483,7 @@ class Login extends Base{
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 发送请求并获取响应
$response = curl_exec($ch);
// dump($response);
// 检查是否有错误发生
if (curl_errno($ch)) {
$error_message = curl_error($ch);
@ -489,7 +492,7 @@ class Login extends Base{
// 关闭cURL会话
curl_close($ch);
// 处理响应
// dump(json_decode($response,true));
if ($response) {
return json_decode($response,true);
} else {

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
@ -11,10 +11,10 @@ class Msginformation extends Base{
protected $judge_wechat_release = false;
protected $msginformation_use_db_name = [
'1'=>'admin_editor_text_content',
'2'=>'admin_editor_text_like_up_log',
'3'=>'admin_notice_banner',
'4'=>'admin_business_cooperation'
'1'=>'admin_editor_text_content_copy1',
'2'=>'admin_editor_text_like_up_log_copy1',
'3'=>'admin_notice_banner_copy1',
'4'=>'admin_business_cooperation_copy1'
];
protected $page_num = 10;
// 加 bcadd(,,20)

View File

@ -1,15 +1,15 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
use app\app\controller\Login;
use app\testapp\controller\Login;
class Myinformation extends Base{
protected $myinformation_use_db_name = [
'1'=>'app_account_number',
'1'=>'app_account_number_copy1',
];
// 加 bcadd(,,20)
// 减 bcsub(,,20)

View File

@ -1,18 +1,18 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
class Pagingcontrast extends Base{
protected $color = ['#FF5656','#FFAB00','#5AD06D','#6492F6','#3967D6'];
protected $db_name = ['2'=>'app_card_body_data','6'=>'app_card_skip_data','8'=>'app_card_vitalcapacity_data'];
protected $db_name = ['2'=>'app_card_body_data_copy1','6'=>'app_card_skip_data_copy1','8'=>'app_card_vitalcapacity_data_copy1'];
protected $pagingcontrast_use_db_name = [
'1'=>'app_card_body_data',
'2'=>'app_card_skip_data',
'3'=>'app_card_vitalcapacity_data',
'4'=>'app_user_data',
'1'=>'app_card_body_data_copy1',
'2'=>'app_card_skip_data_copy1',
'3'=>'app_card_vitalcapacity_data_copy1',
'4'=>'app_user_data_copy1',
];
protected $request_result = [
'2'=>['height'=>['身高','cm'],'weight'=>['体重','kg'],'age'=>['年龄','岁'],'bmi'=>['BMI',''],'head'=>['头围',''],'fat_w'=>['脂肪量','kg'],'fat_r'=>['脂肪率','%'],'muscleval'=>['肌肉量','kg'],'muscle'=>['肌肉率','%'],'proteinval'=>['蛋白量','kg'],'protein'=>['蛋白率','%'],'water'=>['水分',''],'bone'=>['骨重','kg'],'visceral'=>['内脏指数',''],'sfr'=>['皮下脂肪','%'],'kcal'=>['基础代谢','kcal'],'un_fat_w_weight'=>['去脂体重','kg'],'body_age'=>['体龄',''],'body_level'=>['肥胖等级',''],'body_type'=>['体型','']],
@ -69,7 +69,7 @@ class Pagingcontrast extends Base{
}
// 获取记录信息(分页)(包含身体、跳绳、肺活量)
public function get_all_record_data_page($data = ['aud_id'=>'11','page'=>1,'token'=>'0dafb98a10995c98b5a33b7d59d986ca','type'=>'2']){
public function get_all_record_data_page($data = ['aud_id'=>'144','page'=>1,'token'=>'caadd1be045a65f30b92aa805f1de54a','type'=>'8']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -87,7 +87,7 @@ class Pagingcontrast extends Base{
if(!$this->verify_data_is_ok($data['type'],'intnum')){
return $this->msg(10005);
}
unset($data['token']);
// unset($data['token']);
if(array_key_exists($data['type'],$this->db_name)){
$return_data = $this->jump_transfer_interface_record($data,'page');
}else{
@ -112,7 +112,7 @@ class Pagingcontrast extends Base{
}
// 获取详细历史数据信息(包含身体、跳绳、肺活量)
public function get_all_record_detailed_information($data = ['id'=>'36','type'=>'8','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
public function get_all_record_detailed_information($data = ['id'=>'3802','type'=>'2','aan_id'=>'1841','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -458,6 +458,8 @@ class Pagingcontrast extends Base{
// $for_data_arr = ['height'=>['身高','cm'],'weight'=>['体重','kg'],'age'=>['年龄','岁'],'bmi'=>['BMI','']];
// }
$result_data = [];
// dump($result);
// dump($for_data_arr);
foreach ($for_data_arr as $key => $value) {
$temporary_arr['key_name'] = $key;
$temporary_arr['name'] = $value[0];
@ -471,10 +473,16 @@ class Pagingcontrast extends Base{
$temporary_arr['value'] = explode(',',$result[$key])[0];
}
}else{
if($key == 'un_fat_w_weight'){
$temporary_arr['value'] = bcsub(explode(',',$result['weight'])[0],explode(',',$result['fat_w'])[0],2);
}else{
$temporary_arr['value'] = explode(',',$result[$key])[0];
// dump($key);
// dump($result[$key]);
if(array_key_exists($key,$result)){
$temporary_arr['value'] = explode(',',$result[$key])[0];
}
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
@ -9,9 +9,10 @@ class Skip extends Base{
protected $color = ['#FF5656','#FFAB00','#5AD06D','#6492F6','#3967D6'];
protected $curve_data_format = ['jump_num'=>['跳绳个数','个','#009DFF'],'jump_time'=>['跳绳时长','分钟','#009DFF'],'jump_kcal'=>['消耗卡路里','kcal','#009DFF']];
protected $skip_use_db_name = [
'1'=>'app_card_skip_data',
'2'=>'app_user_data',
'3'=>'app_card_body_data',
'1'=>'app_card_skip_data_copy1',
'2'=>'app_user_data_copy1',
'3'=>'app_card_body_data_copy1',
'4'=>'app_account_number_copy1',
];
protected $result_end_data_mould = [
'name'=>'',
@ -29,7 +30,7 @@ class Skip extends Base{
################################################################接口################################################################
################################################################接口################################################################
// 手动记录
public function skip_manual_recording($data = ['aud_id'=>'61','r_time'=>'2024-07-24','num'=>'369','time_m'=>'02','time_s'=>'42','type'=>'free','token'=>'caadd1be045a65f30b92aa805f1de54a']){
public function skip_manual_recording($data = ['aud_id'=>'144','r_time'=>'2024-07-24','num'=>'369','time_m'=>'02','time_s'=>'42','type'=>'free','token'=>'caadd1be045a65f30b92aa805f1de54a']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -137,7 +138,7 @@ class Skip extends Base{
}
// 今日数据
public function skip_today_data($data = ['aud_id'=>'26','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
public function skip_today_data($data = ['aud_id'=>'144','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -153,7 +154,7 @@ class Skip extends Base{
$return_data = $this->skip_today_data_action($data);
// 成功
$this->record_api_log($data, null, $return_data);
// $this->record_api_log($data, null, $return_data);
return $return_data;
} catch (\Exception $e) {
// 捕获异常
@ -171,7 +172,7 @@ class Skip extends Base{
}
// 曲线
public function skip_curve_chart($data = ['aud_id'=>'9','time'=>'2024-10','token'=>'0dafb98a10995c98b5a33b7d59d986ca']){
public function skip_curve_chart($data = ['aud_id'=>'144','time'=>'2025-04','token'=>'caadd1be045a65f30b92aa805f1de54a']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){
@ -183,7 +184,6 @@ class Skip extends Base{
if(!$this->verify_data_is_ok($data['aud_id'],'intnum')){
return $this->msg(10005);
}
unset($data['token']);
$return_data = $this->skip_curve_chart_action($data);
// 成功
@ -422,6 +422,16 @@ class Skip extends Base{
// $return_data[1]['line']['series'][0]['data'][$key] = $jump_time_long['h'].':'.$jump_time_long['m'].':'.$jump_time_long['s'];
}
// dump($return_data);
$language_str = Db::table($this->skip_use_db_name['4'])->where(['token'=>$data['token']])->field('language')->find();
$language_data = new Language();
if(!$language_str['language']){
$language_str['language'] = 'zh-Hans';
}
// dump($language_str['language']);
$return_data = $language_data->handling_languages_from_multiple_countries($language_str['language'], $return_data);
// dump($return_data);
// die;
return $this->msg($return_data);
}

View File

@ -0,0 +1,84 @@
<?php
namespace app\testapp\controller;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Controller;
class Smsaliyun extends Controller
{
// 阿里云短信配置
private $smsConfig = [
'accessKeyId' => 'LTAI5tQCdWe9Epir3ydXWbzp',
'accessKeySecret' => 'JKLzF0b5AXw2ajhwtem2fhPSUZVOZ5',
'signName' => '郑州巨天信息',
'templateCode' => 'SMS_484085215',
'regionId' => 'cn-hangzhou'
];
/**
* 发送短信接口
* @param string $phone 手机号
* @param string $code 验证码
*/
public function send_sms($phone='18530934717', $code='0932')
{
try {
// 初始化阿里云客户端
AlibabaCloud::accessKeyClient(
$this->smsConfig['accessKeyId'],
$this->smsConfig['accessKeySecret']
)
->regionId($this->smsConfig['regionId'])
->asDefaultClient();
// 发送短信请求
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => $this->smsConfig['regionId'],
'PhoneNumbers' => $phone,
'SignName' => $this->smsConfig['signName'],
'TemplateCode' => $this->smsConfig['templateCode'],
'TemplateParam' => json_encode(['code' => $code]),
],
])
->request();
$result = $result->toArray();
if ($result['Code'] == 'OK') {
return [
'code' => 0,
'message' => '短信发送成功',
'data' => $result
];
} else {
return [
'code' => 99999,
'message' => $result['Message'],
'error' => $result
];
}
} catch (ClientException $e) {
return [
'code' => 99998,
'message' => '客户端异常: ' . $e->getErrorMessage(),
'error' => $e->getMessage()
];
} catch (ServerException $e) {
return [
'code' => 99997,
'message' => '服务端异常: ' . $e->getErrorMessage(),
'error' => $e->getMessage()
];
}
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
@ -11,9 +11,9 @@ class Sportstesting extends Base{
protected $color = ['#FF5656','#FF5656','#5AD06D','#6492F6','#3967D6'];
protected $sportstesting_use_db_name = [
'1'=>'admin_estimate',
'2'=>'app_sportstesting_data',
'3'=>'app_user_data',
'1'=>'admin_estimate_copy1',
'2'=>'app_sportstesting_data_copy1',
'3'=>'app_user_data_copy1',
];
protected $page_num = 10;
protected $default_address = '上海';

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
@ -17,9 +17,9 @@ class Vitalcapacity extends Base{
['min_val'=>'0','max_val'=>'9','text'=>'无效','color'=>'#FF5656'],
];
protected $vitalcapacity_use_db_name = [
'1'=>'app_user_data',
'2'=>'app_card_vitalcapacity_data',
'3'=>'pc_vitalcapacity_standard',
'1'=>'app_user_data_copy1',
'2'=>'app_card_vitalcapacity_data_copy1',
'3'=>'pc_vitalcapacity_standard_copy1',
];
protected $result_end_data_mould = [
'name'=>'',
@ -107,7 +107,7 @@ class Vitalcapacity extends Base{
}
// 数据报告
public function vitalcapacity_data_report($data = ['aud_id'=>'83','token'=>'caadd1be045a65f30b92aa805f1de54a']){
public function vitalcapacity_data_report($data = ['aud_id'=>'144','token'=>'caadd1be045a65f30b92aa805f1de54a']){
try {
// 你的业务逻辑
if(count(input('post.')) > 0){

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;

View File

@ -1,6 +1,6 @@
<?php
namespace app\app\controller;
namespace app\testapp\controller;
use think\Db;
@ -8,8 +8,8 @@ use think\Db;
class Wechatabout extends Base{
protected $msginformation_use_db_name = [
'1'=>'admin_editor_text_content',
'2'=>'admin_editor_text_like_up_log',
'1'=>'admin_editor_text_content_copy1',
'2'=>'admin_editor_text_like_up_log_copy1',
];
protected $page_num = 10;
// 加 bcadd(,,20)

View File

@ -21,7 +21,8 @@
"phpmailer/phpmailer": "^6.9",
"phpoffice/phpspreadsheet": "^1.25",
"overtrue/wechat": "~4.0",
"zoujingli/ip2region": "^2.0"
"zoujingli/ip2region": "^2.0",
"alibabacloud/client": "^1.5"
},
"autoload": {
"psr-4": {

View File

@ -0,0 +1,21 @@
# The MIT License (MIT)
Copyright (c) 2016-2019 Riku Särkinen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,29 @@
{
"name": "adbario/php-dot-notation",
"description": "PHP dot notation access to arrays",
"keywords": ["dotnotation", "arrayaccess"],
"homepage": "https://github.com/adbario/php-dot-notation",
"license": "MIT",
"authors": [
{
"name": "Riku Särkinen",
"email": "riku@adbar.io"
}
],
"require": {
"php": "^5.5 || ^7.0 || ^8.0",
"ext-json": "*"
},
"require-dev": {
"phpunit/phpunit": "^4.8|^5.7|^6.6|^7.5|^8.5|^9.5",
"squizlabs/php_codesniffer": "^3.6"
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Adbar\\": "src"
}
}
}

View File

@ -0,0 +1,623 @@
<?php
/**
* Dot - PHP dot notation access to arrays
*
* @author Riku Särkinen <riku@adbar.io>
* @link https://github.com/adbario/php-dot-notation
* @license https://github.com/adbario/php-dot-notation/blob/2.x/LICENSE.md (MIT License)
*/
namespace Adbar;
use Countable;
use ArrayAccess;
use ArrayIterator;
use JsonSerializable;
use IteratorAggregate;
/**
* Dot
*
* This class provides a dot notation access and helper functions for
* working with arrays of data. Inspired by Laravel Collection.
*/
class Dot implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
{
/**
* The stored items
*
* @var array
*/
protected $items = [];
/**
* The delimiter (alternative to a '.') to be used.
*
* @var string
*/
protected $delimiter = '.';
/**
* Create a new Dot instance
*
* @param mixed $items
* @param string $delimiter
*/
public function __construct($items = [], $delimiter = '.')
{
$this->items = $this->getArrayItems($items);
$this->delimiter = strlen($delimiter) ? $delimiter : '.';
}
/**
* Set a given key / value pair or pairs
* if the key doesn't exist already
*
* @param array|int|string $keys
* @param mixed $value
*/
public function add($keys, $value = null)
{
if (is_array($keys)) {
foreach ($keys as $key => $value) {
$this->add($key, $value);
}
} elseif (is_null($this->get($keys))) {
$this->set($keys, $value);
}
}
/**
* Return all the stored items
*
* @return array
*/
public function all()
{
return $this->items;
}
/**
* Delete the contents of a given key or keys
*
* @param array|int|string|null $keys
*/
public function clear($keys = null)
{
if (is_null($keys)) {
$this->items = [];
return;
}
$keys = (array) $keys;
foreach ($keys as $key) {
$this->set($key, []);
}
}
/**
* Delete the given key or keys
*
* @param array|int|string $keys
*/
public function delete($keys)
{
$keys = (array) $keys;
foreach ($keys as $key) {
if ($this->exists($this->items, $key)) {
unset($this->items[$key]);
continue;
}
$items = &$this->items;
$segments = explode($this->delimiter, $key);
$lastSegment = array_pop($segments);
foreach ($segments as $segment) {
if (!isset($items[$segment]) || !is_array($items[$segment])) {
continue 2;
}
$items = &$items[$segment];
}
unset($items[$lastSegment]);
}
}
/**
* Checks if the given key exists in the provided array.
*
* @param array $array Array to validate
* @param int|string $key The key to look for
*
* @return bool
*/
protected function exists($array, $key)
{
return array_key_exists($key, $array);
}
/**
* Flatten an array with the given character as a key delimiter
*
* @param string $delimiter
* @param array|null $items
* @param string $prepend
* @return array
*/
public function flatten($delimiter = '.', $items = null, $prepend = '')
{
$flatten = [];
if (is_null($items)) {
$items = $this->items;
}
if (!func_num_args()) {
$delimiter = $this->delimiter;
}
foreach ($items as $key => $value) {
if (is_array($value) && !empty($value)) {
$flatten = array_merge(
$flatten,
$this->flatten($delimiter, $value, $prepend.$key.$delimiter)
);
} else {
$flatten[$prepend.$key] = $value;
}
}
return $flatten;
}
/**
* Return the value of a given key
*
* @param int|string|null $key
* @param mixed $default
* @return mixed
*/
public function get($key = null, $default = null)
{
if (is_null($key)) {
return $this->items;
}
if ($this->exists($this->items, $key)) {
return $this->items[$key];
}
if (strpos($key, $this->delimiter) === false) {
return $default;
}
$items = $this->items;
foreach (explode($this->delimiter, $key) as $segment) {
if (!is_array($items) || !$this->exists($items, $segment)) {
return $default;
}
$items = &$items[$segment];
}
return $items;
}
/**
* Return the given items as an array
*
* @param mixed $items
* @return array
*/
protected function getArrayItems($items)
{
if (is_array($items)) {
return $items;
} elseif ($items instanceof self) {
return $items->all();
}
return (array) $items;
}
/**
* Check if a given key or keys exists
*
* @param array|int|string $keys
* @return bool
*/
public function has($keys)
{
$keys = (array) $keys;
if (!$this->items || $keys === []) {
return false;
}
foreach ($keys as $key) {
$items = $this->items;
if ($this->exists($items, $key)) {
continue;
}
foreach (explode($this->delimiter, $key) as $segment) {
if (!is_array($items) || !$this->exists($items, $segment)) {
return false;
}
$items = $items[$segment];
}
}
return true;
}
/**
* Check if a given key or keys are empty
*
* @param array|int|string|null $keys
* @return bool
*/
public function isEmpty($keys = null)
{
if (is_null($keys)) {
return empty($this->items);
}
$keys = (array) $keys;
foreach ($keys as $key) {
if (!empty($this->get($key))) {
return false;
}
}
return true;
}
/**
* Merge a given array or a Dot object with the given key
* or with the whole Dot object
*
* @param array|string|self $key
* @param array|self $value
*/
public function merge($key, $value = [])
{
if (is_array($key)) {
$this->items = array_merge($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_merge($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_merge($this->items, $key->all());
}
}
/**
* Recursively merge a given array or a Dot object with the given key
* or with the whole Dot object.
*
* Duplicate keys are converted to arrays.
*
* @param array|string|self $key
* @param array|self $value
*/
public function mergeRecursive($key, $value = [])
{
if (is_array($key)) {
$this->items = array_merge_recursive($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_merge_recursive($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_merge_recursive($this->items, $key->all());
}
}
/**
* Recursively merge a given array or a Dot object with the given key
* or with the whole Dot object.
*
* Instead of converting duplicate keys to arrays, the value from
* given array will replace the value in Dot object.
*
* @param array|string|self $key
* @param array|self $value
*/
public function mergeRecursiveDistinct($key, $value = [])
{
if (is_array($key)) {
$this->items = $this->arrayMergeRecursiveDistinct($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = $this->arrayMergeRecursiveDistinct($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = $this->arrayMergeRecursiveDistinct($this->items, $key->all());
}
}
/**
* Merges two arrays recursively. In contrast to array_merge_recursive,
* duplicate keys are not converted to arrays but rather overwrite the
* value in the first array with the duplicate value in the second array.
*
* @param array $array1 Initial array to merge
* @param array $array2 Array to recursively merge
* @return array
*/
protected function arrayMergeRecursiveDistinct(array $array1, array $array2)
{
$merged = &$array1;
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = $this->arrayMergeRecursiveDistinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
/**
* Return the value of a given key and
* delete the key
*
* @param int|string|null $key
* @param mixed $default
* @return mixed
*/
public function pull($key = null, $default = null)
{
if (is_null($key)) {
$value = $this->all();
$this->clear();
return $value;
}
$value = $this->get($key, $default);
$this->delete($key);
return $value;
}
/**
* Push a given value to the end of the array
* in a given key
*
* @param mixed $key
* @param mixed $value
*/
public function push($key, $value = null)
{
if (is_null($value)) {
$this->items[] = $key;
return;
}
$items = $this->get($key);
if (is_array($items) || is_null($items)) {
$items[] = $value;
$this->set($key, $items);
}
}
/**
* Replace all values or values within the given key
* with an array or Dot object
*
* @param array|string|self $key
* @param array|self $value
*/
public function replace($key, $value = [])
{
if (is_array($key)) {
$this->items = array_replace($this->items, $key);
} elseif (is_string($key)) {
$items = (array) $this->get($key);
$value = array_replace($items, $this->getArrayItems($value));
$this->set($key, $value);
} elseif ($key instanceof self) {
$this->items = array_replace($this->items, $key->all());
}
}
/**
* Set a given key / value pair or pairs
*
* @param array|int|string $keys
* @param mixed $value
*/
public function set($keys, $value = null)
{
if (is_array($keys)) {
foreach ($keys as $key => $value) {
$this->set($key, $value);
}
return;
}
$items = &$this->items;
foreach (explode($this->delimiter, $keys) as $key) {
if (!isset($items[$key]) || !is_array($items[$key])) {
$items[$key] = [];
}
$items = &$items[$key];
}
$items = $value;
}
/**
* Replace all items with a given array
*
* @param mixed $items
*/
public function setArray($items)
{
$this->items = $this->getArrayItems($items);
}
/**
* Replace all items with a given array as a reference
*
* @param array $items
*/
public function setReference(array &$items)
{
$this->items = &$items;
}
/**
* Return the value of a given key or all the values as JSON
*
* @param mixed $key
* @param int $options
* @return string
*/
public function toJson($key = null, $options = 0)
{
if (is_string($key)) {
return json_encode($this->get($key), $options);
}
$options = $key === null ? 0 : $key;
return json_encode($this->items, $options);
}
/*
* --------------------------------------------------------------
* ArrayAccess interface
* --------------------------------------------------------------
*/
/**
* Check if a given key exists
*
* @param int|string $key
* @return bool
*/
#[\ReturnTypeWillChange]
public function offsetExists($key)
{
return $this->has($key);
}
/**
* Return the value of a given key
*
* @param int|string $key
* @return mixed
*/
#[\ReturnTypeWillChange]
public function offsetGet($key)
{
return $this->get($key);
}
/**
* Set a given value to the given key
*
* @param int|string|null $key
* @param mixed $value
*/
#[\ReturnTypeWillChange]
public function offsetSet($key, $value)
{
if (is_null($key)) {
$this->items[] = $value;
return;
}
$this->set($key, $value);
}
/**
* Delete the given key
*
* @param int|string $key
*/
#[\ReturnTypeWillChange]
public function offsetUnset($key)
{
$this->delete($key);
}
/*
* --------------------------------------------------------------
* Countable interface
* --------------------------------------------------------------
*/
/**
* Return the number of items in a given key
*
* @param int|string|null $key
* @return int
*/
#[\ReturnTypeWillChange]
public function count($key = null)
{
return count($this->get($key));
}
/*
* --------------------------------------------------------------
* IteratorAggregate interface
* --------------------------------------------------------------
*/
/**
* Get an iterator for the stored items
*
* @return \ArrayIterator
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
return new ArrayIterator($this->items);
}
/*
* --------------------------------------------------------------
* JsonSerializable interface
* --------------------------------------------------------------
*/
/**
* Return items for JSON serialization
*
* @return array
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->items;
}
}

View File

@ -0,0 +1,24 @@
<?php
/**
* Dot - PHP dot notation access to arrays
*
* @author Riku Särkinen <riku@adbar.io>
* @link https://github.com/adbario/php-dot-notation
* @license https://github.com/adbario/php-dot-notation/blob/2.x/LICENSE.md (MIT License)
*/
use Adbar\Dot;
if (! function_exists('dot')) {
/**
* Create a new Dot object with the given items and optional delimiter
*
* @param mixed $items
* @param string $delimiter
* @return \Adbar\Dot
*/
function dot($items, $delimiter = '.')
{
return new Dot($items, $delimiter);
}
}

311
vendor/alibabacloud/client/CHANGELOG.md vendored Normal file
View File

@ -0,0 +1,311 @@
# CHANGELOG
## 1.5.32 - 2022-12-08
- Support PHP versions: From 5.5 up to 8.1
## 1.5.31 - 2021-05-13
- Deprecate `\GuzzleHttp\Psr7\parse_query` method
## 1.5.30 - 2021-03-22
- Fixed incompatibility in PHP 5.6 version.
## 1.5.29 - 2020-08-03
- Fixed RPC Signature.
## 1.5.28 - 2020-08-03
- Updated `endpoints`.
## 1.5.27 - 2020-07-17
- Fixed composer error config.
## 1.5.26 - 2020-07-17
- Validate RegionID/EndpointSuffix/Network.
## 1.5.25 - 2020-07-04
- Fixed ROA signature.
- Deprecated `LogFormatter`.
## 1.5.24 - 2020-06-04
- Fixed Resolve Host.
## 1.5.23 - 2020-05-22
- Optimized global product support.
## 1.5.22 - 2020-05-12
- Updated Endpoints.
## 1.5.21 - 2020-02-26
- Improved Nonce.
- Updated Endpoints.
## 1.5.20 - 2019-12-30
- Improved Docs.
- Updated Endpoints.
## 1.5.19 - 2019-12-17
- Updated Endpoints.
## 1.5.18 - 2019-10-11
- Updated Request link.
- Updated Endpoints data.
## 1.5.17 - 2019-09-15
- Improved Host Finder.
- Updated Endpoints Data.
## 1.5.16 - 2019-08-21
- Updated Endpoints Data.
## 1.5.15 - 2019-08-14
- Improved Client.
## 1.5.14 - 2019-07-25
- Improved Credential Filter.
## 1.5.13 - 2019-07-18
- Improved API Resolver.
## 1.5.12 - 2019-06-20
- Fixed Signature for ROA.
## 1.5.11 - 2019-06-14
- Added endpoint rules.
## 1.5.10 - 2019-06-13
- Improved `Resovler`.
- Updated `endpoints`.
## 1.5.9 - 2019-06-04
- Improved `UUID`.
## 1.5.8 - 2019-05-30
- Improved `Arrays`.
## 1.5.7 - 2019-05-29
- Improved `uuid`.
## 1.5.6 - 2019-05-29
- Fixed `uuid` version lock.
## 1.5.5 - 2019-05-23
- Improved `Signature`.
## 1.5.4 - 2019-05-22
- Updated `Endpoints`.
- Fixed `Content-Type` in header.
## 1.5.3 - 2019-05-13
- Improved `Endpoint` tips.
- Improved `Endpoints` for `STS`.
## 1.5.2 - 2019-05-10
- Improved `Result` object.
## 1.5.1 - 2019-05-09
- Supported `Resolver` for Third-party dependencies.
## 1.5.0 - 2019-05-07
- Improved `Resolver` for products.
## 1.4.0 - 2019-05-06
- Support `Retry` and `Asynchronous` for Request.
## 1.3.1 - 2019-04-30
- Allow timeouts to be set in microseconds.
## 1.3.0 - 2019-04-18
- Improved parameters methods.
- Optimized the logic for body encode.
## 1.2.1 - 2019-04-11
- Improve exception code and message for `Region ID`.
## 1.2.0 - 2019-04-11
- Improve exception message for `Region ID`.
## 1.1.1 - 2019-04-02
- Added endpoints for `batchcomputenew`, `privatelink`.
- Improve Region ID tips.
## 1.1.0 - 2019-04-01
- Updated `composer.json`.
## 1.0.27 - 2019-03-31
- Support `Policy` for `ramRoleArnClient`.
## 1.0.26 - 2019-03-27
- Support `pid`, `cost`, `start_time` for Log.
## 1.0.25 - 2019-03-27
- Updated default log format.
- Add endpoints for `dbs`.
## 1.0.24 - 2019-03-26
- Support Log.
## 1.0.23 - 2019-03-23
- Remove SVG.
## 1.0.22 - 2019-03-20
- Add endpoint `cn-hangzhou` for `idaas` .
## 1.0.21 - 2019-03-19
- Installing by Using the ZIP file.
- Update Docs.
## 1.0.20 - 2019-03-13
- Improve Tests.
- Update Docs.
## 1.0.19 - 2019-03-12
- Add SSL Verify Option `verify()`.
## 1.0.18 - 2019-03-11
- Add endpoints for `acr`.
- Add endpoints for `faas`.
- Add endpoints for `ehs`.
- SSL certificates are not validated by default.
## 1.0.17 - 2019-03-08
- Support Mock for Test.
## 1.0.16 - 2019-03-07
- Support Credential Provider Chain.
- Support `CCC`.
- Add `ap-south-1` for `cas`.
- Add `ap-southeast-1` for `waf`.
- Update Docs.
## 1.0.15 - 2019-02-27
- Add endpoints for `Chatbot`.
- Change endpoints for `drdspost` and `drdspre`.
## 1.0.14 - 2019-02-21
- Enable debug mode by set environment variable `DEBUG=sdk`.
## 1.0.13 - 2019-02-18
- Support Release Script `composer release`.
- Add endpoints for apigateway in `drdspre` in `cn-qingdao`.
- Add endpoints for apigateway in `drdspre` in `cn-beijing`.
- Add endpoints for apigateway in `drdspre` in `cn-hangzhou`.
- Add endpoints for apigateway in `drdspre` in `cn-shanghai`.
- Add endpoints for apigateway in `drdspre` in `cn-shenzhen`.
- Add endpoints for apigateway in `drdspre` in `cn-hongkong`.
- Add endpoints for apigateway in `drdspost` in `ap-southeast-1`.
- Add endpoints for apigateway in `drdspost` in `cn-shanghai`.
- Add endpoints for apigateway in `drdspost` in `cn-hongkong`.
- Add endpoints for apigateway in `vod` in `ap-southeast-1`.
- Add endpoints for apigateway in `vod` in `eu-central-1`.
## 1.0.12 - 2019-02-16
- Support `open_basedir`.
## 1.0.11 - 2019-02-13
- Improve User Agent.
## 1.0.10 - 2019-02-12
- `userAgentAppend` is renamed to `appendUserAgent`.
## 1.0.9 - 2019-02-12
- `userAgent` is renamed to `userAgentAppend`.
## 1.0.8 - 2019-02-11
- `userAgent` - Support DIY User Agent.
- Add endpoints for apigateway in Zhangjiakou.
- Add endpoints for apigateway in Hu He Hao Te.
- Add endpoints for vod in Hu He Hao Te.
- Add endpoints for hsm in Zhangjiakou.
- Add endpoints for luban in Germany.
- Add endpoints for linkwan in Hangzhou.
- Add endpoints for drdspost in Singapore.
## 1.0.7 - 2019-01-28
- Add endpoints for gpdb in Tokyo.
- Add endpoints for elasticsearch in Beijing.
## 1.0.6 - 2019-01-23
- Add endpoints for dysmsapi in Singapore.
- Add endpoints for dybaseapi.
- Add endpoints for dyiotapi.
- Add endpoints for dycdpapi.
- Add endpoints for dyplsapi.
- Add endpoints for dypnsapi.
- Add endpoints for dyvmsapi.
- Add endpoints for snsuapi.
## 1.0.5 - 2019-01-21
- Add endpoints for ApiGateway in Silicon Valley, Virginia.
- Add endpoints for Image Search in Shanghai.
## 1.0.4 - 2019-01-17
- Support fixer all.
- Add Endpoints.
## 1.0.3 - 2019-01-15
- Update Endpoints.
- Update README.md.
- Update Return Result Message.
## 1.0.2 - 2019-01-15
- Optimize the documentation.
- Adjust the CI configuration.
## 1.0.1 - 2019-01-09
- Distinguish credential error.
- Add endpoints for NLS.
- Add not found product tip.
## 1.0.0 - 2019-01-07
- Initial release of the Alibaba Cloud Client for PHP Version 1.0.0 on Packagist See <https://github.com/aliyun/openapi-sdk-php-client> for more information.

View File

@ -0,0 +1,30 @@
# Contributing to the Alibaba Cloud Client for PHP
We work hard to provide a high-quality and useful SDK for Alibaba Cloud, and
we greatly value feedback and contributions from our community. Please submit
your [issues][issues] or [pull requests][pull-requests] through GitHub.
## Tips
- The SDK is released under the [Apache license][license]. Any code you submit
will be released under that license. For substantial contributions, we may
ask you to sign a [Alibaba Documentation Corporate Contributor License
Agreement (CLA)][cla].
- We follow all of the relevant PSR recommendations from the [PHP Framework
Interop Group][php-fig]. Please submit code that follows these standards.
The [PHP CS Fixer][cs-fixer] tool can be helpful for formatting your code.
Your can use `composer fixer` to fix code.
- We maintain a high percentage of code coverage in our unit tests. If you make
changes to the code, please add, update, and/or remove tests as appropriate.
- If your code does not conform to the PSR standards, does not include adequate
tests, or does not contain a changelog document, we may ask you to update
your pull requests before we accept them. We also reserve the right to deny
any pull requests that do not align with our standards or goals.
[issues]: https://github.com/aliyun/openapi-sdk-php-client/issues
[pull-requests]: https://github.com/aliyun/openapi-sdk-php-client/pulls
[license]: http://www.apache.org/licenses/LICENSE-2.0
[cla]: https://alibaba-cla-2018.oss-cn-beijing.aliyuncs.com/Alibaba_Documentation_Open_Source_Corporate_CLA.pdf
[php-fig]: http://php-fig.org
[cs-fixer]: http://cs.sensiolabs.org/
[docs-readme]: https://github.com/aliyun/openapi-sdk-php-client/blob/master/README.md

13
vendor/alibabacloud/client/LICENSE.md vendored Normal file
View File

@ -0,0 +1,13 @@
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

88
vendor/alibabacloud/client/NOTICE.md vendored Normal file
View File

@ -0,0 +1,88 @@
# Alibaba Cloud Client for PHP
<https://www.alibabacloud.com/>
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
<http://www.apache.org/licenses/LICENSE-2.0>
or in the "license" file accompanying this file. This file is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
# Guzzle
<https://github.com/guzzle/guzzle>
Copyright (c) 2011-2018 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# jmespath.php
<https://github.com/mtdowling/jmespath.php>
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# Dot
<https://github.com/adbario/php-dot-notation>
Copyright (c) 2016-2019 Riku Särkinen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,168 @@
[English](/README.md) | 简体中文
# Alibaba Cloud Client for PHP
[![Latest Stable Version](https://poser.pugx.org/alibabacloud/client/v/stable)](https://packagist.org/packages/alibabacloud/client)
[![composer.lock](https://poser.pugx.org/alibabacloud/client/composerlock)](https://packagist.org/packages/alibabacloud/client)
[![Total Downloads](https://poser.pugx.org/alibabacloud/client/downloads)](https://packagist.org/packages/alibabacloud/client)
[![License](https://poser.pugx.org/alibabacloud/client/license)](https://packagist.org/packages/alibabacloud/client)
[![codecov](https://codecov.io/gh/aliyun/openapi-sdk-php-client/branch/master/graph/badge.svg?token=90Yd5Bne3S)](https://codecov.io/gh/aliyun/openapi-sdk-php-client)
[![PHP Version Require](http://poser.pugx.org/alibabacloud/client/require/php)](https://packagist.org/packages/alibabacloud/client)
![](https://aliyunsdk-pages.alicdn.com/icons/AlibabaCloud.svg)
Alibaba Cloud Client for PHP 是帮助 PHP 开发者管理凭据、发送请求的客户端工具,[Alibaba Cloud SDK for PHP][SDK] 由本工具提供底层支持。
## 使用诊断
[Troubleshoot](https://troubleshoot.api.aliyun.com/?source=github_sdk) 提供 OpenAPI 使用诊断服务,通过 `RequestID``报错信息` ,帮助开发者快速定位,为开发者提供解决方案。
## 在线示例
[阿里云 OpenAPI 开发者门户]https://next.api.aliyun.com/) 提供在线调用阿里云产品,并动态生成 SDK 代码和快速检索接口等能力,能显著降低使用云 API 的难度。
## 先决条件
您的系统需要满足[先决条件](/docs/zh-CN/0-Prerequisites.md),包括 PHP> = 5.5。 我们强烈建议使用cURL扩展并使用TLS后端编译cURL 7.16.2+。
## 安装依赖
如果已在系统上[全局安装 Composer](https://getcomposer.org/doc/00-intro.md#globally),请直接在项目目录中运行以下内容来安装 Alibaba Cloud Client for PHP 作为依赖项:
```
composer require alibabacloud/client
```
> 一些用户可能由于网络问题无法安装,可以使用[阿里云 Composer 全量镜像](https://developer.aliyun.com/composer)。
请看[安装](/docs/zh-CN/1-Installation.md)有关通过 Composer 和其他方式安装的详细信息。
## 快速使用
在您开始之前,您需要注册阿里云帐户并获取您的[凭证](https://usercenter.console.aliyun.com/#/manage/ak)。
```php
<?php
use AlibabaCloud\Client\AlibabaCloud;
AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')->asDefaultClient();
```
## 请求
> 请求风格分为 `ROA``RPC`,不同产品风格不同,使用前,请参考产品文档。推荐使用 [Alibaba Cloud SDK for PHP][SDK] ,细节已被封装,无需关心风格。
### ROA 请求
```php
<?php
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
try {
$result = AlibabaCloud::roa()
->regionId('cn-hangzhou') // 指定请求的区域,不指定则使用客户端区域、默认区域
->product('CS') // 指定产品
->version('2015-12-15') // 指定产品版本
->action('DescribeClusterServices') // 指定产品接口
->serviceCode('cs') // 设置 ServiceCode 以备寻址,非必须
->endpointType('openAPI') // 设置类型,非必须
->method('GET') // 指定请求方式
->host('cs.aliyun.com') // 指定域名则不会寻址,如认证方式为 Bearer Token 的服务则需要指定
->pathPattern('/clusters/[ClusterId]/services') // 指定ROA风格路径规则
->withClusterId('123456') // 为路径中参数赋值方法名with + 参数
->request(); // 发起请求并返回结果对象,请求需要放在设置的最后面
print_r($result->toArray());
} catch (ClientException $exception) {
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
```
### RPC 请求
```php
<?php
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
try {
$result = AlibabaCloud::rpc()
->product('Cdn')
->version('2014-11-11')
->action('DescribeCdnService')
->method('POST')
->request();
print_r($result->toArray());
} catch (ClientException $exception) {
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
```
## 文档
* [先决条件](/docs/zh-CN/0-Prerequisites.md)
* [安装](/docs/zh-CN/1-Installation.md)
* [客户端和凭证](/docs/zh-CN/2-Client.md)
* [请求](/docs/zh-CN/3-Request.md)
* [结果](/docs/zh-CN/4-Result.md)
* [区域](/docs/zh-CN/5-Region.md)
* [域名](/docs/zh-CN/6-Host.md)
* [SSL 验证](/docs/zh-CN/7-Verify.md)
* [调试](/docs/zh-CN/8-Debug.md)
* [日志](/docs/zh-CN/9-Log.md)
* [测试](/docs/zh-CN/10-Test.md)
## 问题
[提交 Issue](https://github.com/aliyun/openapi-sdk-php-client/issues/new/choose),不符合指南的问题可能会立即关闭。
## 发行说明
每个版本的详细更改记录在[发行说明](/CHANGELOG.md)中。
## 贡献
提交 Pull Request 之前请阅读[贡献指南](/CONTRIBUTING.md)。
## 相关
* [阿里云服务 Regions & Endpoints][endpoints]
* [阿里云 OpenAPI 开发者门户][open-api]
* [Packagist][packagist]
* [Composer][composer]
* [Guzzle中文文档][guzzle-docs]
* [最新源码][latest-release]
## 许可证
[Apache-2.0](/LICENSE.md)
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
[SDK]: https://github.com/aliyun/openapi-sdk-php
[open-api]: https://next.api.aliyun.com/
[latest-release]: https://github.com/aliyun/openapi-sdk-php-client
[guzzle-docs]: https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html
[composer]: https://getcomposer.org
[packagist]: https://packagist.org/packages/alibabacloud/sdk
[home]: https://home.console.aliyun.com
[aliyun]: https://www.aliyun.com
[regions]: https://help.aliyun.com/document_detail/40654.html
[endpoints]: https://developer.aliyun.com/endpoints
[cURL]: http://php.net/manual/zh/book.curl.php
[OPCache]: http://php.net/manual/zh/book.opcache.php
[xdebug]: http://xdebug.org
[OpenSSL]: http://php.net/manual/zh/book.openssl.php
[client]: https://github.com/aliyun/openapi-sdk-php-client

167
vendor/alibabacloud/client/README.md vendored Normal file
View File

@ -0,0 +1,167 @@
English | [简体中文](/README-zh-CN.md)
# Alibaba Cloud Client for PHP
[![Latest Stable Version](https://poser.pugx.org/alibabacloud/client/v/stable)](https://packagist.org/packages/alibabacloud/client)
[![composer.lock](https://poser.pugx.org/alibabacloud/client/composerlock)](https://packagist.org/packages/alibabacloud/client)
[![Total Downloads](https://poser.pugx.org/alibabacloud/client/downloads)](https://packagist.org/packages/alibabacloud/client)
[![License](https://poser.pugx.org/alibabacloud/client/license)](https://packagist.org/packages/alibabacloud/client)
[![codecov](https://codecov.io/gh/aliyun/openapi-sdk-php-client/branch/master/graph/badge.svg?token=90Yd5Bne3S)](https://codecov.io/gh/aliyun/openapi-sdk-php-client)
[![PHP Version Require](http://poser.pugx.org/alibabacloud/client/require/php)](https://packagist.org/packages/alibabacloud/client)
![](https://aliyunsdk-pages.alicdn.com/icons/AlibabaCloud.svg)
Alibaba Cloud Client for PHP is a client tool that helps PHP developers manage credentials and send requests, [Alibaba Cloud SDK for PHP][SDK] dependency on this tool.
## Troubleshoot
[Troubleshoot](https://troubleshoot.api.aliyun.com/?source=github_sdk) Provide OpenAPI diagnosis service to help developers locate quickly and provide solutions for developers through `RequestID` or `error message`.
## Online Demo
[Alibaba Cloud OpenAPI Developer Portal](https://next.api.aliyun.com/) provides the ability to call the cloud product OpenAPI online, and dynamically generate SDK Example code and quick retrieval interface, which can significantly reduce the difficulty of using the cloud API.
## Prerequisites
Your system will need to meet the [Prerequisites](/docs/en-US/0-Prerequisites.md), including having PHP >= 5.5. We highly recommend having it compiled with the cURL extension and cURL 7.16.2+.
## Installation
If Composer is already [installed globally on your system](https://getcomposer.org/doc/00-intro.md#globally), run the following in the base directory of your project to install Alibaba Cloud Client for PHP as a dependency:
```
composer require alibabacloud/client
```
> Some users may not be able to install due to network problems, you can try to switch the Composer mirror.
Please see the [Installation](/docs/en-US/1-Installation.md) for more detailed information about installing the Alibaba Cloud Client for PHP through Composer and other means.
## Quick Examples
Before you begin, you need to sign up for an Alibaba Cloud account and retrieve your [Credentials](https://usercenter.console.aliyun.com/#/manage/ak).
### Create Client
```php
<?php
use AlibabaCloud\Client\AlibabaCloud;
AlibabaCloud::accessKeyClient('accessKeyId', 'accessKeySecret')->asDefaultClient();
```
## Request
> Request styles are divided into `ROA` and `RPC`. Different product styles are different. Please refer to the product documentation before using. It is recommended to use [Alibaba cloud SDK for PHP][SDK], the details have been encapsulated, and you do not need to care about the style.
### ROA Request
```php
<?php
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
try {
$result = AlibabaCloud::roa()
->regionId('cn-hangzhou') // Specify the requested regionId, if not specified, use the client regionId, then default regionId
->product('CS') // Specify product
->version('2015-12-15') // Specify product version
->action('DescribeClusterServices') // Specify product interface
->serviceCode('cs') // Set ServiceCode for addressing, optional
->endpointType('openAPI') // Set type, optional
->method('GET') // Set request method
->host('cs.aliyun.com') // Location Service will not be enabled if the host is specified. For example, service with a Certification type-Bearer Token should be specified
->pathPattern('/clusters/[ClusterId]/services') // Specify path rule with ROA-style
->withClusterId('123456') // Assign values to parameters in the path. Method: with + Parameter
->request(); // Make a request and return to result object. The request is to be placed at the end of the setting
print_r($result->toArray());
} catch (ClientException $exception) {
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
```
### RPC Request
```php
<?php
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
try {
$result = AlibabaCloud::rpc()
->product('Cdn')
->version('2014-11-11')
->action('DescribeCdnService')
->method('POST')
->request();
print_r($result->toArray());
} catch (ClientException $exception) {
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
print_r($exception->getErrorMessage());
}
```
## Documentation
* [Prerequisites](/docs/en-US/0-Prerequisites.md)
* [Installation](/docs/en-US/1-Installation.md)
* [Client & Credentials](/docs/en-US/2-Client.md)
* [Request](/docs/en-US/3-Request.md)
* [Result](/docs/en-US/4-Result.md)
* [Region](/docs/en-US/5-Region.md)
* [Host](/docs/en-US/6-Host.md)
* [SSL Verify](/docs/en-US/7-Verify.md)
* [Debug](/docs/en-US/8-Debug.md)
* [Log](/docs/en-US/9-Log.md)
* [Test](/docs/en-US/10-Test.md)
## Issues
[Opening an Issue](https://github.com/aliyun/openapi-sdk-php-client/issues/new/choose), Issues not conforming to the guidelines may be closed immediately.
## Changelog
Detailed changes for each release are documented in the [release notes](/CHANGELOG.md).
## Contribution
Please make sure to read the [Contributing Guide](/CONTRIBUTING.md) before making a pull request.
## References
* [Alibaba Cloud Regions & Endpoints][endpoints]
* [Alibaba Cloud OpenAPI Developer Portal][open-api]
* [Packagist][packagist]
* [Composer][composer]
* [Guzzle Documentation][guzzle-docs]
* [Latest Release][latest-release]
## License
[Apache-2.0](/LICENSE.md)
Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
[SDK]: https://github.com/aliyun/openapi-sdk-php
[open-api]: https://next.api.aliyun.com/
[latest-release]: https://github.com/aliyun/openapi-sdk-php-client
[guzzle-docs]: http://docs.guzzlephp.org/en/stable/request-options.html
[composer]: https://getcomposer.org
[packagist]: https://packagist.org/packages/alibabacloud/sdk
[home]: https://home.console.aliyun.com
[alibabacloud]: https://www.alibabacloud.com
[regions]: https://www.alibabacloud.com/help/doc-detail/40654.html
[endpoints]: https://developer.aliyun.com/endpoints
[cURL]: http://php.net/manual/en/book.curl.php
[OPCache]: http://php.net/manual/en/book.opcache.php
[xdebug]: http://xdebug.org
[OpenSSL]: http://php.net/manual/en/book.openssl.php
[client]: https://github.com/aliyun/openapi-sdk-php-client

View File

@ -0,0 +1,6 @@
Upgrading Guide
===============
1.x
-----------------------
- This is the first version. See <https://github.com/aliyun/openapi-sdk-php-client> for more information.

17
vendor/alibabacloud/client/autoload.php vendored Normal file
View File

@ -0,0 +1,17 @@
<?php
if (\file_exists(__DIR__ . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php')) {
require_once __DIR__ . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
}
spl_autoload_register(function ($class) {
$name = \str_replace('AlibabaCloud\\Client\\', '', $class);
$file = __DIR__ . \DIRECTORY_SEPARATOR . 'src' . \DIRECTORY_SEPARATOR . \str_replace('\\', \DIRECTORY_SEPARATOR, $name) . '.php';
if (\file_exists($file)) {
require_once $file;
return true;
}
return false;
});

134
vendor/alibabacloud/client/composer.json vendored Normal file
View File

@ -0,0 +1,134 @@
{
"name": "alibabacloud/client",
"homepage": "https://www.alibabacloud.com/",
"description": "Alibaba Cloud Client for PHP - Use Alibaba Cloud in your PHP project",
"keywords": [
"sdk",
"tool",
"cloud",
"client",
"aliyun",
"library",
"alibaba",
"alibabacloud"
],
"type": "library",
"license": "Apache-2.0",
"support": {
"source": "https://github.com/aliyun/openapi-sdk-php-client",
"issues": "https://github.com/aliyun/openapi-sdk-php-client/issues"
},
"authors": [
{
"name": "Alibaba Cloud SDK",
"email": "sdk-team@alibabacloud.com",
"homepage": "http://www.alibabacloud.com"
}
],
"require": {
"php": ">=5.5",
"ext-curl": "*",
"ext-json": "*",
"ext-libxml": "*",
"ext-openssl": "*",
"ext-mbstring": "*",
"ext-simplexml": "*",
"ext-xmlwriter": "*",
"guzzlehttp/guzzle": "^6.3|^7.0",
"mtdowling/jmespath.php": "^2.5",
"adbario/php-dot-notation": "^2.4.1",
"clagiordano/weblibs-configmanager": "^1.0"
},
"require-dev": {
"ext-spl": "*",
"ext-dom": "*",
"ext-pcre": "*",
"psr/cache": "^1.0",
"ext-sockets": "*",
"drupal/coder": "^8.3",
"symfony/dotenv": "^3.4",
"league/climate": "^3.2.4",
"phpunit/phpunit": "^5.7|^6.6|^7.5|^8.5|^9.5",
"monolog/monolog": "^1.24",
"composer/composer": "^1.8",
"mikey179/vfsstream": "^1.6",
"symfony/var-dumper": "^3.4"
},
"suggest": {
"ext-sockets": "To use client-side monitoring"
},
"autoload": {
"psr-4": {
"AlibabaCloud\\Client\\": "src"
},
"files": [
"src/Functions.php"
]
},
"autoload-dev": {
"psr-4": {
"AlibabaCloud\\Client\\Tests\\": "tests/"
}
},
"config": {
"preferred-install": "dist",
"optimize-autoloader": true,
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts-descriptions": {
"cs": "Tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard.",
"cbf": "Automatically correct coding standard violations.",
"fixer": "Fixes code to follow standards.",
"test": "Run all tests.",
"unit": "Run Unit tests.",
"feature": "Run Feature tests.",
"clearCache": "Clear cache like coverage.",
"coverage": "Show Coverage html.",
"endpoints": "Update endpoints from OSS."
},
"scripts": {
"cs": "phpcs --standard=PSR2 -n ./",
"cbf": "phpcbf --standard=PSR2 -n ./",
"fixer": "php-cs-fixer fix ./",
"test": [
"phpunit --colors=always"
],
"test4HighVersion": [
"@clearCache",
"phpunit --testsuite=Test4HighVersion --colors=always"
],
"test4LowVersion": [
"@clearCache",
"phpunit --testsuite=Test4LowVersion --colors=always"
],
"unit4HighVersion": [
"@clearCache",
"phpunit --testsuite=Unit4HighVersion --colors=always"
],
"unit4LowVersion": [
"@clearCache",
"phpunit --testsuite=Unit4LowVersion --colors=always"
],
"feature4HighVersion": [
"@clearCache",
"phpunit --testsuite=Feature4HighVersion --colors=always"
],
"feature4LowVersion": [
"@clearCache",
"phpunit --testsuite=Feature4LowVersion --colors=always"
],
"coverage": "open cache/coverage/index.html",
"clearCache": "rm -rf cache/*",
"endpoints": [
"AlibabaCloud\\Client\\Regions\\LocationService::updateEndpoints",
"@fixer"
],
"release": [
"AlibabaCloud\\Client\\Release::release"
]
}
}

View File

@ -0,0 +1,53 @@
<?php
namespace AlibabaCloud\Client;
/**
* Class Accept
*
* @package AlibabaCloud\Client
*/
class Accept
{
/**
* @var string
*/
private $format;
/**
* Accept constructor.
*
* @param string $format
*/
private function __construct($format)
{
$this->format = $format;
}
/**
* @param $format
*
* @return Accept
*/
public static function create($format)
{
return new static($format);
}
/**
* @return mixed|string
*/
public function toString()
{
$key = \strtoupper($this->format);
$list = [
'JSON' => 'application/json',
'XML' => 'application/xml',
'RAW' => 'application/octet-stream',
'FORM' => 'application/x-www-form-urlencoded'
];
return isset($list[$key]) ? $list[$key] : $list['RAW'];
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace AlibabaCloud\Client;
use AlibabaCloud\Client\Traits\LogTrait;
use AlibabaCloud\Client\Traits\MockTrait;
use AlibabaCloud\Client\Traits\ClientTrait;
use AlibabaCloud\Client\Traits\HistoryTrait;
use AlibabaCloud\Client\Traits\RequestTrait;
use AlibabaCloud\Client\Traits\EndpointTrait;
use AlibabaCloud\Client\Traits\DefaultRegionTrait;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class AlibabaCloud
*
* @package AlibabaCloud\Client
* @mixin \AlibabaCloud\IdeHelper
*/
class AlibabaCloud
{
use ClientTrait;
use DefaultRegionTrait;
use EndpointTrait;
use RequestTrait;
use MockTrait;
use HistoryTrait;
use LogTrait;
/**
* Version of the Client
*/
const VERSION = '1.5.32';
/**
* This static method can directly call the specific service.
*
* @param string $product
* @param array $arguments
*
* @codeCoverageIgnore
* @return object
* @throws ClientException
*/
public static function __callStatic($product, $arguments)
{
$product = \ucfirst($product);
$product_class = 'AlibabaCloud' . '\\' . $product . '\\' . $product;
if (\class_exists($product_class)) {
return new $product_class;
}
throw new ClientException(
"May not yet support product $product quick access, "
. 'you can use [Alibaba Cloud Client for PHP] to send any custom '
. 'requests: https://github.com/aliyun/openapi-sdk-php-client/blob/master/docs/en-US/3-Request.md',
SDK::SERVICE_NOT_FOUND
);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Signature\ShaHmac1Signature;
use AlibabaCloud\Client\Credentials\AccessKeyCredential;
/**
* Use the AccessKey to complete the authentication.
*
* @package AlibabaCloud\Client\Clients
*/
class AccessKeyClient extends Client
{
/**
* @param string $accessKeyId
* @param string $accessKeySecret
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret)
{
parent::__construct(
new AccessKeyCredential($accessKeyId, $accessKeySecret),
new ShaHmac1Signature()
);
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Signature\BearerTokenSignature;
use AlibabaCloud\Client\Credentials\BearerTokenCredential;
/**
* Use the Bearer Token to complete the authentication.
*
* @package AlibabaCloud\Client\Clients
*/
class BearerTokenClient extends Client
{
/**
* @param string $bearerToken
*
* @throws ClientException
*/
public function __construct($bearerToken)
{
parent::__construct(
new BearerTokenCredential($bearerToken),
new BearerTokenSignature()
);
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Traits\HttpTrait;
use AlibabaCloud\Client\Traits\RegionTrait;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Signature\ShaHmac1Signature;
use AlibabaCloud\Client\Signature\SignatureInterface;
use AlibabaCloud\Client\Signature\ShaHmac256Signature;
use AlibabaCloud\Client\Signature\BearerTokenSignature;
use AlibabaCloud\Client\Credentials\AccessKeyCredential;
use AlibabaCloud\Client\Credentials\CredentialsInterface;
use AlibabaCloud\Client\Credentials\EcsRamRoleCredential;
use AlibabaCloud\Client\Credentials\RamRoleArnCredential;
use AlibabaCloud\Client\Credentials\RsaKeyPairCredential;
use AlibabaCloud\Client\Credentials\BearerTokenCredential;
use AlibabaCloud\Client\Signature\ShaHmac256WithRsaSignature;
/**
* Custom Client.
*
* @package AlibabaCloud\Client\Clients
*/
class Client
{
use HttpTrait;
use RegionTrait;
use ManageTrait;
/**
* @var CredentialsInterface|AccessKeyCredential|BearerTokenCredential|StsCredential|EcsRamRoleCredential|RamRoleArnCredential|RsaKeyPairCredential
*/
private $credential;
/**
* @var SignatureInterface
*/
private $signature;
/**
* Self constructor.
*
* @param CredentialsInterface $credential
* @param SignatureInterface $signature
*/
public function __construct(CredentialsInterface $credential, SignatureInterface $signature)
{
$this->credential = $credential;
$this->signature = $signature;
$this->options['connect_timeout'] = Request::CONNECT_TIMEOUT;
$this->options['timeout'] = Request::TIMEOUT;
$this->options['verify'] = false;
}
/**
* @return AccessKeyCredential|BearerTokenCredential|CredentialsInterface|EcsRamRoleCredential|RamRoleArnCredential|RsaKeyPairCredential|StsCredential
*/
public function getCredential()
{
return $this->credential;
}
/**
* @return SignatureInterface|BearerTokenSignature|ShaHmac1Signature|ShaHmac256Signature|ShaHmac256WithRsaSignature
*/
public function getSignature()
{
return $this->signature;
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Signature\ShaHmac1Signature;
use AlibabaCloud\Client\Credentials\EcsRamRoleCredential;
/**
* Use the RAM role of an ECS instance to complete the authentication.
*/
class EcsRamRoleClient extends Client
{
/**
* @param string $roleName
*
* @throws ClientException
*/
public function __construct($roleName)
{
parent::__construct(
new EcsRamRoleCredential($roleName),
new ShaHmac1Signature()
);
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Filter\Filter;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\CredentialsInterface;
use AlibabaCloud\Client\Credentials\EcsRamRoleCredential;
use AlibabaCloud\Client\Credentials\RamRoleArnCredential;
use AlibabaCloud\Client\Credentials\RsaKeyPairCredential;
use AlibabaCloud\Client\Credentials\Providers\EcsRamRoleProvider;
use AlibabaCloud\Client\Credentials\Providers\RamRoleArnProvider;
use AlibabaCloud\Client\Credentials\Providers\RsaKeyPairProvider;
use AlibabaCloud\Client\Credentials\Providers\CredentialsProvider;
/**
* Trait ManageTrait.
*
* @mixin Client
*/
trait ManageTrait
{
/**
* @param int $timeout
* @param int $connectTimeout
*
* @return CredentialsInterface|StsCredential
*
* @throws ClientException
* @throws ServerException
*/
public function getSessionCredential($timeout = Request::TIMEOUT, $connectTimeout = Request::CONNECT_TIMEOUT)
{
switch (\get_class($this->credential)) {
case EcsRamRoleCredential::class:
return (new EcsRamRoleProvider($this))->get();
case RamRoleArnCredential::class:
return (new RamRoleArnProvider($this))->get($timeout, $connectTimeout);
case RsaKeyPairCredential::class:
return (new RsaKeyPairProvider($this))->get($timeout, $connectTimeout);
default:
return $this->credential;
}
}
/**
* @return static
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public function asGlobalClient()
{
return $this->asDefaultClient();
}
/**
* Set the current client as the default client.
*
* @return static
* @throws ClientException
*/
public function asDefaultClient()
{
return $this->name(CredentialsProvider::getDefaultName());
}
/**
* Naming clients.
*
* @param string $name
*
* @return static
* @throws ClientException
*/
public function name($name)
{
Filter::name($name);
return AlibabaCloud::set($name, $this);
}
/**
* @return bool
*/
public function isDebug()
{
if (isset($this->options['debug'])) {
return $this->options['debug'] === true && PHP_SAPI === 'cli';
}
return false;
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Signature\ShaHmac1Signature;
use AlibabaCloud\Client\Credentials\RamRoleArnCredential;
/**
* Use the AssumeRole of the RAM account to complete the authentication.
*
* @package AlibabaCloud\Client\Clients
*/
class RamRoleArnClient extends Client
{
/**
* @param string $accessKeyId
* @param string $accessKeySecret
* @param string $roleArn
* @param string $roleSessionName
* @param string|array $policy
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret, $roleArn, $roleSessionName, $policy = '')
{
parent::__construct(
new RamRoleArnCredential($accessKeyId, $accessKeySecret, $roleArn, $roleSessionName, $policy),
new ShaHmac1Signature()
);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Signature\ShaHmac1Signature;
use AlibabaCloud\Client\Credentials\RsaKeyPairCredential;
/**
* Use the RSA key pair to complete the authentication (supported only on Japanese site)
*
* @package AlibabaCloud\Client\Clients
*/
class RsaKeyPairClient extends Client
{
/**
* @param string $publicKeyId
* @param string $privateKeyFile
*
* @throws ClientException
*/
public function __construct($publicKeyId, $privateKeyFile)
{
parent::__construct(
new RsaKeyPairCredential($publicKeyId, $privateKeyFile),
new ShaHmac1Signature()
);
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace AlibabaCloud\Client\Clients;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Signature\ShaHmac1Signature;
/**
* Use the STS Token to complete the authentication.
*/
class StsClient extends Client
{
/**
* @param string $accessKeyId Access key ID
* @param string $accessKeySecret Access Key Secret
* @param string $securityToken Security Token
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret, $securityToken = '')
{
parent::__construct(
new StsCredential($accessKeyId, $accessKeySecret, $securityToken),
new ShaHmac1Signature()
);
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace AlibabaCloud\Client\Config;
use Exception;
use clagiordano\weblibs\configmanager\ConfigManager;
/**
* Class Config
*
* @package AlibabaCloud\Client\Config
*/
class Config
{
/**
* @var ConfigManager|null
*/
private static $configManager;
/**
* @param string $configPath
*
* @param string|null $defaultValue
*
* @return mixed
*/
public static function get($configPath, $defaultValue = null)
{
return self::getConfigManager()
->getValue(
\strtolower($configPath),
$defaultValue
);
}
/**
* @return ConfigManager
*/
private static function getConfigManager()
{
if (!self::$configManager instanceof ConfigManager) {
self::$configManager = new ConfigManager(__DIR__ . DIRECTORY_SEPARATOR . 'Data.php');
}
return self::$configManager;
}
/**
* @param string $configPath
* @param mixed $newValue
*
* @return ConfigManager
* @throws Exception
*/
public static function set($configPath, $newValue)
{
self::getConfigManager()->setValue(\strtolower($configPath), $newValue);
return self::getConfigManager()->saveConfigFile();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,65 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the AccessKey to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class AccessKeyCredential implements CredentialsInterface
{
/**
* @var string
*/
private $accessKeyId;
/**
* @var string
*/
private $accessKeySecret;
/**
* AccessKeyCredential constructor.
*
* @param string $accessKeyId Access key ID
* @param string $accessKeySecret Access Key Secret
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret)
{
CredentialFilter::AccessKey($accessKeyId, $accessKeySecret);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return $this->accessKeyId;
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return $this->accessKeySecret;
}
/**
* @return string
*/
public function __toString()
{
return "$this->accessKeyId#$this->accessKeySecret";
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class BearerTokenCredential
*
* @package AlibabaCloud\Client\Credentials
*/
class BearerTokenCredential implements CredentialsInterface
{
/**
* @var string
*/
private $bearerToken;
/**
* Class constructor.
*
* @param string $bearerToken
*
* @throws ClientException
*/
public function __construct($bearerToken)
{
CredentialFilter::bearerToken($bearerToken);
$this->bearerToken = $bearerToken;
}
/**
* @return string
*/
public function getBearerToken()
{
return $this->bearerToken;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return '';
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return '';
}
/**
* @return string
*/
public function __toString()
{
return "bearerToken#$this->bearerToken";
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace AlibabaCloud\Client\Credentials;
/**
* interface CredentialsInterface
*
* @package AlibabaCloud\Client\Credentials
*
* @codeCoverageIgnore
*/
interface CredentialsInterface
{
/**
* @return string
*/
public function __toString();
}

View File

@ -0,0 +1,50 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the RAM role of an ECS instance to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class EcsRamRoleCredential implements CredentialsInterface
{
/**
* @var string
*/
private $roleName;
/**
* Class constructor.
*
* @param string $roleName
*
* @throws ClientException
*/
public function __construct($roleName)
{
CredentialFilter::roleName($roleName);
$this->roleName = $roleName;
}
/**
* @return string
*/
public function getRoleName()
{
return $this->roleName;
}
/**
* @return string
*/
public function __toString()
{
return "roleName#$this->roleName";
}
}

View File

@ -0,0 +1,181 @@
<?php
namespace AlibabaCloud\Client\Credentials\Ini;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Clients\AccessKeyClient;
use AlibabaCloud\Client\Clients\RamRoleArnClient;
use AlibabaCloud\Client\Clients\RsaKeyPairClient;
use AlibabaCloud\Client\Clients\EcsRamRoleClient;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Clients\BearerTokenClient;
/**
* Trait CreateTrait
*
* @package AlibabaCloud\Client\Credentials\Ini
*
* @mixin IniCredential
*/
trait CreateTrait
{
/**
* @param string $clientName
* @param array $credential
*
* @return Client|bool
* @throws ClientException
*/
protected function createClient($clientName, array $credential)
{
if (!isset($credential['enable']) || !$credential['enable']) {
return false;
}
if (!isset($credential['type'])) {
$this->missingRequired('type', $clientName);
}
return $this->createClientByType($clientName, $credential)->name($clientName);
}
/**
* @param string $clientName
* @param array $credential
*
* @return AccessKeyClient|BearerTokenClient|EcsRamRoleClient|RamRoleArnClient|RsaKeyPairClient
* @throws ClientException
*/
private function createClientByType($clientName, array $credential)
{
switch (\strtolower($credential['type'])) {
case 'access_key':
return $this->accessKeyClient($clientName, $credential);
case 'ecs_ram_role':
return $this->ecsRamRoleClient($clientName, $credential);
case 'ram_role_arn':
return $this->ramRoleArnClient($clientName, $credential);
case 'bearer_token':
return $this->bearerTokenClient($clientName, $credential);
case 'rsa_key_pair':
return $this->rsaKeyPairClient($clientName, $credential);
default:
throw new ClientException(
"Invalid type '{$credential['type']}' for '$clientName' in {$this->filename}",
SDK::INVALID_CREDENTIAL
);
}
}
/**
* @param array $credential
* @param string $clientName
*
* @return AccessKeyClient
* @throws ClientException
*/
private function accessKeyClient($clientName, array $credential)
{
if (!isset($credential['access_key_id'])) {
$this->missingRequired('access_key_id', $clientName);
}
if (!isset($credential['access_key_secret'])) {
$this->missingRequired('access_key_secret', $clientName);
}
return new AccessKeyClient(
$credential['access_key_id'],
$credential['access_key_secret']
);
}
/**
* @param string $clientName
* @param array $credential
*
* @return EcsRamRoleClient
* @throws ClientException
*/
private function ecsRamRoleClient($clientName, array $credential)
{
if (!isset($credential['role_name'])) {
$this->missingRequired('role_name', $clientName);
}
return new EcsRamRoleClient($credential['role_name']);
}
/**
* @param string $clientName
* @param array $credential
*
* @return RamRoleArnClient
* @throws ClientException
*/
private function ramRoleArnClient($clientName, array $credential)
{
if (!isset($credential['access_key_id'])) {
$this->missingRequired('access_key_id', $clientName);
}
if (!isset($credential['access_key_secret'])) {
$this->missingRequired('access_key_secret', $clientName);
}
if (!isset($credential['role_arn'])) {
$this->missingRequired('role_arn', $clientName);
}
if (!isset($credential['role_session_name'])) {
$this->missingRequired('role_session_name', $clientName);
}
return new RamRoleArnClient(
$credential['access_key_id'],
$credential['access_key_secret'],
$credential['role_arn'],
$credential['role_session_name']
);
}
/**
* @param string $clientName
* @param array $credential
*
* @return BearerTokenClient
* @throws ClientException
*/
private function bearerTokenClient($clientName, array $credential)
{
if (!isset($credential['bearer_token'])) {
$this->missingRequired('bearer_token', $clientName);
}
return new BearerTokenClient($credential['bearer_token']);
}
/**
* @param array $credential
* @param string $clientName
*
* @return RsaKeyPairClient
* @throws ClientException
*/
private function rsaKeyPairClient($clientName, array $credential)
{
if (!isset($credential['public_key_id'])) {
$this->missingRequired('public_key_id', $clientName);
}
if (!isset($credential['private_key_file'])) {
$this->missingRequired('private_key_file', $clientName);
}
return new RsaKeyPairClient(
$credential['public_key_id'],
$credential['private_key_file']
);
}
}

View File

@ -0,0 +1,209 @@
<?php
namespace AlibabaCloud\Client\Credentials\Ini;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class IniCredential
*
* @package AlibabaCloud\Client\Credentials\Ini
*/
class IniCredential
{
use CreateTrait;
use OptionsTrait;
/**
* @var array
*/
private static $hasLoaded;
/**
* @var string
*/
protected $filename;
/**
* IniCredential constructor.
*
* @param string $filename
*/
public function __construct($filename = '')
{
$this->filename = $filename ?: $this->getDefaultFile();
}
/**
* Get the default credential file.
*
* @return string
*/
public function getDefaultFile()
{
return self::getHomeDirectory() . DIRECTORY_SEPARATOR . '.alibabacloud' . DIRECTORY_SEPARATOR . 'credentials';
}
/**
* Gets the environment's HOME directory.
*
* @return null|string
*/
private static function getHomeDirectory()
{
if (getenv('HOME')) {
return getenv('HOME');
}
return (getenv('HOMEDRIVE') && getenv('HOMEPATH'))
? getenv('HOMEDRIVE') . getenv('HOMEPATH')
: null;
}
/**
* Clear credential cache.
*
* @return void
*/
public static function forgetLoadedCredentialsFile()
{
self::$hasLoaded = [];
}
/**
* Get the credential file.
*
* @return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* @param array $array
* @param string $key
*
* @return bool
*/
protected static function isNotEmpty(array $array, $key)
{
return isset($array[$key]) && !empty($array[$key]);
}
/**
* @param string $key
* @param string $clientName
*
* @throws ClientException
*/
public function missingRequired($key, $clientName)
{
throw new ClientException(
"Missing required '$key' option for '$clientName' in " . $this->getFilename(),
SDK::INVALID_CREDENTIAL
);
}
/**
* @return array|mixed
* @throws ClientException
*/
public function load()
{
// If it has been loaded, assign the client directly.
if (isset(self::$hasLoaded[$this->filename])) {
/**
* @var $client Client
*/
foreach (self::$hasLoaded[$this->filename] as $projectName => $client) {
$client->name($projectName);
}
return self::$hasLoaded[$this->filename];
}
return $this->loadFile();
}
/**
* Exceptions will be thrown if the file is unreadable and not the default file.
*
* @return array|mixed
* @throws ClientException
*/
private function loadFile()
{
if (!\AlibabaCloud\Client\inOpenBasedir($this->filename)) {
return [];
}
if (!\is_readable($this->filename) || !\is_file($this->filename)) {
if ($this->filename === $this->getDefaultFile()) {
// @codeCoverageIgnoreStart
return [];
// @codeCoverageIgnoreEnd
}
throw new ClientException(
'Credential file is not readable: ' . $this->getFilename(),
SDK::INVALID_CREDENTIAL
);
}
return $this->parseFile();
}
/**
* Decode the ini file into an array.
*
* @return array|mixed
* @throws ClientException
*/
private function parseFile()
{
try {
$file = \parse_ini_file($this->filename, true);
if (\is_array($file) && $file !== []) {
return $this->initClients($file);
}
throw new ClientException(
'Format error: ' . $this->getFilename(),
SDK::INVALID_CREDENTIAL
);
} catch (\Exception $e) {
throw new ClientException(
$e->getMessage(),
SDK::INVALID_CREDENTIAL,
$e
);
}
}
/**
* Initialize clients.
*
* @param array $array
*
* @return array|mixed
* @throws ClientException
*/
private function initClients($array)
{
foreach (\array_change_key_case($array) as $clientName => $configures) {
$configures = \array_change_key_case($configures);
$clientInstance = $this->createClient($clientName, $configures);
if ($clientInstance instanceof Client) {
self::$hasLoaded[$this->filename][$clientName] = $clientInstance;
self::setClientAttributes($configures, $clientInstance);
self::setCert($configures, $clientInstance);
self::setProxy($configures, $clientInstance);
}
}
return isset(self::$hasLoaded[$this->filename])
? self::$hasLoaded[$this->filename]
: [];
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace AlibabaCloud\Client\Credentials\Ini;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Trait OptionsTrait
*
* @package AlibabaCloud\Client\Credentials\Ini
*
* @mixin IniCredential
*/
trait OptionsTrait
{
/**
* @param array $configures
* @param Client $client
*
* @throws ClientException
*/
private static function setClientAttributes($configures, Client $client)
{
if (self::isNotEmpty($configures, 'region_id')) {
$client->regionId($configures['region_id']);
}
if (isset($configures['debug'])) {
$client->options(
[
'debug' => (bool)$configures['debug'],
]
);
}
if (self::isNotEmpty($configures, 'timeout')) {
$client->options(
[
'timeout' => $configures['timeout'],
]
);
}
if (self::isNotEmpty($configures, 'connect_timeout')) {
$client->options(
[
'connect_timeout' => $configures['connect_timeout'],
]
);
}
}
/**
* @param array $configures
* @param Client $client
*/
private static function setProxy($configures, Client $client)
{
if (self::isNotEmpty($configures, 'proxy')) {
$client->options(
[
'proxy' => $configures['proxy'],
]
);
}
$proxy = [];
if (self::isNotEmpty($configures, 'proxy_http')) {
$proxy['http'] = $configures['proxy_http'];
}
if (self::isNotEmpty($configures, 'proxy_https')) {
$proxy['https'] = $configures['proxy_https'];
}
if (self::isNotEmpty($configures, 'proxy_no')) {
$proxy['no'] = \explode(',', $configures['proxy_no']);
}
if ($proxy !== []) {
$client->options(
[
'proxy' => $proxy,
]
);
}
}
/**
* @param array $configures
* @param Client $client
*/
private static function setCert($configures, Client $client)
{
if (self::isNotEmpty($configures, 'cert_file') && !self::isNotEmpty($configures, 'cert_password')) {
$client->options(
[
'cert' => $configures['cert_file'],
]
);
}
if (self::isNotEmpty($configures, 'cert_file') && self::isNotEmpty($configures, 'cert_password')) {
$client->options(
[
'cert' => [
$configures['cert_file'],
$configures['cert_password'],
],
]
);
}
}
}

View File

@ -0,0 +1,170 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use Closure;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class CredentialsProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class CredentialsProvider
{
/**
* @var array
*/
private static $customChains;
/**
* @throws ClientException
*/
public static function chain()
{
$providers = func_get_args();
if (empty($providers)) {
throw new ClientException('No providers in chain', SDK::INVALID_ARGUMENT);
}
foreach ($providers as $provider) {
if (!$provider instanceof Closure) {
throw new ClientException('Providers must all be Closures', SDK::INVALID_ARGUMENT);
}
}
self::$customChains = $providers;
}
/**
* Forget the custom providers chain.
*/
public static function flush()
{
self::$customChains = [];
}
/**
* @return bool
*/
public static function hasCustomChain()
{
return (bool)self::$customChains;
}
/**
* @param string $clientName
*
* @throws ClientException
*/
public static function customProvider($clientName)
{
foreach (self::$customChains as $provider) {
$provider();
if (AlibabaCloud::has($clientName)) {
break;
}
}
}
/**
* @param string $clientName
*
* @throws ClientException
*/
public static function defaultProvider($clientName)
{
$providers = [
self::env(),
self::ini(),
self::instance(),
];
foreach ($providers as $provider) {
$provider();
if (AlibabaCloud::has($clientName)) {
break;
}
}
}
/**
* @return Closure
*/
public static function env()
{
return static function () {
$accessKeyId = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
if ($accessKeyId && $accessKeySecret) {
AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->asDefaultClient();
}
};
}
/**
* @return Closure
*/
public static function ini()
{
return static function () {
$ini = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_CREDENTIALS_FILE');
if ($ini) {
AlibabaCloud::load($ini);
} else {
// @codeCoverageIgnoreStart
AlibabaCloud::load();
// @codeCoverageIgnoreEnd
}
self::compatibleWithGlobal();
};
}
/**
* @codeCoverageIgnore
*
* Compatible with global
*
* @throws ClientException
*/
private static function compatibleWithGlobal()
{
if (AlibabaCloud::has('global') && !AlibabaCloud::has(self::getDefaultName())) {
AlibabaCloud::get('global')->name(self::getDefaultName());
}
}
/**
* @return array|false|string
* @throws ClientException
*/
public static function getDefaultName()
{
$name = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_PROFILE');
if ($name) {
return $name;
}
return 'default';
}
/**
* @return Closure
*/
public static function instance()
{
return static function () {
$instance = \AlibabaCloud\Client\envNotEmpty('ALIBABA_CLOUD_ECS_METADATA');
if ($instance) {
AlibabaCloud::ecsRamRoleClient($instance)->asDefaultClient();
}
};
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use Exception;
use AlibabaCloud\Client\Support\Stringy;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Result\Result;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\GuzzleException;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\EcsRamRoleCredential;
/**
* Class EcsRamRoleProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class EcsRamRoleProvider extends Provider
{
/**
* Expiration time slot for temporary security credentials.
*
* @var int
*/
protected $expirationSlot = 10;
/**
* @var string
*/
private $uri = 'http://100.100.100.200/latest/meta-data/ram/security-credentials/';
/**
* Get credential.
*
* @return StsCredential
* @throws ClientException
* @throws ServerException
*/
public function get()
{
$result = $this->getCredentialsInCache();
if ($result === null) {
$result = $this->request();
if (!isset($result['AccessKeyId'], $result['AccessKeySecret'], $result['SecurityToken'])) {
throw new ServerException($result, $this->error, SDK::INVALID_CREDENTIAL);
}
$this->cache($result->toArray());
}
return new StsCredential(
$result['AccessKeyId'],
$result['AccessKeySecret'],
$result['SecurityToken']
);
}
/**
* Get credentials by request.
*
* @return Result
* @throws ClientException
* @throws ServerException
*/
public function request()
{
$result = $this->getResponse();
if ($result->getStatusCode() === 404) {
$message = 'The role was not found in the instance';
throw new ClientException($message, SDK::INVALID_CREDENTIAL);
}
if (!$result->isSuccess()) {
$message = 'Error retrieving credentials from result';
throw new ServerException($result, $message, SDK::INVALID_CREDENTIAL);
}
return $result;
}
/**
* Get data from meta.
*
* @return mixed|ResponseInterface
* @throws ClientException
* @throws Exception
*/
public function getResponse()
{
/**
* @var EcsRamRoleCredential $credential
*/
$credential = $this->client->getCredential();
$url = $this->uri . $credential->getRoleName();
$options = [
'http_errors' => false,
'timeout' => 1,
'connect_timeout' => 1,
'debug' => $this->client->isDebug(),
];
try {
return RpcRequest::createClient()->request('GET', $url, $options);
} catch (GuzzleException $exception) {
if (Stringy::contains($exception->getMessage(), 'timed')) {
$message = 'Timeout or instance does not belong to Alibaba Cloud';
} else {
$message = $exception->getMessage();
}
throw new ClientException(
$message,
SDK::SERVER_UNREACHABLE,
$exception
);
}
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use AlibabaCloud\Client\Clients\Client;
/**
* Class Provider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class Provider
{
/**
* For TSC Duration Seconds
*/
const DURATION_SECONDS = 3600;
/**
* @var array
*/
protected static $credentialsCache = [];
/**
* Expiration time slot for temporary security credentials.
*
* @var int
*/
protected $expirationSlot = 180;
/**
* @var Client
*/
protected $client;
/**
* @var string
*/
protected $error = 'Result contains no credentials';
/**
* CredentialTrait constructor.
*
* @param Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* Get the credentials from the cache in the validity period.
*
* @return array|null
*/
public function getCredentialsInCache()
{
if (isset(self::$credentialsCache[$this->key()])) {
$result = self::$credentialsCache[$this->key()];
if (\strtotime($result['Expiration']) - \time() >= $this->expirationSlot) {
return $result;
}
unset(self::$credentialsCache[$this->key()]);
}
return null;
}
/**
* Get the toString of the credentials as the key.
*
* @return string
*/
protected function key()
{
return (string)$this->client->getCredential();
}
/**
* Cache credentials.
*
* @param array $credential
*/
protected function cache(array $credential)
{
self::$credentialsCache[$this->key()] = $credential;
}
}

View File

@ -0,0 +1,84 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Result\Result;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Credentials\StsCredential;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Client\Credentials\Requests\AssumeRole;
/**
* Class RamRoleArnProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class RamRoleArnProvider extends Provider
{
/**
* Get credential.
*
*
* @param int $timeout
* @param int $connectTimeout
*
* @return StsCredential
* @throws ClientException
* @throws ServerException
*/
public function get($timeout = Request::TIMEOUT, $connectTimeout = Request::CONNECT_TIMEOUT)
{
$credential = $this->getCredentialsInCache();
if (null === $credential) {
$result = $this->request($timeout, $connectTimeout);
if (!isset($result['Credentials']['AccessKeyId'],
$result['Credentials']['AccessKeySecret'],
$result['Credentials']['SecurityToken'])) {
throw new ServerException($result, $this->error, SDK::INVALID_CREDENTIAL);
}
$credential = $result['Credentials'];
$this->cache($credential);
}
return new StsCredential(
$credential['AccessKeyId'],
$credential['AccessKeySecret'],
$credential['SecurityToken']
);
}
/**
* Get credentials by request.
*
* @param $timeout
* @param $connectTimeout
*
* @return Result
* @throws ClientException
* @throws ServerException
*/
private function request($timeout, $connectTimeout)
{
$clientName = __CLASS__ . \uniqid('ak', true);
$credential = $this->client->getCredential();
AlibabaCloud::accessKeyClient(
$credential->getAccessKeyId(),
$credential->getAccessKeySecret()
)->name($clientName);
return (new AssumeRole($credential))
->client($clientName)
->timeout($timeout)
->connectTimeout($connectTimeout)
->debug($this->client->isDebug())
->request();
}
}

View File

@ -0,0 +1,86 @@
<?php
namespace AlibabaCloud\Client\Credentials\Providers;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Result\Result;
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\Signature\ShaHmac256WithRsaSignature;
use AlibabaCloud\Client\Credentials\Requests\GenerateSessionAccessKey;
/**
* Class RsaKeyPairProvider
*
* @package AlibabaCloud\Client\Credentials\Providers
*/
class RsaKeyPairProvider extends Provider
{
/**
* Get credential.
*
* @param int $timeout
* @param int $connectTimeout
*
* @return StsCredential
* @throws ClientException
* @throws ServerException
*/
public function get($timeout = Request::TIMEOUT, $connectTimeout = Request::CONNECT_TIMEOUT)
{
$credential = $this->getCredentialsInCache();
if ($credential === null) {
$result = $this->request($timeout, $connectTimeout);
if (!isset($result['SessionAccessKey']['SessionAccessKeyId'],
$result['SessionAccessKey']['SessionAccessKeySecret'])) {
throw new ServerException($result, $this->error, SDK::INVALID_CREDENTIAL);
}
$credential = $result['SessionAccessKey'];
$this->cache($credential);
}
return new StsCredential(
$credential['SessionAccessKeyId'],
$credential['SessionAccessKeySecret']
);
}
/**
* Get credentials by request.
*
* @param $timeout
* @param $connectTimeout
*
* @return Result
* @throws ClientException
* @throws ServerException
*/
private function request($timeout, $connectTimeout)
{
$clientName = __CLASS__ . \uniqid('rsa', true);
$credential = $this->client->getCredential();
AlibabaCloud::client(
new AccessKeyCredential(
$credential->getPublicKeyId(),
$credential->getPrivateKey()
),
new ShaHmac256WithRsaSignature()
)->name($clientName);
return (new GenerateSessionAccessKey($credential->getPublicKeyId()))
->client($clientName)
->timeout($timeout)
->connectTimeout($connectTimeout)
->debug($this->client->isDebug())
->request();
}
}

View File

@ -0,0 +1,110 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the AssumeRole of the RAM account to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class RamRoleArnCredential implements CredentialsInterface
{
/**
* @var string
*/
private $accessKeyId;
/**
* @var string
*/
private $accessKeySecret;
/**
* @var string
*/
private $roleArn;
/**
* @var string
*/
private $roleSessionName;
/**
* @var string
*/
private $policy;
/**
* Class constructor.
*
* @param string $accessKeyId
* @param string $accessKeySecret
* @param string $roleArn
* @param string $roleSessionName
* @param string|array $policy
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret, $roleArn, $roleSessionName, $policy = '')
{
CredentialFilter::AccessKey($accessKeyId, $accessKeySecret);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
$this->roleArn = $roleArn;
$this->roleSessionName = $roleSessionName;
$this->policy = $policy;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return $this->accessKeyId;
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return $this->accessKeySecret;
}
/**
* @return string
*/
public function getRoleArn()
{
return $this->roleArn;
}
/**
* @return string
*/
public function getRoleSessionName()
{
return $this->roleSessionName;
}
/**
* @return string
*/
public function getPolicy()
{
return $this->policy;
}
/**
* @return string
*/
public function __toString()
{
return "$this->accessKeyId#$this->accessKeySecret#$this->roleArn#$this->roleSessionName";
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace AlibabaCloud\Client\Credentials\Requests;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Credentials\Providers\Provider;
use AlibabaCloud\Client\Credentials\RamRoleArnCredential;
/**
* Retrieving assume role credentials.
*
* @package AlibabaCloud\Client\Credentials\Requests
*/
class AssumeRole extends RpcRequest
{
/**
* AssumeRole constructor.
*
* @param RamRoleArnCredential $arnCredential
*
* @throws ClientException
*/
public function __construct(RamRoleArnCredential $arnCredential)
{
parent::__construct();
$this->product('Sts');
$this->version('2015-04-01');
$this->action('AssumeRole');
$this->host('sts.aliyuncs.com');
$this->scheme('https');
$this->regionId('cn-hangzhou');
$this->options['verify'] = false;
$this->options['query']['RoleArn'] = $arnCredential->getRoleArn();
$this->options['query']['RoleSessionName'] = $arnCredential->getRoleSessionName();
$this->options['query']['DurationSeconds'] = Provider::DURATION_SECONDS;
if ($arnCredential->getPolicy()) {
if (is_array($arnCredential->getPolicy())) {
$this->options['query']['Policy'] = json_encode($arnCredential->getPolicy());
}
if (is_string($arnCredential->getPolicy())) {
$this->options['query']['Policy'] = $arnCredential->getPolicy();
}
}
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace AlibabaCloud\Client\Credentials\Requests;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Credentials\Providers\Provider;
/**
* Use the RSA key pair to complete the authentication (supported only on Japanese site)
*
* @package AlibabaCloud\Client\Credentials\Requests
*/
class GenerateSessionAccessKey extends RpcRequest
{
/**
* GenerateSessionAccessKey constructor.
*
* @param string $publicKeyId
*
* @throws ClientException
*/
public function __construct($publicKeyId)
{
parent::__construct();
$this->product('Sts');
$this->version('2015-04-01');
$this->action('GenerateSessionAccessKey');
$this->host('sts.ap-northeast-1.aliyuncs.com');
$this->scheme('https');
$this->regionId('cn-hangzhou');
$this->options['verify'] = false;
$this->options['query']['PublicKeyId'] = $publicKeyId;
$this->options['query']['DurationSeconds'] = Provider::DURATION_SECONDS;
}
}

View File

@ -0,0 +1,75 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use Exception;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the RSA key pair to complete the authentication (supported only on Japanese site)
*
* @package AlibabaCloud\Client\Credentials
*/
class RsaKeyPairCredential implements CredentialsInterface
{
/**
* @var string
*/
private $publicKeyId;
/**
* @var string
*/
private $privateKey;
/**
* RsaKeyPairCredential constructor.
*
* @param string $publicKeyId
* @param string $privateKeyFile
*
* @throws ClientException
*/
public function __construct($publicKeyId, $privateKeyFile)
{
CredentialFilter::publicKeyId($publicKeyId);
CredentialFilter::privateKeyFile($privateKeyFile);
$this->publicKeyId = $publicKeyId;
try {
$this->privateKey = file_get_contents($privateKeyFile);
} catch (Exception $exception) {
throw new ClientException(
$exception->getMessage(),
SDK::INVALID_CREDENTIAL
);
}
}
/**
* @return mixed
*/
public function getPrivateKey()
{
return $this->privateKey;
}
/**
* @return string
*/
public function getPublicKeyId()
{
return $this->publicKeyId;
}
/**
* @return string
*/
public function __toString()
{
return "publicKeyId#$this->publicKeyId";
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace AlibabaCloud\Client\Credentials;
use AlibabaCloud\Client\Filter\CredentialFilter;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Use the STS Token to complete the authentication.
*
* @package AlibabaCloud\Client\Credentials
*/
class StsCredential implements CredentialsInterface
{
/**
* @var string
*/
private $accessKeyId;
/**
* @var string
*/
private $accessKeySecret;
/**
* @var string
*/
private $securityToken;
/**
* StsCredential constructor.
*
* @param string $accessKeyId Access key ID
* @param string $accessKeySecret Access Key Secret
* @param string $securityToken Security Token
*
* @throws ClientException
*/
public function __construct($accessKeyId, $accessKeySecret, $securityToken = '')
{
CredentialFilter::AccessKey($accessKeyId, $accessKeySecret);
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
$this->securityToken = $securityToken;
}
/**
* @return string
*/
public function getAccessKeyId()
{
return $this->accessKeyId;
}
/**
* @return string
*/
public function getAccessKeySecret()
{
return $this->accessKeySecret;
}
/**
* @return string
*/
public function getSecurityToken()
{
return $this->securityToken;
}
/**
* @return string
*/
public function __toString()
{
return "$this->accessKeyId#$this->accessKeySecret#$this->securityToken";
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace AlibabaCloud\Client;
use AlibabaCloud\Client\Result\Result;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
/**
* Class DefaultAcsClient
*
* @package AlibabaCloud
*
* @deprecated deprecated since version 2.0, Use AlibabaCloud instead.
* @codeCoverageIgnore
*/
class DefaultAcsClient
{
/**
* @var string
*/
public $randClientName;
/**
* DefaultAcsClient constructor.
*
* @param Client $client
*
* @throws ClientException
*/
public function __construct(Client $client)
{
$this->randClientName = \uniqid('', true);
$client->name($this->randClientName);
}
/**
* @param Request|Result $request
*
* @return Result|string
* @throws ClientException
* @throws ServerException
*/
public function getAcsResponse($request)
{
if ($request instanceof Result) {
return $request;
}
return $request->client($this->randClientName)->request();
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace AlibabaCloud\Client;
/**
* Class Encode
*
* @package AlibabaCloud\Client
*/
class Encode
{
/**
* @var array
*/
private $data;
/**
* @param array $data
*
* @return static
*/
public static function create(array $data)
{
return new static($data);
}
/**
* Encode constructor.
*
* @param array $data
*/
private function __construct(array $data)
{
$this->data = $data;
}
/**
* @return bool|string
*/
public function toString()
{
$string = '';
foreach ($this->data as $key => $value) {
$encode = rawurlencode($value);
if ($encode === '') {
$string .= "$key&";
} else {
$string .= "$key=$encode&";
}
}
if (0 < count($this->data)) {
$string = substr($string, 0, -1);
}
return $string;
}
/**
* @return $this
*/
public function ksort()
{
ksort($this->data);
return $this;
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace AlibabaCloud\Client\Exception;
use Exception;
use RuntimeException;
/**
* Class AlibabaCloudException
*
* @package AlibabaCloud\Client\Exception
*/
abstract class AlibabaCloudException extends Exception
{
/**
* @var string
*/
protected $errorCode;
/**
* @var string
*/
protected $errorMessage;
/**
* @return string
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* @codeCoverageIgnore
* @deprecated
*/
public function setErrorCode()
{
throw new RuntimeException('deprecated since 2.0.');
}
/**
* @return string
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* @codeCoverageIgnore
*
* @param $errorMessage
*
* @deprecated
*/
public function setErrorMessage($errorMessage)
{
$this->errorMessage = $errorMessage;
}
/**
* @codeCoverageIgnore
* @deprecated
*/
public function setErrorType()
{
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace AlibabaCloud\Client\Exception;
use Exception;
use RuntimeException;
/**
* Class ClientException
*
* @package AlibabaCloud\Client\Exception
*/
class ClientException extends AlibabaCloudException
{
/**
* ClientException constructor.
*
* @param string $errorMessage
* @param string $errorCode
* @param Exception|null $previous
*/
public function __construct($errorMessage, $errorCode, $previous = null)
{
parent::__construct($errorMessage, 0, $previous);
$this->errorMessage = $errorMessage;
$this->errorCode = $errorCode;
}
/**
* @codeCoverageIgnore
* @deprecated
*/
public function getErrorType()
{
return 'Client';
}
}

View File

@ -0,0 +1,158 @@
<?php
namespace AlibabaCloud\Client\Exception;
use AlibabaCloud\Client\Support\Stringy;
use RuntimeException;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Result\Result;
/**
* Class ServerException
*
* @package AlibabaCloud\Client\Exception
*/
class ServerException extends AlibabaCloudException
{
/**
* @var string
*/
protected $requestId;
/**
* @var Result
*/
protected $result;
/**
* ServerException constructor.
*
* @param Result|null $result
* @param string $errorMessage
* @param string $errorCode
*/
public function __construct(
Result $result,
$errorMessage = SDK::RESPONSE_EMPTY,
$errorCode = SDK::SERVICE_UNKNOWN_ERROR
) {
$this->result = $result;
$this->errorMessage = $errorMessage;
$this->errorCode = $errorCode;
$this->resolvePropertiesByReturn();
$this->distinguishSignatureErrors();
$this->bodyAsErrorMessage();
parent::__construct(
$this->getMessageString(),
$this->result->getStatusCode()
);
}
/**
* Resolve the error message based on the return of the server.
*
* @return void
*/
private function resolvePropertiesByReturn()
{
if (isset($this->result['message'])) {
$this->errorMessage = $this->result['message'];
$this->errorCode = $this->result['code'];
}
if (isset($this->result['Message'])) {
$this->errorMessage = $this->result['Message'];
$this->errorCode = $this->result['Code'];
}
if (isset($this->result['errorMsg'])) {
$this->errorMessage = $this->result['errorMsg'];
$this->errorCode = $this->result['errorCode'];
}
if (isset($this->result['requestId'])) {
$this->requestId = $this->result['requestId'];
}
if (isset($this->result['RequestId'])) {
$this->requestId = $this->result['RequestId'];
}
}
/**
* If the string to be signed are the same with server's, it is considered a credential error.
*/
private function distinguishSignatureErrors()
{
if ($this->result->getRequest()
&& Stringy::contains($this->errorMessage, $this->result->getRequest()->stringToSign())) {
$this->errorCode = 'InvalidAccessKeySecret';
$this->errorMessage = 'Specified Access Key Secret is not valid.';
}
}
/**
* If the error message matches the default message and
* the server has returned content, use the return content
*/
private function bodyAsErrorMessage()
{
$body = (string)$this->result->getBody();
if ($this->errorMessage === SDK::RESPONSE_EMPTY && $body) {
$this->errorMessage = $body;
}
}
/**
* Get standard exception message.
*
* @return string
*/
private function getMessageString()
{
$message = "$this->errorCode: $this->errorMessage RequestId: $this->requestId";
if ($this->getResult()->getRequest()) {
$method = $this->getResult()->getRequest()->method;
$uri = (string)$this->getResult()->getRequest()->uri;
$message .= " $method \"$uri\"";
if ($this->result) {
$message .= ' ' . $this->result->getStatusCode();
}
}
return $message;
}
/**
* @return Result
*/
public function getResult()
{
return $this->result;
}
/**
* @return string
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* @codeCoverageIgnore
* @deprecated
*/
public function getErrorType()
{
return 'Server';
}
/**
* @codeCoverageIgnore
* @deprecated
*/
public function getHttpStatus()
{
return $this->getResult()->getStatusCode();
}
}

View File

@ -0,0 +1,259 @@
<?php
namespace AlibabaCloud\Client\Filter;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class ApiFilter
*
* @package AlibabaCloud\Client\Filter
*/
class ApiFilter
{
/**
* @param $serviceCode
*
* @return mixed
* @throws ClientException
*/
public static function serviceCode($serviceCode)
{
if (!is_string($serviceCode)) {
throw new ClientException(
'Service Code must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($serviceCode === '') {
throw new ClientException(
'Service Code cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $serviceCode;
}
/**
* @param $endpointType
*
* @return mixed
* @throws ClientException
*/
public static function endpointType($endpointType)
{
if (!is_string($endpointType)) {
throw new ClientException(
'Endpoint Type must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($endpointType === '') {
throw new ClientException(
'Endpoint Type cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $endpointType;
}
/**
* @param $action
*
* @return mixed
* @throws ClientException
*/
public static function action($action)
{
if (!is_string($action)) {
throw new ClientException(
'Action must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($action === '') {
throw new ClientException(
'Action cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $action;
}
/**
* @codeCoverageIgnore
*
* @param string $endpointSuffix
*
* @return mixed
* @throws ClientException
*/
public static function endpointSuffix($endpointSuffix)
{
if (!is_string($endpointSuffix)) {
throw new ClientException(
'Endpoint Suffix must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($endpointSuffix === '') {
throw new ClientException(
'Endpoint Suffix cannot be empty',
SDK::INVALID_ARGUMENT
);
}
if (!preg_match("/^[a-zA-Z0-9_-]+$/", $endpointSuffix)) {
throw new ClientException(
'Invalid Endpoint Suffix',
SDK::INVALID_ARGUMENT
);
}
return $endpointSuffix;
}
/**
* @codeCoverageIgnore
*
* @param string $network
*
* @return mixed
* @throws ClientException
*/
public static function network($network)
{
if (!is_string($network)) {
throw new ClientException(
'Network Suffix must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($network === '') {
throw new ClientException(
'Network Suffix cannot be empty',
SDK::INVALID_ARGUMENT
);
}
if (!preg_match("/^[a-zA-Z0-9_-]+$/", $network)) {
throw new ClientException(
'Invalid Network Suffix',
SDK::INVALID_ARGUMENT
);
}
return $network;
}
/**
* @param string $version
*
* @return mixed
* @throws ClientException
*/
public static function version($version)
{
if (!is_string($version)) {
throw new ClientException(
'Version must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($version === '') {
throw new ClientException(
'Version cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $version;
}
/**
* @param $format
*
* @return mixed
* @throws ClientException
*/
public static function format($format)
{
if (!is_string($format)) {
throw new ClientException(
'Format must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($format === '') {
throw new ClientException(
'Format cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return \strtoupper($format);
}
/**
* @param $product
*
* @return string
*
* @throws ClientException
*/
public static function product($product)
{
if (!is_string($product)) {
throw new ClientException(
'Product must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($product === '') {
throw new ClientException(
'Product cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $product;
}
/**
* @param $pattern
*
* @return string
*
* @throws ClientException
*/
public static function pattern($pattern)
{
if (!is_string($pattern)) {
throw new ClientException(
'Pattern must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($pattern === '') {
throw new ClientException(
'Pattern cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $pattern;
}
}

View File

@ -0,0 +1,146 @@
<?php
namespace AlibabaCloud\Client\Filter;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class ClientFilter
*
* @package AlibabaCloud\Client\Filter
*/
class ClientFilter
{
/**
* @param $regionId
*
* @return string
*
* @throws ClientException
*/
public static function regionId($regionId)
{
if (!is_string($regionId)) {
throw new ClientException(
'Region ID must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($regionId === '') {
throw new ClientException(
'Region ID cannot be empty',
SDK::INVALID_ARGUMENT
);
}
if (!preg_match("/^[a-zA-Z0-9_-]+$/", $regionId)) {
throw new ClientException(
'Invalid Region ID',
SDK::INVALID_ARGUMENT
);
}
return strtolower($regionId);
}
/**
* @param $clientName
*
* @return string
*
* @throws ClientException
*/
public static function clientName($clientName)
{
if (!is_string($clientName)) {
throw new ClientException(
'Client Name must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($clientName === '') {
throw new ClientException(
'Client Name cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return strtolower($clientName);
}
/**
* @param $times
*
* @return string
*
* @throws ClientException
*/
public static function retry($times)
{
if (!is_int($times)) {
throw new ClientException(
'Retry must be a int',
SDK::INVALID_ARGUMENT
);
}
return $times;
}
/**
* @param $connectTimeout
*
* @return mixed
* @throws ClientException
*/
public static function connectTimeout($connectTimeout)
{
if ($connectTimeout === '') {
throw new ClientException(
'Connect Timeout cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $connectTimeout;
}
/**
* @param $timeout
*
* @return mixed
* @throws ClientException
*/
public static function timeout($timeout)
{
if ($timeout === '') {
throw new ClientException(
'Timeout cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $timeout;
}
/**
* @param int $Milliseconds
*
* @return mixed
* @throws ClientException
*/
public static function milliseconds($Milliseconds)
{
if (!is_int($Milliseconds)) {
throw new ClientException(
'Milliseconds must be int',
SDK::INVALID_ARGUMENT
);
}
return $Milliseconds;
}
}

View File

@ -0,0 +1,152 @@
<?php
namespace AlibabaCloud\Client\Filter;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class CredentialFilter
*
* @package AlibabaCloud\Client\Filter
*/
class CredentialFilter
{
/**
* @param $bearerToken
*
* @return mixed
* @throws ClientException
*/
public static function bearerToken($bearerToken)
{
if (!is_string($bearerToken)) {
throw new ClientException(
'Bearer Token must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($bearerToken === '') {
throw new ClientException(
'Bearer Token cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $bearerToken;
}
/**
* @param $publicKeyId
*
* @return mixed
* @throws ClientException
*/
public static function publicKeyId($publicKeyId)
{
if (!is_string($publicKeyId)) {
throw new ClientException(
'Public Key ID must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($publicKeyId === '') {
throw new ClientException(
'Public Key ID cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $publicKeyId;
}
/**
* @param $privateKeyFile
*
* @return mixed
* @throws ClientException
*/
public static function privateKeyFile($privateKeyFile)
{
if (!is_string($privateKeyFile)) {
throw new ClientException(
'Private Key File must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($privateKeyFile === '') {
throw new ClientException(
'Private Key File cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $privateKeyFile;
}
/**
* @param $roleName
*
* @return string
*
* @throws ClientException
*/
public static function roleName($roleName)
{
if (!is_string($roleName)) {
throw new ClientException(
'Role Name must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($roleName === '') {
throw new ClientException(
'Role Name cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $roleName;
}
/**
* @param string $accessKeyId
* @param string $accessKeySecret
*
* @throws ClientException
*/
public static function AccessKey($accessKeyId, $accessKeySecret)
{
if (!is_string($accessKeyId)) {
throw new ClientException(
'AccessKey ID must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($accessKeyId === '') {
throw new ClientException(
'AccessKey ID cannot be empty',
SDK::INVALID_ARGUMENT
);
}
if (!is_string($accessKeySecret)) {
throw new ClientException(
'AccessKey Secret must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($accessKeySecret === '') {
throw new ClientException(
'AccessKey Secret cannot be empty',
SDK::INVALID_ARGUMENT
);
}
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace AlibabaCloud\Client\Filter;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class Filter
*
* @package AlibabaCloud\Client\Filter
*/
class Filter
{
/**
* @param $name
*
* @return string
*
* @throws ClientException
*/
public static function name($name)
{
if (!is_string($name)) {
throw new ClientException(
'Name must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($name === '') {
throw new ClientException(
'Name cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $name;
}
/**
* @param $value
*
* @return string
*
* @throws ClientException
*/
public static function value($value)
{
if (!is_numeric($value) && !is_string($value)) {
throw new ClientException(
'Value must be a string or int',
SDK::INVALID_ARGUMENT
);
}
if ($value === '') {
throw new ClientException(
'Value cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $value;
}
}

View File

@ -0,0 +1,166 @@
<?php
namespace AlibabaCloud\Client\Filter;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class HttpFilter
*
* @package AlibabaCloud\Client\Filter
*/
class HttpFilter
{
/**
* @param $host
*
* @return string
*
* @throws ClientException
*/
public static function host($host)
{
if (!is_string($host)) {
throw new ClientException(
'Host must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($host === '') {
throw new ClientException(
'Host cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $host;
}
/**
* @param $scheme
*
* @return string
*
* @throws ClientException
*/
public static function scheme($scheme)
{
if (!is_string($scheme)) {
throw new ClientException(
'Scheme must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($scheme === '') {
throw new ClientException(
'Scheme cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $scheme;
}
/**
* @param $body
*
* @return mixed
* @throws ClientException
*/
public static function body($body)
{
if (!is_string($body) && !is_numeric($body)) {
throw new ClientException(
'Body must be a string or int',
SDK::INVALID_ARGUMENT
);
}
if ($body === '') {
throw new ClientException(
'Body cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $body;
}
/**
* @param $method
*
* @return mixed
* @throws ClientException
*/
public static function method($method)
{
if (!is_string($method)) {
throw new ClientException(
'Method must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($method === '') {
throw new ClientException(
'Method cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return \strtoupper($method);
}
/**
* @param $contentType
*
* @return mixed
* @throws ClientException
*/
public static function contentType($contentType)
{
if (!is_string($contentType)) {
throw new ClientException(
'Content-Type must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($contentType === '') {
throw new ClientException(
'Content-Type cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $contentType;
}
/**
* @param $accept
*
* @return mixed
* @throws ClientException
*/
public static function accept($accept)
{
if (!is_string($accept)) {
throw new ClientException(
'Accept must be a string',
SDK::INVALID_ARGUMENT
);
}
if ($accept === '') {
throw new ClientException(
'Accept cannot be empty',
SDK::INVALID_ARGUMENT
);
}
return $accept;
}
}

View File

@ -0,0 +1,289 @@
<?php
namespace AlibabaCloud\Client;
use Closure;
use AlibabaCloud\Client\Support\Stringy;
use League\CLImate\CLImate;
use AlibabaCloud\Client\Exception\ClientException;
/*
|--------------------------------------------------------------------------
| Global Functions for Alibaba Cloud
|--------------------------------------------------------------------------
|
| Some common global functions are defined here.
| This file will be automatically loaded.
|
*/
/**
* @param $filename
* @param bool $throwException
*
* @return bool
* @throws ClientException
*/
function inOpenBasedir($filename, $throwException = false)
{
$open_basedir = ini_get('open_basedir');
if (!$open_basedir) {
return true;
}
$dirs = explode(PATH_SEPARATOR, $open_basedir);
if (empty($dirs)) {
return true;
}
if (inDir($filename, $dirs)) {
return true;
}
if ($throwException === false) {
return false;
}
throw new ClientException(
'open_basedir restriction in effect. '
. "File($filename) is not within the allowed path(s): ($open_basedir)",
'SDK.InvalidPath'
);
}
/**
* @param string $filename
* @param array $dirs
*
* @return bool
*/
function inDir($filename, array $dirs)
{
foreach ($dirs as $dir) {
if (!Stringy::endsWith($dir, DIRECTORY_SEPARATOR)) {
$dir .= DIRECTORY_SEPARATOR;
}
if (0 === strpos($filename, $dir)) {
return true;
}
}
return false;
}
/**
* @return bool
*/
function isWindows()
{
return PATH_SEPARATOR === ';';
}
/**
* @return CLImate
*/
function cliMate()
{
return new CLImate();
}
/**
* @param string $string
* @param string|null $flank
* @param string|null $char
* @param int|null $length
*
* @return void
*/
function backgroundRed($string, $flank = null, $char = null, $length = null)
{
cliMate()->br();
if ($flank !== null) {
cliMate()->backgroundRed()->flank($flank, $char, $length);
cliMate()->br();
}
cliMate()->backgroundRed($string);
cliMate()->br();
}
/**
* @param string $string
* @param string|null $flank
* @param string|null $char
* @param int|null $length
*
* @return void
*/
function backgroundGreen($string, $flank = null, $char = null, $length = null)
{
cliMate()->br();
if ($flank !== null) {
cliMate()->backgroundGreen()->flank($flank, $char, $length);
}
cliMate()->backgroundGreen($string);
cliMate()->br();
}
/**
* @param string $string
* @param string|null $flank
* @param string|null $char
* @param int|null $length
*
* @return void
*/
function backgroundBlue($string, $flank = null, $char = null, $length = null)
{
cliMate()->br();
if ($flank !== null) {
cliMate()->backgroundBlue()->flank($flank, $char, $length);
}
cliMate()->backgroundBlue($string);
cliMate()->br();
}
/**
* @param string $string
* @param string|null $flank
* @param string|null $char
* @param int|null $length
*
* @return void
*/
function backgroundMagenta($string, $flank = null, $char = null, $length = null)
{
cliMate()->br();
if ($flank !== null) {
cliMate()->backgroundMagenta()->flank($flank, $char, $length);
}
cliMate()->backgroundMagenta($string);
cliMate()->br();
}
/**
* @param array $array
*/
function json(array $array)
{
cliMate()->br();
cliMate()->backgroundGreen()->json($array);
cliMate()->br();
}
/**
* @param array $array
*
* @return void
*/
function redTable($array)
{
/**
* @noinspection PhpUndefinedMethodInspection
*/
cliMate()->redTable($array);
}
/**
* @param mixed $result
* @param string $title
*
* @return void
*/
function block($result, $title)
{
cliMate()->backgroundGreen()->flank($title, '--', 20);
dump($result);
}
/**
* Gets the value of an environment variable.
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
function env($key, $default = null)
{
$value = getenv($key);
if ($value === false) {
return value($default);
}
if (envSubstr($value)) {
return substr($value, 1, -1);
}
return envConversion($value);
}
/**
* @param $value
*
* @return bool|string|null
*/
function envConversion($value)
{
$key = strtolower($value);
if ($key === 'null' || $key === '(null)') {
return null;
}
$list = [
'true' => true,
'(true)' => true,
'false' => false,
'(false)' => false,
'empty' => '',
'(empty)' => '',
];
return isset($list[$key]) ? $list[$key] : $value;
}
/**
* @param $key
*
* @return bool|mixed
* @throws ClientException
*/
function envNotEmpty($key)
{
$value = env($key, false);
if ($value !== false && !$value) {
throw new ClientException(
"Environment variable '$key' cannot be empty",
SDK::INVALID_ARGUMENT
);
}
if ($value) {
return $value;
}
return false;
}
/**
* @param $value
*
* @return bool
*/
function envSubstr($value)
{
return ($valueLength = strlen($value)) > 1 && strpos($value, '"') === 0 && $value[$valueLength - 1] === '"';
}
/**
* Return the default value of the given value.
*
* @param mixed $value
*
* @return mixed
*/
function value($value)
{
return $value instanceof Closure ? $value() : $value;
}

View File

@ -0,0 +1,79 @@
<?php
namespace AlibabaCloud\Client\Log;
use DateTime;
use Exception;
use DateTimeZone;
use GuzzleHttp\MessageFormatter;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @deprecated Use GuzzleHttp\MessageFormatter.
* Class LogFormatter
*
* @package AlibabaCloud\Client\Log
*/
class LogFormatter
{
/**
* @var float
*/
private static $logStartTime = 0;
/**
* @var DateTime
*/
private static $ts;
/** @var string Template used to format log messages */
public $template;
/**
* @param string $template Log message template
*
* @throws Exception
*/
public function __construct($template)
{
// parent::__construct($template);
self::$logStartTime = microtime(true);
$this->template = $template;
$timezone = new DateTimeZone(date_default_timezone_get() ?: 'UTC');
if (PHP_VERSION_ID < 70100) {
self::$ts = DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), $timezone);
} else {
self::$ts = new DateTime('now', $timezone);
}
}
/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
* @param Exception $error Exception that was received
*
* @return string
*/
public function format(
RequestInterface $request,
ResponseInterface $response = null,
Exception $error = null
) {
$this->template = str_replace('{pid}', getmypid(), $this->template);
$this->template = str_replace('{cost}', self::getCost(), $this->template);
$this->template = str_replace('{start_time}', self::$ts->format('Y-m-d H:i:s.u'), $this->template);
return (new MessageFormatter($this->template))->format($request, $response, $error);
}
/**
* @return float|mixed
*/
private static function getCost()
{
return microtime(true) - self::$logStartTime;
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace AlibabaCloud\Client\Profile;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Clients\Client;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class DefaultProfile
*
* @package AlibabaCloud\Client\Profile
* @codeCoverageIgnore
* @deprecated deprecated since version 2.0, Use AlibabaCloud instead.
*/
class DefaultProfile
{
/**
* @param string $regionId
* @param string $accessKeyId
* @param string $accessKeySecret
*
* @return Client
* @throws ClientException
*/
public static function getProfile($regionId, $accessKeyId, $accessKeySecret)
{
return AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
->regionId($regionId);
}
/**
* @param string $regionId
* @param string $accessKeyId
* @param string $accessKeySecret
* @param string $roleArn
* @param string $roleSessionName
*
* @return Client
* @throws ClientException
*/
public static function getRamRoleArnProfile($regionId, $accessKeyId, $accessKeySecret, $roleArn, $roleSessionName)
{
return AlibabaCloud::ramRoleArnClient($accessKeyId, $accessKeySecret, $roleArn, $roleSessionName)
->regionId($regionId);
}
/**
* @param string $regionId
* @param string $roleName
*
* @return Client
* @throws ClientException
*/
public static function getEcsRamRoleProfile($regionId, $roleName)
{
return AlibabaCloud::ecsRamRoleClient($roleName)
->regionId($regionId);
}
/**
* @param string $regionId
* @param string $bearerToken
*
* @return Client
* @throws ClientException
*/
public static function getBearerTokenProfile($regionId, $bearerToken)
{
return AlibabaCloud::bearerTokenClient($bearerToken)
->regionId($regionId);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace AlibabaCloud\Client\Regions;
use AlibabaCloud\Client\Traits\EndpointTrait;
/**
* Class EndpointProvider
*
* @package AlibabaCloud\Client\Regions
*
* @deprecated deprecated since version 2.0, Use AlibabaCloud instead.
* @codeCoverageIgnore
*/
class EndpointProvider
{
use EndpointTrait;
}

View File

@ -0,0 +1,160 @@
<?php
namespace AlibabaCloud\Client\Regions;
use Exception;
use RuntimeException;
use AlibabaCloud\Client\SDK;
use AlibabaCloud\Client\Config\Config;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Filter\ApiFilter;
use AlibabaCloud\Client\Filter\HttpFilter;
use AlibabaCloud\Client\Filter\ClientFilter;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
/**
* Class LocationService
*
* @package AlibabaCloud\Client\Regions
*/
class LocationService
{
/**
* Global Region Name
*/
const GLOBAL_REGION = 'global';
/**
* @var array
*/
protected static $hosts = [];
/**
* @var Request
*/
protected $request;
/**
* LocationService constructor.
*
* @param Request $request
*/
private function __construct(Request $request)
{
$this->request = $request;
}
/**
* @param Request $request
* @param string $domain
*
* @return string
* @throws ClientException
* @throws ServerException
* @deprecated
* @codeCoverageIgnore
*/
public static function findProductDomain(Request $request, $domain = 'location.aliyuncs.com')
{
return self::resolveHost($request, $domain);
}
/**
* @param $regionId
* @param $product
* @param $domain
*
* @throws ClientException
* @deprecated
* @codeCoverageIgnore
*/
public static function addEndPoint($regionId, $product, $domain)
{
self::addHost($product, $domain, $regionId);
}
/**
* @param Request $request
* @param string $domain
*
* @return string
* @throws ClientException
* @throws ServerException
*/
public static function resolveHost(Request $request, $domain = 'location.aliyuncs.com')
{
$locationService = new static($request);
$product = $locationService->request->product;
$regionId = $locationService->request->realRegionId();
if (!isset(self::$hosts[$product][$regionId])) {
self::$hosts[$product][$regionId] = self::getResult($locationService, $domain);
}
return self::$hosts[$product][$regionId];
}
/**
* @param static $locationService
* @param string $domain
*
* @return string
* @throws ClientException
* @throws ServerException
*/
private static function getResult($locationService, $domain)
{
$locationRequest = new LocationServiceRequest($locationService->request, $domain);
$result = $locationRequest->request();
if (!isset($result['Endpoints']['Endpoint'][0]['Endpoint'])) {
throw new ClientException(
'Not found Region ID in ' . $domain,
SDK::INVALID_REGION_ID
);
}
return $result['Endpoints']['Endpoint'][0]['Endpoint'];
}
/**
* @param string $product
* @param string $host
* @param string $regionId
*
* @throws ClientException
*/
public static function addHost($product, $host, $regionId = self::GLOBAL_REGION)
{
ApiFilter::product($product);
HttpFilter::host($host);
ClientFilter::regionId($regionId);
self::$hosts[$product][$regionId] = $host;
}
/**
* Update endpoints from OSS.
*
* @codeCoverageIgnore
* @throws Exception
*/
public static function updateEndpoints()
{
$ossUrl = 'https://openapi-endpoints.oss-cn-hangzhou.aliyuncs.com/endpoints.json';
$json = \file_get_contents($ossUrl);
$list = \json_decode($json, true);
foreach ($list['endpoints'] as $endpoint) {
Config::set(
"endpoints.{$endpoint['service']}.{$endpoint['regionid']}",
\strtolower($endpoint['endpoint'])
);
}
}
}

View File

@ -0,0 +1,46 @@
<?php
namespace AlibabaCloud\Client\Regions;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Request\RpcRequest;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class LocationServiceRequest
*
* @package AlibabaCloud\Client\Regions
*/
class LocationServiceRequest extends RpcRequest
{
/**
* LocationServiceRequest constructor.
*
* @param Request $request
* @param string $domain
*
* @throws ClientException
*/
public function __construct(Request $request, $domain)
{
parent::__construct();
$this->product('Location');
$this->version('2015-06-12');
$this->action('DescribeEndpoints');
$this->regionId('cn-hangzhou');
$this->format('JSON');
$this->options['query']['Id'] = $request->realRegionId();
$this->options['query']['ServiceCode'] = $request->serviceCode;
$this->options['query']['Type'] = $request->endpointType;
$this->client($request->client);
$this->host($domain);
if (isset($request->options['timeout'])) {
$this->timeout($request->options['timeout']);
}
if (isset($request->options['connect_timeout'])) {
$this->connectTimeout($request->options['connect_timeout']);
}
}
}

View File

@ -0,0 +1,112 @@
<?php
namespace AlibabaCloud\Client;
use Composer\Script\Event;
/**
* Class Release
*
* @codeCoverageIgnore
* @package AlibabaCloud\Client
*/
class Release
{
/**
* @param Event $event
*/
public static function release(Event $event)
{
$arguments = $event->getArguments();
if (count($arguments) <= 1) {
echo 'Missing ChangeLog';
return;
}
self::updateChangelogFile($arguments[0], $arguments[1]);
self::changeVersionInCode($arguments[0]);
}
/**
* @param $version
* @param $changeLog
*/
private static function updateChangelogFile($version, $changeLog)
{
$content = preg_replace(
'/# CHANGELOG/',
'# CHANGELOG'
. "\n"
. "\n"
. "## $version - " . date('Y-m-d')
. self::log($changeLog),
self::getChangeLogContent()
);
file_put_contents(self::getChangeLogFile(), $content);
}
/**
* @param $changeLog
*
* @return string
*/
private static function log($changeLog)
{
$logs = explode('|', $changeLog);
$string = "\n";
foreach ($logs as $log) {
if ($log) {
$string .= "- $log." . "\n";
}
}
return $string;
}
/**
* @return string
*/
private static function getChangeLogContent()
{
return file_get_contents(self::getChangeLogFile());
}
/**
* @return string
*/
private static function getChangeLogFile()
{
return __DIR__ . '/../CHANGELOG.md';
}
/**
* @param $version
*/
private static function changeVersionInCode($version)
{
$content = preg_replace(
"/const VERSION = \'(.*)\';/",
"const VERSION = '" . $version . "';",
self::getCodeContent()
);
file_put_contents(self::getCodeFile(), $content);
}
/**
* @return string
*/
private static function getCodeContent()
{
return file_get_contents(self::getCodeFile());
}
/**
* @return string
*/
private static function getCodeFile()
{
return __DIR__ . '/AlibabaCloud.php';
}
}

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 = [];
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace AlibabaCloud\Client\Resolver;
use ReflectionClass;
use ReflectionException;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Exception\ClientException;
/**
* @codeCoverageIgnore
* @mixin Rpc
* @mixin Roa
* @mixin Request
* @package AlibabaCloud\Client\Resolver
*/
trait ActionResolverTrait
{
/**
* Resolve Action name from class name
*/
private function resolveActionName()
{
if (!$this->action) {
$array = explode('\\', get_class($this));
$this->action = array_pop($array);
}
}
/**
* Append SDK version into User-Agent
*
* @throws ClientException
* @throws ReflectionException
*/
private function appendSdkUA()
{
if (!(new ReflectionClass(AlibabaCloud::class))->hasMethod('appendUserAgent')) {
return;
}
if (!class_exists('AlibabaCloud\Release')) {
return;
}
AlibabaCloud::appendUserAgent('SDK', \AlibabaCloud\Release::VERSION);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace AlibabaCloud\Client\Resolver;
use ReflectionObject;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class ApiResolver
*
* @codeCoverageIgnore
* @package AlibabaCloud\Client\Resolver
*/
abstract class ApiResolver
{
/**
* @param $name
* @param $arguments
*
* @return mixed
*/
public static function __callStatic($name, $arguments)
{
return (new static())->__call($name, $arguments);
}
/**
* @param $api
* @param $arguments
*
* @return mixed
* @throws ClientException
*/
public function __call($api, $arguments)
{
$product_name = $this->getProductName();
$class = $this->getNamespace() . '\\' . \ucfirst($api);
if (\class_exists($class)) {
if (isset($arguments[0])) {
return $this->warpEndpoint(new $class($arguments[0]));
}
return $this->warpEndpoint(new $class());
}
throw new ClientException(
"{$product_name} contains no $api",
'SDK.ApiNotFound'
);
}
/**
* @param Request $request
*
* @return Request
*/
public function warpEndpoint(Request $request)
{
$reflect = new ReflectionObject($request);
$product_dir = dirname(dirname($reflect->getFileName()));
$endpoints_json = "$product_dir/endpoints.json";
if (file_exists($endpoints_json)) {
$endpoints = json_decode(file_get_contents($endpoints_json), true);
if (isset($endpoints['endpoint_map'])) {
$request->endpointMap = $endpoints['endpoint_map'];
}
if (isset($endpoints['endpoint_regional'])) {
$request->endpointRegional = $endpoints['endpoint_regional'];
}
}
return $request;
}
/**
* @return mixed
* @throws ClientException
*/
private function getProductName()
{
$array = \explode('\\', \get_class($this));
if (isset($array[3])) {
return str_replace('ApiResolver', '', $array[3]);
}
throw new ClientException(
'Service name not found.',
'SDK.ServiceNotFound'
);
}
/**
* @return string
* @throws ClientException
*/
private function getNamespace()
{
$array = \explode('\\', \get_class($this));
if (!isset($array[3])) {
throw new ClientException(
'Get namespace error.',
'SDK.ParseError'
);
}
unset($array[3]);
return \implode('\\', $array);
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace AlibabaCloud\Client\Resolver;
use RuntimeException;
/**
* Trait CallTrait
*
* @codeCoverageIgnore
* @package AlibabaCloud\Client\Resolver
*/
trait CallTrait
{
/**
* 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 = \mb_strcut($name, 3);
return $this->__get($parameter);
}
if (strncmp($name, 'with', 4) === 0) {
$parameter = \mb_strcut($name, 4);
$value = $this->getCallArguments($name, $arguments);
$this->data[$parameter] = $value;
$this->parameterPosition()[$parameter] = $value;
return $this;
}
if (strncmp($name, 'set', 3) === 0) {
$parameter = \mb_strcut($name, 3);
$with_method = "with$parameter";
return $this->$with_method($this->getCallArguments($name, $arguments));
}
throw new RuntimeException('Call to undefined method ' . __CLASS__ . '::' . $name . '()');
}
/**
* @param string $name
* @param array $arguments
* @param int $index
*
* @return mixed
*/
private function getCallArguments($name, array $arguments, $index = 0)
{
if (!isset($arguments[$index])) {
throw new \InvalidArgumentException("Missing arguments to method $name");
}
return $arguments[$index];
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace AlibabaCloud\Client\Resolver;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Request\RoaRequest;
use ReflectionClass;
use ReflectionException;
/**
* Class Roa
*
* @codeCoverageIgnore
* @package AlibabaCloud\Client\Resolver
*/
abstract class Roa extends RoaRequest
{
use ActionResolverTrait;
use CallTrait;
/**
* @param array $options
*
* @throws ReflectionException
* @throws ClientException
*/
public function __construct(array $options = [])
{
parent::__construct($options);
$this->resolveActionName();
$this->appendSdkUA();
}
/**
* @return mixed
*/
private function &parameterPosition()
{
return $this->pathParameters;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace AlibabaCloud\Client\Resolver;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Request\RpcRequest;
use ReflectionException;
/**
* Class Rpc
*
* @codeCoverageIgnore
* @package AlibabaCloud\Client\Resolver
*/
abstract class Rpc extends RpcRequest
{
use ActionResolverTrait;
use CallTrait;
/**
* @param array $options
*
* @throws ReflectionException
* @throws ClientException
*/
public function __construct(array $options = [])
{
parent::__construct($options);
$this->resolveActionName();
$this->appendSdkUA();
}
/**
* @return mixed
*/
private function &parameterPosition()
{
return $this->options['query'];
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace AlibabaCloud\Client\Resolver;
use AlibabaCloud\Client\Exception\ClientException;
/**
* Class VersionResolver
*
* @codeCoverageIgnore
* @package AlibabaCloud\Client\Resolver
*/
abstract class VersionResolver
{
/**
* @param string $name
* @param array $arguments
*
* @return mixed
* @throws ClientException
*/
public static function __callStatic($name, $arguments)
{
return (new static())->__call($name, $arguments);
}
/**
* @param string $version
* @param array $arguments
*
* @return mixed
* @throws ClientException
*/
public function __call($version, $arguments)
{
$version = \ucfirst($version);
$product = $this->getProductName();
$position = strpos($product, 'Version');
if ($position !== false && $position !== 0) {
$product = \str_replace('Version', '', $product);
}
$class = "AlibabaCloud\\{$product}\\$version\\{$product}ApiResolver";
if (\class_exists($class)) {
return new $class();
}
throw new ClientException(
"$product Versions contains no {$version}",
'SDK.VersionNotFound'
);
}
/**
* @return mixed
* @throws ClientException
*/
private function getProductName()
{
$array = \explode('\\', \get_class($this));
if (is_array($array) && isset($array[1])) {
return $array[1];
}
throw new ClientException(
'Service name not found.',
'SDK.ServiceNotFound'
);
}
}

Some files were not shown because too many files have changed in this diff Show More