Commit 5cff11f3 by allen

Merge branch 'master' of ssh://119.23.72.7:22611/zhujilai/Order into lt_订单周迭代3.09

parents 151fba26 7a811c86
Showing with 3349 additions and 19 deletions
...@@ -18,6 +18,7 @@ use App\Model\OrderActionLogModel; ...@@ -18,6 +18,7 @@ use App\Model\OrderActionLogModel;
use App\Model\OrderReturnModel; use App\Model\OrderReturnModel;
use App\Model\OrderItemsTrackModel; use App\Model\OrderItemsTrackModel;
use Session; use Session;
use Hprose\Http\Client;
// 获取订单优惠券金额 // 获取订单优惠券金额
function getCoupon($order_id) function getCoupon($order_id)
...@@ -672,11 +673,51 @@ Class OrderController extends Controller ...@@ -672,11 +673,51 @@ Class OrderController extends Controller
// 订单导出 // 订单导出
public function export(Request $request) public function export(Request $request)
{ {
$info = $this->_search($request, $request->input('order_goods_type')); $order_goods_type = $request->input('order_goods_type', 1);
$info = $this->_search($request, $order_goods_type);
if ($order_goods_type == 1) {
$file_name = '联营订单导出';
$source_items_id = Config('website.export_joint_source_id');
$headerCell = ['订单ID', '订单编号', 'ERP单号', '京东订单号', '会员账号', '收货人', '下单日期', '下单时间', '客户名称', '平台来源', 'SKUID', '商品型号', '商品分类', '制造商', '供应商', '数量', '单价', '均摊后单价', '商品小计', '币种', '客服', '商品总额', '运费', '附加费', '优惠券', '订单总额', '人民币总额', '付款类型', '订单状态', '发货状态', '收货地址', '发票类型', '发票状态', '发票抬头', '公司注册地址', '公司电话', 'adtags来源', '新用户来源', '取消原因', '推送备注', '是否为测试订单', '是否为新订单'];
$return_url = '/list';
} else {
$file_name = '自营订单导出';
$source_items_id = Config('website.export_self_source_id');
$headerCell = ['订单ID', '订单编号', 'ERP单号', '京东订单号', '会员账号', '收货人', '下单日期', '下单时间', '客户名称', '平台来源', 'SKUID', '商品型号', '商品分类', '制造商', '供应商', '数量', '单价', '均摊后单价', '商品小计', '币种', '客服', '商品总额', '运费', '附加费', '优惠券', '订单总额', '付款类型', '订单状态', '发货状态', '收货地址', '发票类型', '发票状态', '发票抬头', '公司注册地址', '公司电话', 'adtags来源', '新用户来源', '取消原因', '推送备注', '是否为测试订单', '销售类型', '业务类型', '自采标记', '项目需求描述','收货联系电话'];
$return_url = '/self_order';
}
$info['map']['p'] = 1;
$potrol = $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http';
$params = [
"type" => 2, // 类型 1:模板调用 2: api回调 (必填)
"source_items_id" => $source_items_id, //设置来源明细id:http://data.ichunt.net/database/1199(必填)
"file_name" => $file_name,//导出后文件名称(必填)
"excel_suf" => "csv", //导出文件格式 csv,xls(必填)
"header" => $headerCell, //导出文件头部 (必填,不得用 ID 做头部,数据顺序必须一致)
"query_param" => $info['map'], //p 第几页,limit每页多少条 占位符,照抄不需要改 (必填)
"callbackurl" => $potrol."://".$_SERVER['HTTP_HOST']."/hprose/service", //hrpose 数据提供网址(提供导出脚本分页回调获取数据,必填)
"callbackfuc" => "orderExport", //hrpose 回调函数(必填)
"create_uid" => $request->user->userId, #创建人id(必填)
];
// 调用导出系统
$url = Config('website.export_url');
$client = new \Hprose\Http\Client($url."/insertExport", false);
$res = $client->insertExport(json_encode($params));
// print_r($res);
$res = json_decode($res, true);
if ($res['err_code'] == 0) return ['err_code'=>0, 'err_msg'=>'推入到导出系统成功', 'data'=>$res['data']];
return ['err_code'=>1, 'err_msg'=>'推入到导出系统失败'];
$orderModel = new OrderModel(); // $orderModel = new OrderModel();
return $orderModel->orderExport($info['map']); // return $orderModel->orderExport($info['map']);
} }
// 下载合同 // 下载合同
......
...@@ -3,6 +3,8 @@ namespace App\Http\Controllers; ...@@ -3,6 +3,8 @@ namespace App\Http\Controllers;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use DB; use DB;
use Illuminate\Support\Facades\Redis as Redis;
use App\Model\RegionModel;
class RegionController extends Controller class RegionController extends Controller
{ {
...@@ -38,11 +40,47 @@ class RegionController extends Controller ...@@ -38,11 +40,47 @@ class RegionController extends Controller
); );
} }
//获取省市县名称 //获取省市县名称
public function getRegionName($region_id){ public function getRegionName($region_id)
{
if (empty($region_id)){ if (empty($region_id)){
return ""; return "";
} }
$list = DB::connection('order')->table('lie_region')->select("region_name")->where("region_id",$region_id)->get(); $list = DB::connection('order')->table('lie_region')->select("region_name")->where("region_id",$region_id)->get();
return !$list ? "" : current(objectToArray($list))['region_name']; return !$list ? "" : current(objectToArray($list))['region_name'];
} }
// 初始化地址缓存
public function cache()
{
$RegionModel = new RegionModel();
$province = $RegionModel->getRegion(1); // 获取省
S_str('oms:province', json_encode($province));
$city = $RegionModel->getRegion(2); // 获取城市
foreach($city as $c) {
S_hash('oms:city:'.$c['parent_id'], $c['region_id'], json_encode($c));
}
$district = $RegionModel->getRegion(3); // 获取区
foreach($district as $d) {
S_hash('oms:district:'.$d['parent_id'], $d['region_id'], json_encode($d));
}
echo '设置地址缓存成功';
}
// 清除缓存
public function clear()
{
Redis::del('oms:province');
Redis::del(Redis::keys('oms:city:*'));
Redis::del(Redis::keys('oms:district:*'));
echo '清除地址缓存成功';
}
} }
\ No newline at end of file
...@@ -445,3 +445,41 @@ function Autograph(){ ...@@ -445,3 +445,41 @@ function Autograph(){
// // Session::forget($token); // 验证完毕后删除token // // Session::forget($token); // 验证完毕后删除token
// // return true; // // return true;
// } // }
// 读取Redis缓存
function S_str($key, $value='')
{
static $redis = null;
if ($redis == null) $redis = new \App\Model\RedisModel();
if ($value === '') return json_decode($redis->get($key), true);
return $redis->set($key, $value);
}
function S_hash($key, $field='', $value='')
{
static $redis = null;
if ($redis == null) $redis = new \App\Model\RedisModel();
if ($value === '') {
$data = $field === '' ? $redis->hgetAll($key) : $redis->hget($key, $field);
$datas = [];
if (is_array($data)) {
foreach ($data as $v) {
$datas[] = json_decode($v, true);
}
} else {
$datas = json_decode($data, true);
}
return $datas;
}
return $redis->hset($key, $field, $value);
}
\ No newline at end of file
...@@ -41,7 +41,8 @@ class CheckLogin ...@@ -41,7 +41,8 @@ class CheckLogin
$rsp = $client->request('GET', $login['check'], [ $rsp = $client->request('GET', $login['check'], [
'headers' => ['Cookie' => $cookie], 'headers' => ['Cookie' => $cookie],
'connect_timeout' => 1, 'connect_timeout' => 1,
'timeout' => 3 'timeout' => 10,
'verify' => false,
]); ]);
if ($rsp->getStatusCode() != 200) { if ($rsp->getStatusCode() != 200) {
......
...@@ -54,6 +54,8 @@ Route::group(['middleware' => 'web'], function () { ...@@ -54,6 +54,8 @@ Route::group(['middleware' => 'web'], function () {
Route::match(['get', 'post'], '/changeShipping/{id?}', 'OrderController@changeShipping'); Route::match(['get', 'post'], '/changeShipping/{id?}', 'OrderController@changeShipping');
Route::post('/region/getAll', 'RegionController@getAll'); Route::post('/region/getAll', 'RegionController@getAll');
Route::get('/region/cache', 'RegionController@cache');
Route::get('/region/clear', 'RegionController@clear');
Route::match(['get', 'post'], '/changeInvoice/{id?}', 'OrderController@changeInvoice'); Route::match(['get', 'post'], '/changeInvoice/{id?}', 'OrderController@changeInvoice');
...@@ -153,5 +155,21 @@ Route::group(['middleware' => 'api'], function () { ...@@ -153,5 +155,21 @@ Route::group(['middleware' => 'api'], function () {
Route::get ('/handle/paylog', 'SpecialController@handlePayLog'); // 处理支付记录 Route::get ('/handle/paylog', 'SpecialController@handlePayLog'); // 处理支付记录
Route::get('/act/sendactmsg', 'CronController@sendActMsg'); // 推送活动短信 Route::get('/act/sendactmsg', 'CronController@sendActMsg'); // 推送活动短信
Route::get ('/handle/paytype', 'SpecialController@changeOrderPayType'); // 自营更改预付款支付方式 Route::get ('/handle/paytype', 'SpecialController@changeOrderPayType'); // 自营更改预付款支付方式
Route::post('/hprose/service', function (Request $request) {
$server = new \App\Services\ExportService();
$server->init(); //开启服务
});
Route::get('client', function () {
$server = new \App\Services\TestClient();
$server->index();
});
}); });
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class OrderAddressModel extends Model
{
protected $connection = 'order';
protected $table = 'lie_order_address';
protected $primaryKey = 'order_address_id';
public $timestamps = false;
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class OrderShippingModel extends Model
{
protected $connection = 'order';
protected $table = 'lie_order_shipping';
protected $primaryKey = 'order_shipping_id';
public $timestamps = false;
}
\ No newline at end of file
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class RegionModel extends Model
{
protected $connection = 'order';
protected $table = 'lie_region';
protected $primaryKey = 'region_id';
public $timestamps = false;
// 获取地址
public function getRegion($region_type=1)
{
$map['region_type'] = $region_type;
return $this->where($map)->select('region_id', 'parent_id', 'region_name')->get()->toArray();
}
}
\ No newline at end of file
<?php
namespace App\Services;
use Hprose\Http\Server;
use App\Model\OrderModel;
class ExportService {
public function init()
{
$server = new Server();
$server->addMethod('test', $this);
$server->addMethod('orderExport', $this);
$server->handle();
}
public function test()
{
return 'hello';
}
// 订单导出
public function orderExport($map)
{
$map = json_decode($map, true);
if (!$map) return json_encode(['code'=>-10001, 'msg'=>'查询条件不能为空']);
$orderModel = new OrderModel();
$list = $orderModel->orderExport($map);
return json_encode(['code'=>0, 'msg'=>'成功', 'count'=>$list['total'], 'data'=>$list['data']]);
}
}
<?php
namespace App\Services;
use Hprose\Http\Client;
class TestClient
{
public function index()
{
//服务端路由在api路由中配置,则此处路由应加上api/test
//实例化可选参数 加上false 即创建创建一个同步的 HTTP 客户端
//不写false 为创建一个异步的 HTTP 客户端
$user =new Client('http://lorder.liexin.net/hprose/service', false);
// $res = $user->test();
$res=$user->orderExport(json_encode(['limit'=>10, 'p'=>1]));
print_r($res);
}
}
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
"guzzlehttp/guzzle": "^6.3", "guzzlehttp/guzzle": "^6.3",
"predis/predis": "^1.1", "predis/predis": "^1.1",
"redgo/monitor-ding": "0.2", "redgo/monitor-ding": "0.2",
"barryvdh/laravel-debugbar": "^2.0" "barryvdh/laravel-debugbar": "^2.0",
"hprose/hprose": "2.0"
}, },
"require-dev": { "require-dev": {
"fzaninotto/faker": "~1.4", "fzaninotto/faker": "~1.4",
......
...@@ -12,7 +12,7 @@ return [ ...@@ -12,7 +12,7 @@ return [
| |
*/ */
'enabled' => env('APP_DEBUG', false), 'enabled' => env('APP_DEBUG_X', false),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
......
...@@ -83,4 +83,9 @@ return [ ...@@ -83,4 +83,9 @@ return [
// crm // crm
'crm_domain' => 'http://lcrm.liexin.net', 'crm_domain' => 'http://lcrm.liexin.net',
// 导出系统
'export_url' => 'http://export.liexin.com',
'export_joint_source_id' => 16,
'export_self_source_id' => 17,
]; ];
...@@ -285,27 +285,53 @@ ...@@ -285,27 +285,53 @@
listUrl += '&order_goods_type='+type; listUrl += '&order_goods_type='+type;
} }
location.href = listUrl; return listUrl;
} }
// 联营搜索 // 联营搜索
$('.searchOrder').click(function(){ $('.searchOrder').click(function(){
orderListCommon('/list', 1); var listUrl = orderListCommon('/list', 1);
location.href = listUrl;
})
// 自营搜索
$('.search_self_order').click(function(){
var listUrl = orderListCommon('/self_order', 2);
location.href = listUrl;
}) })
// 联营导出订单 // 联营导出订单
$('.exportExcel').click(function() { $('.exportExcel').click(function() {
orderListCommon('/export', 1); var listUrl = orderListCommon('/export', 1);
$.get(listUrl, function(resp) {
if (resp.err_code != 0) {
layer.msg(resp.err_msg);
return false;
}
window.open(resp.data, '_blank');
}) })
// 自营搜索 layer.msg('推入导出系统中...', {icon: 16, time: 1000, shade: 0.3}); // 阻止重复提交
$('.search_self_order').click(function(){
orderListCommon('/self_order', 2);
}) })
// 自营导出订单 // 自营导出订单
$('.self_export').click(function() { $('.self_export').click(function() {
orderListCommon('/export', 2); var listUrl = orderListCommon('/export', 2);
$.get(listUrl, function(resp) {
if (resp.err_code != 0) {
layer.msg(resp.err_msg);
return false;
}
window.open(resp.data, '_blank');
})
layer.msg('推入导出系统中...', {icon: 16, time: 1000, shade: 0.3}); // 阻止重复提交
}) })
// 选择查看测试订单 // 选择查看测试订单
......
...@@ -279,7 +279,7 @@ class ClassLoader ...@@ -279,7 +279,7 @@ class ClassLoader
*/ */
public function setApcuPrefix($apcuPrefix) public function setApcuPrefix($apcuPrefix)
{ {
$this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
} }
/** /**
...@@ -377,11 +377,11 @@ class ClassLoader ...@@ -377,11 +377,11 @@ class ClassLoader
$subPath = $class; $subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) { while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos); $subPath = substr($subPath, 0, $lastPos);
$search = $subPath.'\\'; $search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) { if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) { foreach ($this->prefixDirsPsr4[$search] as $dir) {
$length = $this->prefixLengthsPsr4[$first][$search]; if (file_exists($file = $dir . $pathEnd)) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
return $file; return $file;
} }
} }
......
This diff could not be displayed because it is too large.
...@@ -17,6 +17,7 @@ return array( ...@@ -17,6 +17,7 @@ return array(
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php', 'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php', 'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
'58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php', '58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'4a1f389d6ce373bda9e57857d3b61c84' => $vendorDir . '/barryvdh/laravel-debugbar/src/helpers.php', '4a1f389d6ce373bda9e57857d3b61c84' => $vendorDir . '/barryvdh/laravel-debugbar/src/helpers.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'7a3a3ddf55aa5bdbff2cc90a2e666654' => $vendorDir . '/hprose/hprose/src/Hprose.php',
); );
This diff could not be displayed because it is too large.
temp
vendor
composer.phar
composer.lock
/netbeans
/nbproject
/examples/nbproject
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- 7.1
sudo: required
before_script:
- composer install
- cd tests
script: phpunit -v
The MIT License (MIT)
Copyright (c) 2008-2016 http://hprose.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.
# Hprose for PHP
[![Build Status](https://travis-ci.org/hprose/hprose-php.svg?branch=master)](https://travis-ci.org/hprose/hprose-php)
[![Join the chat at https://gitter.im/hprose/hprose-php](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/hprose/hprose-php?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
![Supported PHP versions: 5.3 .. 7.1](https://img.shields.io/badge/php-5.3~7.1-blue.svg)
[![Packagist](https://img.shields.io/packagist/v/hprose/hprose.svg)](https://packagist.org/packages/hprose/hprose)
[![Packagist Download](https://img.shields.io/packagist/dm/hprose/hprose.svg)](https://packagist.org/packages/hprose/hprose)
[![License](https://img.shields.io/packagist/l/hprose/hprose.svg)](https://packagist.org/packages/hprose/hprose)
## Introduction
*Hprose* is a High Performance Remote Object Service Engine.
It is a modern, lightweight, cross-language, cross-platform, object-oriented, high performance, remote dynamic communication middleware. It is not only easy to use, but powerful. You just need a little time to learn, then you can use it to easily construct cross language cross platform distributed application system.
*Hprose* supports many programming languages, for example:
* AAuto Quicker
* ActionScript
* ASP
* C++
* Dart
* Delphi/Free Pascal
* dotNET(C#, Visual Basic...)
* Golang
* Java
* JavaScript
* Node.js
* Objective-C
* Perl
* PHP
* Python
* Ruby
* ...
Through *Hprose*, You can conveniently and efficiently intercommunicate between those programming languages.
This project is the implementation of Hprose for PHP.
Hprose 2.0 for PHP Documents: https://github.com/hprose/hprose-php/wiki
# Hprose for PHP
[![Build Status](https://travis-ci.org/hprose/hprose-php.svg?branch=master)](https://travis-ci.org/hprose/hprose-php)
[![Join the chat at https://gitter.im/hprose/hprose-php](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/hprose/hprose-php?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
![Supported PHP versions: 5.3 .. 7.1](https://img.shields.io/badge/php-5.3~7.1-blue.svg)
[![Packagist](https://img.shields.io/packagist/v/hprose/hprose.svg)](https://packagist.org/packages/hprose/hprose)
[![Packagist Download](https://img.shields.io/packagist/dm/hprose/hprose.svg)](https://packagist.org/packages/hprose/hprose)
[![License](https://img.shields.io/packagist/l/hprose/hprose.svg)](https://packagist.org/packages/hprose/hprose)
## 简介
*Hprose* 是高性能远程对象服务引擎(High Performance Remote Object Service Engine)的缩写。
它是一个先进的轻量级的跨语言跨平台面向对象的高性能远程动态通讯中间件。它不仅简单易用,而且功能强大。你只需要稍许的时间去学习,就能用它轻松构建跨语言跨平台的分布式应用系统了。
*Hprose* 支持众多编程语言,例如:
* AAuto Quicker
* ActionScript
* ASP
* C++
* Dart
* Delphi/Free Pascal
* dotNET(C#, Visual Basic...)
* Golang
* Java
* JavaScript
* Node.js
* Objective-C
* Perl
* PHP
* Python
* Ruby
* ...
通过 *Hprose*,你就可以在这些语言之间方便高效的实现互通了。
本项目是 Hprose 的 PHP 语言版本实现。
Hprose 2.0 for PHP 文档: https://github.com/hprose/hprose-php/wiki
{
"name": "hprose/hprose",
"type": "library",
"description": "It is a modern, lightweight, cross-language, cross-platform, object-oriented, high performance, remote dynamic communication middleware. It is not only easy to use, but powerful. You just need a little time to learn, then you can use it to easily construct cross language cross platform distributed application system.",
"keywords": [
"hprose",
"phprpc",
"rpc",
"webservice",
"websocket",
"http",
"ajax",
"json",
"jsonrpc",
"xmlrpc",
"cross-language",
"cross-platform",
"cross-domain",
"html5",
"serialize",
"serialization",
"protocol",
"web",
"service",
"framework",
"library",
"game",
"communication",
"middleware",
"webapi",
"socket",
"tcp",
"async",
"unix",
"future"
],
"homepage": "http://hprose.com/",
"license": "MIT",
"authors": [
{
"name": "Ma Bingyao",
"email": "andot@hprose.com",
"homepage": "http://hprose.com",
"role": "Developer"
}
],
"require": {
"php": ">=5.3.0"
},
"suggest": {
"ext-hprose": "Faster serialize and unserialize hprose extension."
},
"require-dev": {
"phpunit/phpunit": ">=4.0.0"
},
"autoload": {
"files": ["src/Hprose.php"]
}
}
{
"name": "hprose/examples",
"description": "examples of hprose",
"authors": [
{
"name": "andot",
"email": "mabingyao@gmail.com"
}
],
"require": {
"php": ">=5.3.0",
"hprose/hprose": "dev-master"
}
}
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
Future\all(array(1, Future\value(2), 3))->then(function($value) {
var_dump($value);
});
Future\join(1, Future\value(2), 3)->then(function($value) {
var_dump($value);
});
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$p = Future\reject(new OutOfRangeException());
$p->catchError(function($reason) { return 'this is a OverflowException'; },
function($reason) { return $reason instanceof OverflowException; })
->catchError(function($reason) { return 'this is a OutOfRangeException'; },
function($reason) { return $reason instanceof OutOfRangeException; })
->then(function($value) { var_dump($value); });
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use \Hprose\Future;
use \Hprose\Http\Client;
Future\co(function() {
$test = new Client("http://hprose.com/example/");
var_dump((yield $test->hello("hprose")));
$a = $test->sum(1, 2, 3);
$b = $test->sum(4, 5, 6);
$c = $test->sum(7, 8, 9);
var_dump((yield $test->sum($a, $b, $c)));
var_dump((yield $test->hello("world")));
});
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use \Hprose\Future;
use \Hprose\Http\Client;
$test = new Client("http://hprose.com/example/");
Future\co(function() use ($test) {
for ($i = 0; $i < 5; $i++) {
var_dump((yield $test->hello("1-" . $i)));
}
});
Future\co(function() use ($test) {
for ($i = 0; $i < 5; $i++) {
var_dump((yield $test->hello("2-" . $i)));
}
});
<?php
require_once "../vendor/autoload.php";
use \Hprose\Future;
use \Hprose\Http\Client;
$test = new Client("http://hprose.com/example/");
function hello($n, $test) {
$result = array();
for ($i = 0; $i < 5; $i++) {
$result[] = $test->hello("$n-$i");
}
yield $result;
}
Future\co(function() use ($test) {
$result = (yield Future\co(function($test) {
$result = array();
for ($i = 0; $i < 3; $i++) {
$result[] = Future\co('hello', $i, $test);
}
yield $result;
}, $test));
var_dump($result);
});
<?php
require_once "../vendor/autoload.php";
use \Hprose\Future;
use \Hprose\Http\Client;
$test = new Client("http://hprose.com/example/");
Future\co(function() use ($test) {
for ($i = 0; $i < 5; $i++) {
var_dump((yield $test->hello("1-" . $i)));
}
$var_dump = Future\wrap('var_dump');
for ($i = 0; $i < 5; $i++) {
$var_dump($test->hello("2-" . $i));
}
for ($i = 0; $i < 5; $i++) {
var_dump((yield $test->hello("3-" . $i)));
}
});
<?php
require_once "../vendor/autoload.php";
use \Hprose\Future;
use \Hprose\Http\Client;
$test = new Client("http://hprose.com/example/");
$coroutine = Future\wrap(function($test) {
var_dump(1);
var_dump((yield $test->hello("hprose")));
$a = $test->sum(1, 2, 3);
$b = $test->sum(4, 5, 6);
$c = $test->sum(7, 8, 9);
var_dump((yield $test->sum($a, $b, $c)));
var_dump((yield $test->hello("world")));
});
$coroutine($test);
$coroutine(Future\value($test));
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use \Hprose\Future;
class Test {
function test($x) {
yield $x;
}
}
$test = Future\wrap(new Test());
$test->test(123)->then('var_dump');
$test->test(Future\value('hello'))->then('var_dump');
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Completer;
$completer = new Completer();
$promise = $completer->future();
$promise->then(function($value) {
var_dump($value);
});
var_dump($completer->isCompleted());
$completer->complete('hprose');
var_dump($completer->isCompleted());
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
function dumpArray($value, $key) {
var_dump("a[$key] = $value");
}
$a1 = array(2, Future\value(5), 9);
$a2 = array('name' => Future\value('Tom'), 'age' => Future\value(18));
Future\each($a1, 'dumpArray');
Future\each($a2, 'dumpArray');
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
function dumpArray($value, $key) {
var_dump("a[$key] = $value");
}
$a1 = Future\value(array(2, Future\value(5), 9));
$a2 = Future\value(array('name' => Future\value('Tom'), 'age' => Future\value(18)));
$a1->each('dumpArray');
$a2->each('dumpArray');
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
function isBigEnough($value) {
return $value >= 10;
}
$a1 = array(12, Future\value(5), 8, Future\value(130), 44);
$a2 = array(12, Future\value(54), 18, Future\value(130), 44);
$a3 = Future\value($a1);
$a4 = Future\value($a2);
$dump(Future\every($a1, 'isBigEnough')); // false
$dump(Future\every($a2, 'isBigEnough')); // true
$dump(Future\every($a3, 'isBigEnough')); // false
$dump(Future\every($a4, 'isBigEnough')); // true
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
function isBigEnough($value) {
return $value >= 10;
}
$a1 = Future\value(array(12, Future\value(5), 8, Future\value(130), 44));
$a2 = Future\value(array(12, Future\value(54), 18, Future\value(130), 44));
$dump($a1->every('isBigEnough')); // false
$dump($a2->every('isBigEnough')); // true
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
function isBigEnough($value) {
return $value >= 8;
}
$a1 = array(12, Future\value(5), 8, Future\value(130), 44);
$a2 = Future\value($a1);
$dump(Future\filter($a1, 'isBigEnough'));
$dump(Future\filter($a2, 'isBigEnough'));
$a3 = array('Tom' => 8, 'Jerry' => Future\value(5), 'Spike' => 10, 'Tyke' => 3);
$a4 = Future\value($a3);
$dump(Future\filter($a3, 'isBigEnough'));
$dump(Future\filter($a3, 'isBigEnough', true));
$dump(Future\filter($a4, 'isBigEnough', true));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
function isBigEnough($value) {
return $value >= 8;
}
$a = Future\value(array(
'Tom' => 8,
'Jerry' => Future\value(5),
'Spike' => 10,
'Tyke' => 3
));
$dump($a->filter('isBigEnough'));
$dump($a->filter('isBigEnough', true));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
var_dump(Future\isFuture(123));
var_dump(Future\isFuture(Future\value(123)));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
$a = array(1, Future\value(4), 9);
$dump(Future\map($a, 'sqrt'));
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
$a = Future\value(array(1, Future\value(4), 9));
$dump($a->map('sqrt'));
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$p = Future\promise(function($resolve, $reject) {
$a = 1;
$b = 2;
if ($a != $b) {
$resolve('OK');
}
else {
$reject(new Exception("$a == $b"));
}
});
$p->then(function($value) {
var_dump($value);
});
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
$numbers = array(Future\value(0), 1, Future\value(2), 3, Future\value(4));
function add($a, $b) {
return $a + $b;
}
$dump(Future\reduce($numbers, 'add'));
$dump(Future\reduce($numbers, 'add', 10));
$dump(Future\reduce($numbers, 'add', Future\value(20)));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
$numbers = Future\value(array(Future\value(0), 1, Future\value(2), 3, Future\value(4)));
function add($a, $b) {
return $a + $b;
}
$dump($numbers->reduce('add'));
$dump($numbers->reduce('add', 10));
$dump($numbers->reduce('add', Future\value(20)));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
function add($a, $b) {
return $a + $b;
}
$p1 = Future\resolve(3);
Future\run('add', 2, $p1)->then('var_dump');
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
$numbers = Future\value(array(Future\value(0), 1, Future\value(2), 3, Future\value(4)));
$dump($numbers->search(2));
$dump($numbers->search(Future\value(3)));
$dump($numbers->search(true));
$dump($numbers->search(true, true));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
$numbers = array(Future\value(0), 1, Future\value(2), 3, Future\value(4));
$dump(Future\search($numbers, 2));
$dump(Future\search($numbers, Future\value(3)));
$dump(Future\search($numbers, true));
$dump(Future\search($numbers, true, true));
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$p1 = Future\resolve(3);
$p2 = Future\reject(new Exception("x"));
Future\settle(array(true, $p1, $p2))->then('print_r');
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
function isBigEnough($value) {
return $value >= 10;
}
$a1 = array(12, Future\value(5), 8, Future\value(130), 44);
$a2 = array(1, Future\value(5), 8, Future\value(1), 4);
$a3 = Future\value($a1);
$a4 = Future\value($a2);
$dump(Future\some($a1, 'isBigEnough')); // true
$dump(Future\some($a2, 'isBigEnough')); // false
$dump(Future\some($a3, 'isBigEnough')); // true
$dump(Future\some($a4, 'isBigEnough')); // false
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$dump = Future\wrap('var_dump');
function isBigEnough($value) {
return $value >= 10;
}
$a1 = Future\value(array(12, Future\value(5), 8, Future\value(130), 44));
$a2 = Future\value(array(1, Future\value(5), 8, Future\value(1), 4));
$dump($a1->some('isBigEnough')); // true
$dump($a2->some('isBigEnough')); // false
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$p1 = new Future(function() {
return array(Future\value(1), Future\value(2));
});
$p1->then(function($value) {
var_dump($value);
});
$p2 = Future\sync(function() {
return array(Future\value(1), Future\value(2));
});
$p2->then(function($value) {
var_dump($value);
});
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$a = array(1, Future\value(2), 3, Future\value(4), 5);
$o = new \stdClass();
$o->name = Future\value("Tom");
$o->age = Future\value(18);
Future\toFuture($a)->then(function($value) {
var_dump($value);
});
Future\toFuture($o)->then(function($value) {
var_dump($value);
});
Future\toPromise($a)->then(function($value) {
var_dump($value);
});
Future\toPromise($o)->then(function($value) {
var_dump($value);
});
\ No newline at end of file
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
$p1 = Future\resolve('resolve hprose');
$p1->whenComplete(function() {
var_dump('p1 complete');
})->then(function($value) {
var_dump($value);
});
$p2 = Future\reject(new Exception('reject thrift'));
$p2->whenComplete(function() {
var_dump('p2 complete');
})->catchError(function($reason) {
var_dump($reason->getMessage());
});
$p3 = Future\resolve('resolve protobuf');
$p3->whenComplete(function() {
var_dump('p3 complete');
throw new Exception('reject protobuf');
})->catchError(function($reason) {
var_dump($reason->getMessage());
});
<?php
require_once "../vendor/autoload.php";
use Hprose\Future;
class Test {
function add($a, $b) {
return $a + $b;
}
function sub($a, $b) {
return $a - $b;
}
function mul($a, $b) {
return $a * $b;
}
function div($a, $b) {
return $a / $b;
}
}
$var_dump = Future\wrap('var_dump');
$test = Future\wrap(new Test());
$var_dump($test->add(1, Future\value(2)));
$var_dump($test->sub(Future\value(1), 2));
$var_dump($test->mul(Future\value(1), Future\value(2)));
$var_dump($test->div(1, 2));
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose.php *
* *
* hprose for php 5.3+ *
* *
* LastModified: Jul 24, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
require_once 'Throwable.php';
require_once 'TypeError.php';
require_once 'Hprose/Future/functions.php';
require_once 'Hprose/Promise/functions.php';
require_once 'Hprose/functions.php';
require_once 'functions.php';
spl_autoload_register(function($className) {
if ((strlen($className) > 6) && (strtolower(substr($className, 0, 6)) === "hprose")) {
if ($className{6} === '\\') {
include __DIR__ . DIRECTORY_SEPARATOR . str_replace("\\", DIRECTORY_SEPARATOR, $className) . ".php";
}
else {
// Deprecated
// Compatible with older versions only
// You'd better not use these classes.
switch (strtolower($className)) {
case 'hproseasync':
class_alias('Hprose\\Async', 'HproseAsync');
break;
case 'hprosecompleter':
class_alias('Hprose\\Completer', 'HproseCompleter');
break;
case 'hprosefuture':
class_alias('Hprose\\Future', 'HproseFuture');
break;
case 'hprosetags':
class_alias('Hprose\\Tags', 'HproseTags');
break;
case 'hprosebytesio':
class_alias('Hprose\\BytesIO', 'HproseBytesIO');
break;
case 'hproseclassmanager':
class_alias('Hprose\\ClassManager', 'HproseClassManager');
break;
case 'hproserawreader':
class_alias('Hprose\\RawReader', 'HproseRawReader');
break;
case 'hprosereader':
class_alias('Hprose\\Reader', 'HproseReader');
break;
case 'hprosewriter':
class_alias('Hprose\\Writer', 'HproseWriter');
break;
case 'hproseformatter':
class_alias('Hprose\\Formatter', 'HproseFormatter');
break;
case 'hproseresultmode':
class_alias('Hprose\\ResultMode', 'HproseResultMode');
break;
case 'hprosefilter':
class_alias('Hprose\\Filter', 'HproseFilter');
break;
case 'hproseclient':
class_alias('Hprose\\Client', 'HproseClient');
break;
case 'hproseservice':
class_alias('Hprose\\Service', 'HproseService');
break;
case 'hprosehttpclient':
class_alias('Hprose\\Http\\Client', 'HproseHttpClient');
break;
case 'hprosehttpservice':
class_alias('Hprose\\Http\\Service', 'HproseHttpService');
break;
case 'hprosehttpserver':
class_alias('Hprose\\Http\\Server', 'HproseHttpServer');
break;
case 'hprosesocketclient':
class_alias('Hprose\\Socket\\Client', 'HproseSocketClient');
break;
case 'hprosejsonrpcclientfilter':
class_alias('Hprose\\Filter\\JSONRPC\\ClientFilter', 'HproseJSONRPCClientFilter');
break;
case 'hprosejsonrpcservicefilter':
class_alias('Hprose\\Filter\\JSONRPC\\ServiceFilter', 'HproseJSONRPCServiceFilter');
break;
case 'hprosexmlrpcclientfilter':
class_alias('Hprose\\Filter\\XMLRPC\\ClientFilter', 'HproseXMLRPCClientFilter');
break;
case 'hprosexmlrpcservicefilter':
class_alias('Hprose\\Filter\\XMLRPC\\ServiceFilter', 'HproseXMLRPCServiceFilter');
break;
default:
return false;
}
}
return true;
}
return false;
});
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/BytesIO.php *
* *
* hprose BytesIO class for php 5.3+ *
* *
* LastModified: Jul 11, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use Exception;
class BytesIO {
protected $buffer;
protected $length;
protected $pos = 0;
protected $mark = -1;
public function __construct($string = '') {
$this->buffer = $string;
$this->length = strlen($string);
}
public function close() {
$this->buffer = '';
$this->pos = 0;
$this->mark = -1;
$this->length = 0;
}
public function length() {
return $this->length;
}
public function getc() {
if ($this->pos < $this->length) {
return $this->buffer[$this->pos++];
}
return '';
}
public function read($n) {
$s = substr($this->buffer, $this->pos, $n);
$this->skip($n);
return $s;
}
public function readfull() {
$s = substr($this->buffer, $this->pos);
$this->pos = $this->length;
return $s;
}
public function readuntil($tag) {
$pos = strpos($this->buffer, $tag, $this->pos);
if ($pos !== false) {
$s = substr($this->buffer, $this->pos, $pos - $this->pos);
$this->pos = $pos + strlen($tag);
}
else {
$s = substr($this->buffer, $this->pos);
$this->pos = $this->length;
}
return $s;
}
public function readString($n) {
$pos = $this->pos;
$buffer = $this->buffer;
for ($i = 0; $i < $n; ++$i) {
switch (ord($buffer[$pos]) >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7: {
// 0xxx xxxx
++$pos;
break;
}
case 12:
case 13: {
// 110x xxxx 10xx xxxx
$pos += 2;
break;
}
case 14: {
// 1110 xxxx 10xx xxxx 10xx xxxx
$pos += 3;
break;
}
case 15: {
// 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
$pos += 4;
++$i;
if ($i >= $n) {
throw new Exception('bad utf-8 encoding');
}
break;
}
default: {
throw new Exception('bad utf-8 encoding');
}
}
}
return $this->read($pos - $this->pos);
}
public function mark() {
$this->mark = $this->pos;
}
public function unmark() {
$this->mark = -1;
}
public function reset() {
if ($this->mark != -1) {
$this->pos = $this->mark;
}
}
public function skip($n) {
$this->pos += $n;
}
public function eof() {
return ($this->pos >= $this->length);
}
public function write($str, $n = -1) {
if ($n == -1) {
$this->buffer .= $str;
$n = strlen($str);
}
else {
$this->buffer .= substr($str, 0, $n);
}
$this->length += $n;
}
public function load($filename) {
$str = file_get_contents($filename);
if ($str === false) return false;
$this->buffer = $str;
$this->pos = 0;
$this->mark = -1;
$this->length = strlen($str);
return true;
}
public function save($filename) {
return file_put_contents($filename, $this->buffer);
}
public function toString() {
return $this->buffer;
}
public function __toString() {
return $this->buffer;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/ClassManager.php *
* *
* hprose class manager class for php 5.3+ *
* *
* LastModified: Jul 11, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class ClassManager {
private static $classCache1 = array();
private static $classCache2 = array();
public static function register($class, $alias) {
self::$classCache1[$alias] = $class;
self::$classCache2[$class] = $alias;
}
public static function getClassAlias($class) {
if (isset(self::$classCache2[$class])) {
return self::$classCache2[$class];
}
$alias = str_replace('\\', '_', $class);
self::register($class, $alias);
return $alias;
}
public static function getClass($alias) {
if (isset(self::$classCache1[$alias])) {
return self::$classCache1[$alias];
}
if (!class_exists($alias)) {
$class = str_replace('_', '\\', $alias);
if (class_exists($class)) {
self::register($class, $alias);
return $class;
}
return 'stdClass';
}
return $alias;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Completer.php *
* *
* hprose Completer class for php 5.3+ *
* *
* LastModified: Jul 11, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class Completer {
private $future;
public function __construct() {
$this->future = new Future();
}
public function future() {
return $this->future;
}
public function complete($result) {
$this->future->resolve($result);
}
public function completeError($error) {
$this->future->reject($error);
}
public function isCompleted() {
return $this->future->state !== Future::PENDING;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Deferred.php *
* *
* hprose Deferred class for php 5.3+ *
* *
* LastModified: Jul 11, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class Deferred {
public $promise;
public function __construct() {
$this->promise = new Future();
}
public function resolve($value) {
$this->promise->resolve($value);
}
public function reject($reason) {
$this->promise->reject($reason);
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/FakeReaderRefer.php *
* *
* hprose FakeReaderRefer class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use Exception;
class FakeReaderRefer implements ReaderRefer {
public function set($val) {}
public function read($index) {
throw new Exception("Unexpected serialize tag '" .
Tags::TagRef .
"' in stream");
}
public function reset() {}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/FakeWriterRefer.php *
* *
* hprose FakeWriterRefer class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class FakeWriterRefer implements WriterRefer {
public function set($val) {}
public function write(BytesIO $stream, $val) { return false; }
public function reset() {}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Filter.php *
* *
* hprose filter interface for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use stdClass;
interface Filter {
public function inputFilter($data, stdClass $context);
public function outputFilter($data, stdClass $context);
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Filter/JSONRPC/ClientFilter.php *
* *
* json rpc client filter class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Filter\JSONRPC;
use stdClass;
use Exception;
use Hprose\Filter;
use Hprose\BytesIO;
use Hprose\Writer;
use Hprose\Reader;
use Hprose\Tags;
class ClientFilter implements Filter {
private static $id = 1;
private $version;
public function __construct() {
$this->version = "2.0";
}
public function getVersion() {
return $this->version;
}
public function setVersion($version) {
if ($version === "1.0" || $version === "1.1" || $version === "2.0") {
$this->version = $version;
}
else {
throw new Exception("version must be 1.0, 1.1 or 2.0 in string format.");
}
}
public function inputFilter($data, stdClass $context) {
$response = json_decode($data);
if (!isset($response->result)) {
$response->result = null;
}
if (!isset($response->error)) {
$response->error = null;
}
$stream = new BytesIO();
$writer = new Writer($stream, true);
if ($response->error) {
$stream->write(Tags::TagError);
$writer->writeString($response->error->message);
}
else {
$stream->write(Tags::TagResult);
$writer->serialize($response->result);
}
$stream->write(Tags::TagEnd);
return $stream->toString();
}
public function outputFilter($data, stdClass $context) {
$request = new stdClass();
if ($this->version === "1.1") {
$request->version = "1.1";
}
else if ($this->version === "2.0") {
$request->jsonrpc = "2.0";
}
$stream = new BytesIO($data);
$reader = new Reader($stream);
$tag = $stream->getc();
if ($tag === Tags::TagCall) {
$request->method = $reader->readString();
$tag = $stream->getc();
if ($tag == Tags::TagList) {
$reader->reset();
$request->params = $reader->readListWithoutTag();
}
}
else {
throw new Exception("Error Processing Request", 1);
}
$request->id = self::$id++;
return json_encode($request);
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Filter/JSONRPC/ServiceFilter.php *
* *
* json rpc service filter class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Filter\JSONRPC;
use stdClass;
use Hprose\Filter;
use Hprose\BytesIO;
use Hprose\Writer;
use Hprose\Reader;
use Hprose\Tags;
class ServiceFilter implements Filter {
function inputFilter($data, stdClass $context) {
if ($data !== "" && ($data{0} === '[' || $data{0} === '{')) {
try {
$requests = json_decode($data);
}
catch (Exception $e) {
return $data;
}
if ($data{0} === '{') {
$requests = array($requests);
}
else if (count($requests) === 0) {
return $data;
}
$stream = new BytesIO();
$writer = new Writer($stream, true);
$context->userdata->jsonrpc = array();
foreach ($requests as $request) {
$jsonrpc = new stdClass();
if (isset($request->id)) {
$jsonrpc->id = $request->id;
}
else {
$jsonrpc->id = null;
}
if (isset($request->version)) {
$jsonrpc->version = $request->version;
}
else if (isset($request->jsonrpc)) {
$jsonrpc->version = $request->jsonrpc;
}
else {
$jsonrpc->version = '1.0';
}
$context->userdata->jsonrpc[] = $jsonrpc;
if (isset($request->method)) {
$stream->write(Tags::TagCall);
$writer->writeString($request->method);
if (isset($request->params) &&
count($request->params) > 0) {
$writer->writeArray($request->params);
}
}
else {
unset($context->userdata->jsonrpc);
return $data;
}
}
$stream->write(Tags::TagEnd);
$data = $stream->toString();
unset($stream);
unset($writer);
}
return $data;
}
function outputFilter($data, stdClass $context) {
if (isset($context->userdata->jsonrpc)) {
$responses = array();
$stream = new BytesIO($data);
$reader = new Reader($stream);
$tag = $stream->getc();
foreach ($context->userdata->jsonrpc as $jsonrpc) {
$response = new stdClass();
$response->id = $jsonrpc->id;
$version = $jsonrpc->version;
if ($version !== '2.0') {
if ($version === '1.1') {
$response->version = '1.1';
}
$response->result = null;
$response->error = null;
}
else {
$response->jsonrpc = '2.0';
}
if ($tag !== Tags::TagEnd) {
$reader->reset();
if ($tag === Tags::TagResult) {
$response->result = $reader->unserialize();
}
else if ($tag === Tags::TagError) {
$lasterror = error_get_last();
$response->error = new stdClass();
$response->error->code = $lasterror['type'];
$response->error->message = $reader->unserialize();
}
$tag = $stream->getc();
}
else {
$response->result = null;
}
if ($response->id !== null) {
$responses[] = $response;
}
}
if (count($context->userdata->jsonrpc) === 1) {
if (count($responses) === 1) {
return json_encode($responses[0]);
}
return '';
}
return json_encode($responses);
}
return $data;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Filter/XMLRPC/ClientFilter.php *
* *
* xml-rpc client filter class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Filter\XMLRPC;
use stdClass;
use Exception;
use Hprose\Filter;
use Hprose\BytesIO;
use Hprose\Writer;
use Hprose\Reader;
use Hprose\Tags;
class ClientFilter implements Filter {
public function inputFilter($data, stdClass $context) {
$result = xmlrpc_decode($data, "UTF-8");
$stream = new BytesIO();
$writer = new Writer($stream, true);
if (isset($result['faultString'])) {
$stream->write(Tags::TagError);
$writer->writeString($result['faultString']);
}
else {
$stream->write(Tags::TagResult);
$writer->serialize($result);
}
$stream->write(Tags::TagEnd);
return $stream->toString();
}
public function outputFilter($data, stdClass $context) {
$method = null;
$params = array();
$stream = new BytesIO($data);
$reader = new Reader($stream);
$tag = $stream->getc();
if ($tag === Tags::TagCall) {
$method = $reader->readString();
$tag = $stream->getc();
if ($tag ==Tags::TagList) {
$reader->reset();
$params = $reader->readListWithoutTag();
}
}
else {
throw new Exception("Error Processing Request", 1);
}
return xmlrpc_encode_request($method, $params);
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Filter/XMLRPC/ServiceFilter.php *
* *
* xml-rpc service filter class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Filter\XMLRPC;
use stdClass;
use Hprose\Filter;
use Hprose\BytesIO;
use Hprose\Writer;
use Hprose\Reader;
use Hprose\Tags;
class ServiceFilter implements Filter {
public function inputFilter($data, stdClass $context) {
if ($data !== "" && $data{0} === '<') {
$context->userdata->format = "xmlrpc";
$method = null;
$params = xmlrpc_decode_request($data, $method, "UTF-8");
$stream = new BytesIO();
$writer = new Writer($stream, true);
if (isset($method)) {
$stream->write(Tags::TagCall);
$writer->writeString($method);
if (isset($params)) {
$writer->writeArray($params);
}
}
$stream->write(Tags::TagEnd);
$data = $stream->toString();
}
return $data;
}
public function outputFilter($data, stdClass $context) {
if (isset($context->userdata->format) && $context->userdata->format === "xmlrpc") {
$result = null;
if ($data !== "") {
$stream = new BytesIO($data);
$reader = new Reader($stream);
while (($tag = $stream->getc()) !== Tags::TagEnd) {
$reader->reset();
switch ($tag) {
case Tags::TagResult:
$result = $reader->unserialize();
break;
case Tags::TagError:
$lasterror = error_get_last();
$result = array(
"faultCode" => $lasterror["type"],
"faultString" => $reader->unserialize()
);
break;
case Tags::TagFunctions:
$result = $reader->unserialize();
break;
default:
return xmlrpc_encode($result);
}
}
}
$data = xmlrpc_encode($result);
}
return $data;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Formatter.php *
* *
* hprose formatter class for php 5.3+ *
* *
* LastModified: Jul 16, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class Formatter {
public static function serialize($var, $simple = false) {
$stream = new BytesIO();
$writer = new Writer($stream, $simple);
$writer->serialize($var);
$data = $stream->toString();
$stream->close();
return $data;
}
public static function unserialize($data, $simple = false) {
$stream = new BytesIO($data);
$reader = new Reader($stream, $simple);
$result = $reader->unserialize();
$stream->close();
return $result;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Future/CallableWrapper.php *
* *
* Future CallableWrapper for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Future;
class CallableWrapper extends Wrapper {
public function __invoke() {
$obj = $this->obj;
return all(func_get_args())->then(function($args) use ($obj) {
return call_user_func_array($obj, $args);
});
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Future/UncatchableException.php *
* *
* UncatchableException for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Future;
use Exception;
class UncatchableException extends Exception {}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Future/Wrapper.php *
* *
* Future Wrapper for php 5.3+ *
* *
* LastModified: Jul 25, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Future;
use ReflectionMethod;
class Wrapper {
protected $obj;
public function __construct($obj) {
$this->obj = $obj;
}
public function __call($name, array $arguments) {
$method = array($this->obj, $name);
return all($arguments)->then(function($args) use ($method, $name) {
if (class_exists("\\Generator")) {
$m = new ReflectionMethod($this->obj, $name);
if ($m->isGenerator()) {
array_splice($args, 0, 0, array($method));
return call_user_func_array('\\Hprose\\Future\\co', $args);
}
}
return call_user_func_array($method, $args);
});
}
public function __get($name) {
return $this->obj->$name;
}
public function __set($name, $value) {
$this->obj->$name = $value;
}
public function __isset($name) {
return isset($this->obj->$name);
}
public function __unset($name) {
unset($this->obj->$name);
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/HandlerManager.php *
* *
* hprose HandlerManager class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use stdClass;
use Closure;
use Exception;
use Throwable;
abstract class HandlerManager {
private $invokeHandlers = array();
private $beforeFilterHandlers = array();
private $afterFilterHandlers = array();
private $defaultInvokeHandler;
private $defaultBeforeFilterHandler;
private $defaultAfterFilterHandler;
protected $invokeHandler;
protected $beforeFilterHandler;
protected $afterFilterHandler;
public function __construct() {
$self = $this;
$this->defaultInvokeHandler = function(/*string*/ $name, array &$args, stdClass $context) use ($self) {
return $self->invokeHandler($name, $args, $context);
};
$this->defaultBeforeFilterHandler = function(/*string*/ $request, stdClass $context) use ($self) {
return $self->beforeFilterHandler($request, $context);
};
$this->defaultAfterFilterHandler = function(/*string*/ $request, stdClass $context) use ($self) {
return $self->afterFilterHandler($request, $context);
};
$this->invokeHandler = $this->defaultInvokeHandler;
$this->beforeFilterHandler = $this->defaultBeforeFilterHandler;
$this->afterFilterHandler = $this->defaultAfterFilterHandler;
}
/*
This method is a protected method.
But PHP 5.3 can't call protected method in closure,
so we comment the protected keyword.
*/
/*protected*/ abstract function invokeHandler(/*string*/ $name, array &$args, stdClass $context);
/*
This method is a protected method.
But PHP 5.3 can't call protected method in closure,
so we comment the protected keyword.
*/
/*protected*/ abstract function beforeFilterHandler(/*string*/ $request, stdClass $context);
/*
This method is a protected method.
But PHP 5.3 can't call protected method in closure,
so we comment the protected keyword.
*/
/*protected*/ abstract function afterFilterHandler(/*string*/ $request, stdClass $context);
protected function getNextInvokeHandler(Closure $next, /*callable*/ $handler) {
return function(/*string*/ $name, array $args, stdClass $context) use ($next, $handler) {
try {
return Future\toPromise(call_user_func($handler, $name, $args, $context, $next));
}
catch (Exception $e) {
return Future\error($e);
}
catch (Throwable $e) {
return Future\error($e);
}
};
}
protected function getNextFilterHandler(Closure $next, /*callable*/ $handler) {
return function(/*string*/ $request, stdClass $context) use ($next, $handler) {
try {
return Future\toPromise(call_user_func($handler, $request, $context, $next));
}
catch (Exception $e) {
return Future\error($e);
}
catch (Throwable $e) {
return Future\error($e);
}
};
}
public function addInvokeHandler(/*callable*/ $handler) {
if ($handler == null) return;
$this->invokeHandlers[] = $handler;
$next = $this->defaultInvokeHandler;
for ($i = count($this->invokeHandlers) - 1; $i >= 0; --$i) {
$next = $this->getNextInvokeHandler($next, $this->invokeHandlers[$i]);
}
$this->invokeHandler = $next;
return $this;
}
public function addBeforeFilterHandler(/*callable*/ $handler) {
if ($handler == null) return;
$this->beforeFilterHandlers[] = $handler;
$next = $this->defaultBeforeFilterHandler;
for ($i = count($this->beforeFilterHandlers) - 1; $i >= 0; --$i) {
$next = $this->getNextFilterHandler($next, $this->beforeFilterHandlers[$i]);
}
$this->beforeFilterHandler = $next;
return $this;
}
public function addAfterFilterHandler(/*callable*/ $handler) {
if ($handler == null) return;
$this->afterFilterHandlers[] = $handler;
$next = $this->defaultAfterFilterHandler;
for ($i = count($this->afterFilterHandlers) - 1; $i >= 0; --$i) {
$next = $this->getNextFilterHandler($next, $this->afterFilterHandlers[$i]);
}
$this->afterFilterHandler = $next;
return $this;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Http/Server.php *
* *
* hprose http server class for php 5.3+ *
* *
* LastModified: Jul 17, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Http;
class Server extends Service {
public function start() {
$this->handle();
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Http/Service.php *
* *
* hprose http service class for php 5.3+ *
* *
* LastModified: Jul 22, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Http;
use stdClass;
use Hprose\Future;
class Service extends \Hprose\Service {
const ORIGIN = 'HTTP_ORIGIN';
public $onSendHeader = null;
public $crossDomain = false;
public $p3p = false;
public $get = true;
private $origins = array();
public function header($name, $value, $context) {
header("$name: $value");
}
public function getAttribute($name, $context) {
return $_SERVER[$name];
}
public function hasAttribute($name, $context) {
return isset($_SERVER[$name]);
}
protected function readRequest($context) {
return file_get_contents("php://input");
}
protected function createContext($request, $response) {
$context = new stdClass();
$context->server = $this;
$context->request = $request;
$context->response = $response;
$context->userdata = new stdClass();
return $context;
}
public function writeResponse($data, $context) {
echo $data;
}
public function isGet($context) {
return @$_SERVER['REQUEST_METHOD'] === 'GET';
}
public function isPost($context) {
return @$_SERVER['REQUEST_METHOD'] === 'POST';
}
private function sendHeader($context) {
if ($this->onSendHeader !== null) {
$sendHeader = $this->onSendHeader;
call_user_func($sendHeader, $context);
}
$this->header('Content-Type', 'text/plain', $context);
if ($this->p3p) {
$this->header('P3P', 'CP="CAO DSP COR CUR ADM DEV TAI PSA PSD ' .
'IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi ' .
'UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV ' .
'INT DEM CNT STA POL HEA PRE GOV"', $context);
}
if ($this->crossDomain) {
if ($this->hasAttribute(static::ORIGIN, $context) &&
$this->getAttribute(static::ORIGIN, $context) != "null") {
$origin = $this->getAttribute(static::ORIGIN, $context);
if (count($this->origins) === 0 ||
isset($this->origins[strtolower($origin)])) {
$this->header('Access-Control-Allow-Origin', $origin, $context);
$this->header('Access-Control-Allow-Credentials', 'true', $context);
}
}
else {
$this->header('Access-Control-Allow-Origin', '*', $context);
}
}
}
public function isCrossDomainEnabled() {
return $this->crossDomain;
}
public function setCrossDomainEnabled($enable = true) {
$this->crossDomain = $enable;
}
public function isP3PEnabled() {
return $this->p3p;
}
public function setP3PEnabled($enable = true) {
$this->p3p = $enable;
}
public function isGetEnabled() {
return $this->get;
}
public function setGetEnabled($enable = true) {
$this->get = $enable;
}
public function addAccessControlAllowOrigin($origin) {
$count = count($origin);
if (($count > 0) && ($origin[$count - 1] === "/")) {
$origin = substr($origin, 0, -1);
}
$this->origins[strtolower($origin)] = true;
}
public function removeAccessControlAllowOrigin($origin) {
$count = count($origin);
if (($count > 0) && ($origin[$count - 1] === "/")) {
$origin = substr($origin, 0, -1);
}
unset($this->origins[strtolower($origin)]);
}
public function handle($request = null, $response = null) {
$context = $this->createContext($request, $response);
$self = $this;
$this->userFatalErrorHandler = function($error) use ($self, $context) {
$self->writeResponse($self->endError($error, $context), $context);
};
$this->sendHeader($context);
$result = '';
if ($this->isGet($context) && $this->get) {
$result = $this->doFunctionList();
}
elseif ($this->isPost($context)) {
$result = $this->defaultHandle($this->readRequest($context), $context);
}
else {
$result = $this->doFunctionList();
}
if (Future\isFuture($result)) {
$result->then(function($result) use ($self, $context) {
$self->writeResponse($result, $context);
});
}
else {
$self->writeResponse($result, $context);
}
return $context->response;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/InvokeSettings.php *
* *
* hprose InvokeSettings class for php 5.3+ *
* *
* LastModified: Jul 11, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class InvokeSettings {
public $settings;
public function __construct(array $settings = array()) {
if ($settings !== null) {
$this->settings = $settings;
}
else {
$this->settings = array();
}
}
public function __set($name, $value) {
$this->settings[$name] = $value;
}
public function __get($name) {
return $this->settings[$name];
}
public function __isset($name) {
return isset($this->settings[$name]);
}
public function __unset($name) {
unset($this->settings[$name]);
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Promise.php *
* *
* Promise for php 5.3+ *
* *
* LastModified: Jul 23, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class Promise extends Future {
public function __construct($executor = null) {
parent::__construct();
if (is_callable($executor)) {
$self = $this;
call_user_func($executor,
function($value) use ($self) {
$self->resolve($value);
},
function($reason) use ($self) {
$self->reject($reason);
}
);
}
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Promise/functions.php *
* *
* some helper functions for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Promise;
use Hprose\Future;
function isPromise($obj) {
return $obj instanceof Future;
}
function error($e) {
return Future\error($e);
}
function value($v) {
return Future\value($v);
}
function resolve($value) {
return value($value);
}
function reject($reason) {
return error($reason);
}
function sync($computation) {
return Future\sync($computation);
}
function promise($executor) {
return new Promise($executor);
}
function all($array) {
return Future\all($array);
}
function join() {
return all(func_get_args());
}
function race($array) {
return Future\race($array);
}
function any($array) {
return Future\any($array);
}
function settle($array) {
return Future\settle($array);
}
function run($handler/*, arg1, arg2, ... */) {
$args = array_slice(func_get_args(), 1);
return all($args)->then(
function($args) use ($handler) {
return call_user_func_array($handler, $args);
}
);
}
function wrap($handler) {
return Future\wrap($handler);
}
function each($array, $callback) {
return Future\each($array, $callback);
}
function every($array, $callback) {
return Future\every($array, $callback);
}
function some($array, $callback) {
return Future\some($array, $callback);
}
function filter($array, $callback, $preserveKeys = false) {
return Future\filter($array, $callback, $preserveKeys);
}
function map($array, $callback) {
return Future\map($array, $callback);
}
function reduce($array, $callback, $initial = NULL) {
return Future\reduce($array, $callback, $initial);
}
function search($array, $searchElement, $strict = false) {
return Future\search($array, $searchElement, $strict);
}
function includes($array, $searchElement, $strict = false) {
return Future\includes($array, $searchElement, $strict);
}
function diff(/*$array1, $array2, ...*/) {
return call_user_func_array("\\Hprose\\Future\\diff", func_get_args());
}
function udiff(/*$array1, $array2, $...*/) {
return call_user_func_array("\\Hprose\\Future\\udiff", func_get_args());
}
function toPromise($obj) {
return Future\toPromise($obj);
}
function arrayToPromise(array $array) {
return Future\arrayToPromise($array);
}
function objectToPromise($obj) {
return Future\objectToPromise($obj);
}
if (class_exists("\\Generator")) {
function co(/*$generator, arg1, arg2...*/) {
return call_user_func_array("\\Hprose\\Future\\co", func_get_args());
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Proxy.php *
* *
* hprose Proxy class for php 5.3+ *
* *
* LastModified: Jul 24, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use Closure;
class Proxy {
private $client;
private $namespace;
public function __construct(Client $client, $namespace = '') {
$this->client = $client;
$this->namespace = $namespace;
}
public function __call($name, array $args) {
$name = $this->namespace . $name;
$n = count($args);
if ($n > 0) {
if ($args[$n - 1] instanceof Closure) {
$callback = array_pop($args);
return $this->client->invoke($name, $args, $callback);
}
else if ($args[$n - 1] instanceof InvokeSettings) {
if (($n > 1) && ($args[$n - 2] instanceof Closure)) {
$settings = array_pop($args);
$callback = array_pop($args);
return $this->client->invoke($name, $args, $callback, $settings);
}
$settings = array_pop($args);
return $this->client->invoke($name, $args, $settings);
}
else if (($n > 1) && is_array($args[$n - 1]) &&
($args[$n - 2] instanceof Closure)) {
$settings = new InvokeSettings(array_pop($args));
$callback = array_pop($args);
return $this->client->invoke($name, $args, $callback, $settings);
}
}
return $this->client->invoke($name, $args);
}
public function __get($name) {
return new Proxy($this->client, $this->namespace . $name . '_');
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/RawReader.php *
* *
* hprose raw reader class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use Exception;
class RawReader {
public $stream;
public function __construct(BytesIO $stream) {
$this->stream = $stream;
}
public function unexpectedTag($tag, $expectTags = '') {
if ($tag && $expectTags) {
return new Exception("Tag '" . $expectTags . "' expected, but '" . $tag . "' found in stream");
}
else if ($tag) {
return new Exception("Unexpected serialize tag '" . $tag . "' in stream");
}
else {
return new Exception('No byte found in stream');
}
}
public function readRaw() {
$ostream = new BytesIO();
$this->privateReadRaw($ostream);
return $ostream;
}
private function privateReadRaw(BytesIO $ostream, $tag = '') {
if ($tag == '') {
$tag = $this->stream->getc();
}
$ostream->write($tag);
switch ($tag) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case Tags::TagNull:
case Tags::TagEmpty:
case Tags::TagTrue:
case Tags::TagFalse:
case Tags::TagNaN:
break;
case Tags::TagInfinity:
$ostream->write($this->stream->getc());
break;
case Tags::TagInteger:
case Tags::TagLong:
case Tags::TagDouble:
case Tags::TagRef:
$this->readNumberRaw($ostream);
break;
case Tags::TagDate:
case Tags::TagTime:
$this->readDateTimeRaw($ostream);
break;
case Tags::TagUTF8Char:
$this->readUTF8CharRaw($ostream);
break;
case Tags::TagBytes:
$this->readBytesRaw($ostream);
break;
case Tags::TagString:
$this->readStringRaw($ostream);
break;
case Tags::TagGuid:
$this->readGuidRaw($ostream);
break;
case Tags::TagList:
case Tags::TagMap:
case Tags::TagObject:
$this->readComplexRaw($ostream);
break;
case Tags::TagClass:
$this->readComplexRaw($ostream);
$this->privateReadRaw($ostream);
break;
case Tags::TagError:
$this->privateReadRaw($ostream);
break;
default: throw $this->unexpectedTag($tag);
}
}
private function readNumberRaw(BytesIO $ostream) {
$s = $this->stream->readuntil(Tags::TagSemicolon) .
Tags::TagSemicolon;
$ostream->write($s);
}
private function readDateTimeRaw(BytesIO $ostream) {
$s = '';
do {
$tag = $this->stream->getc();
$s .= $tag;
} while ($tag != Tags::TagSemicolon &&
$tag != Tags::TagUTC);
$ostream->write($s);
}
private function readUTF8CharRaw(BytesIO $ostream) {
$ostream->write($this->stream->readString(1));
}
private function readBytesRaw(BytesIO $ostream) {
$len = $this->stream->readuntil(Tags::TagQuote);
$s = $len . Tags::TagQuote . $this->stream->read((int)$len) . Tags::TagQuote;
$this->stream->skip(1);
$ostream->write($s);
}
private function readStringRaw(BytesIO $ostream) {
$len = $this->stream->readuntil(Tags::TagQuote);
$s = $len . Tags::TagQuote . $this->stream->readString((int)$len) . Tags::TagQuote;
$this->stream->skip(1);
$ostream->write($s);
}
private function readGuidRaw(BytesIO $ostream) {
$ostream->write($this->stream->read(38));
}
private function readComplexRaw(BytesIO $ostream) {
$s = $this->stream->readuntil(Tags::TagOpenbrace) .
Tags::TagOpenbrace;
$ostream->write($s);
while (($tag = $this->stream->getc()) != Tags::TagClosebrace) {
$this->privateReadRaw($ostream, $tag);
}
$ostream->write($tag);
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/ReaderRefer.php *
* *
* hprose reader reference interface for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
interface ReaderRefer {
public function set($val);
public function read($index);
public function reset();
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/RealReaderRefer.php *
* *
* hprose RealReaderRefer class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class RealReaderRefer implements ReaderRefer {
private $ref;
public function __construct() {
$this->reset();
}
public function set($val) {
$this->ref[] = $val;
}
public function read($index) {
return $this->ref[$index];
}
public function reset() {
$this->ref = array();
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/RealWriterRefer.php *
* *
* hprose RealWriterRefer class for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use SplObjectStorage;
class RealWriterRefer implements WriterRefer {
private $oref;
private $sref = array();
private $refcount = 0;
public function __construct() {
$this->oref = new SplObjectStorage();
}
private function writeRef(BytesIO $stream, $index) {
$stream->write(Tags::TagRef . $index . Tags::TagSemicolon);
return true;
}
public function set($val) {
if (is_string($val)) {
$this->sref[$val] = $this->refcount;
}
elseif (is_object($val)) {
$this->oref->attach($val, $this->refcount);
}
$this->refcount++;
}
public function write(BytesIO $stream, $val) {
if (is_string($val) && isset($this->sref[$val])) {
return $this->writeRef($stream, $this->sref[$val]);
}
elseif (is_object($val) && isset($this->oref[$val])) {
return $this->writeRef($stream, $this->oref[$val]);
}
return false;
}
public function reset() {
$this->oref = new \SplObjectStorage();
$this->sref = array();
$this->refcount = 0;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/ResultMode.php *
* *
* hprose ResultMode enum for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class ResultMode {
const Normal = 0;
const Serialized = 1;
const Raw = 2;
const RawWithEndTag = 3;
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Socket/Client.php *
* *
* hprose socket client class for php 5.3+ *
* *
* LastModified: Jul 12, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Socket;
use stdClass;
use Exception;
class Client extends \Hprose\Client {
private $hdtrans;
private $fdtrans;
public $fullDuplex = false;
public $readBuffer = 8192;
public $writeBuffer = 8192;
public $maxPoolSize = 10;
public $options = null;
public function __construct($uris = null, $async = true) {
parent::__construct($uris, $async);
$this->hdtrans = new HalfDuplexTransporter($this, $async);
$this->fdtrans = new FullDuplexTransporter($this, $async);
}
public function __destruct() {
try {
$this->loop();
}
catch (\Exception $e) {
}
}
public function isFullDuplex() {
return $this->fullDuplex;
}
public function setFullDuplex($fullDuplex) {
$this->fullDuplex = $fullDuplex;
}
public function getReadBuffer() {
return $this->readBuffer;
}
public function setReadBuffer($size) {
$this->readBuffer = $size;
}
public function getWriteBuffer() {
return $this->writeBuffer;
}
public function setWriteBuffer($size) {
$this->writeBuffer = $size;
}
public function getMaxPoolSize() {
return $this->maxPoolSize;
}
public function setMaxPoolSize($maxPoolSize) {
if ($maxPoolSize < 1) throw new Exception("maxPoolSize must be great than 0");
$this->maxPoolSize = $maxPoolSize;
}
protected function sendAndReceive($request, stdClass $context) {
if ($this->fullDuplex) {
return $this->fdtrans->sendAndReceive($request, $context);
}
return $this->hdtrans->sendAndReceive($request, $context);
}
public function getOptions() {
return $this->options;
}
public function setOptions(array $options) {
$this->options = $options;
}
public function set($key, $value) {
$this->options[$key] = $value;
return $this;
}
public function loop() {
if ($this->fullDuplex) {
$this->fdtrans->loop();
}
else {
$this->hdtrans->loop();
}
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Socket/DataBuffer.php *
* *
* hprose socket DataBuffer class for php 5.3+ *
* *
* LastModified: Jul 12, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Socket;
class DataBuffer {
public $index;
public $buffer;
public $length;
public $id;
public function __construct($index, $buffer, $length, $id = null) {
$this->index = $index;
$this->buffer = $buffer;
$this->length = $length;
$this->id = $id;
}
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Socket/FullDuplexTransporter.php *
* *
* hprose socket FullDuplexTransporter class for php 5.3+ *
* *
* LastModified: Jul 12, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Socket;
class FullDuplexTransporter extends Transporter {
private $id = 0;
private function getId() {
return $this->id++;
}
protected function appendHeader($request, $id = null) {
if ($id === null) {
$id = $this->getId();
}
return pack("NN", strlen($request) | 0x80000000, $id) . $request;
}
protected function createRequest($index, $request) {
$id = $this->getId();
$buffer = $this->appendHeader($request, $id);
return new DataBuffer($index, $buffer, strlen($buffer), $id);
}
protected function afterWrite($request, $stream, $o) {
$response = new DataBuffer($request->index, '', 0, $request->id);
$stream_id = (integer)$stream;
unset($o->requests[$stream_id]);
if (empty($o->queue[$stream_id])) {
$o->queue[$stream_id] = array();
$o->readpool[] = $stream;
}
$o->queue[$stream_id][$request->id] = $response;
}
protected function asyncReadError($o, $stream, $index) {
$stream_id = (integer)$stream;
foreach ($o->queue[$stream_id] as $response) {
$index = $response->index;
$o->results[$index]->reject($this->getLastError('response read error'));
$this->free($o, $index);
}
unset($o->queue[$stream_id]);
unset($o->responses[$stream_id]);
fclose($stream);
$this->removeStream($stream, $o->readpool);
$this->removeStream($stream, $o->writepool);
}
private function getHeaderInfo($stream) {
$header = $this->readHeader($stream, 8);
if ($header === false) return false;
list(, $length, $id) = unpack('N*', $header);
$length &= 0x7FFFFFFF;
return array($length, $id);
}
protected function getBodyLength($stream) {
$headerInfo = $this->getHeaderInfo($stream);
if ($headerInfo === false) return false;
return $headerInfo[0];
}
protected function getResponse($stream, $o) {
$stream_id = (integer)$stream;
if (isset($o->responses[$stream_id])) {
$response = $o->responses[$stream_id];
}
else {
$headerInfo = $this->getHeaderInfo($stream);
if ($headerInfo === false) return false;
$id = $headerInfo[1];
$response = $o->queue[$stream_id][$id];
$response->length = $headerInfo[0];
$o->responses[$stream_id] = $response;
}
return $response;
}
protected function afterRead($stream, $o, $response) {
$stream_id = (integer)$stream;
unset($o->queue[$stream_id][$response->id]);
if (empty($o->queue[$stream_id])) {
$this->removeStream($stream, $o->readpool);
}
}
}
\ No newline at end of file
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Socket/HalfDuplexTransporter.php *
* *
* hprose socket HalfDuplexTransporter class for php 5.3+ *
* *
* LastModified: Jul 12, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose\Socket;
class HalfDuplexTransporter extends Transporter {
protected function appendHeader($request) {
return pack("N", strlen($request)) . $request;
}
protected function createRequest($index, $request) {
$buffer = $this->appendHeader($request);
return new DataBuffer($index, $buffer, strlen($buffer));
}
protected function afterWrite($request, $stream, $o) {
$stream_id = (integer)$stream;
$o->responses[$stream_id] = new DataBuffer($request->index, '', 0);
$o->readpool[] = $stream;
unset($o->requests[$stream_id]);
$this->removeStream($stream, $o->writepool);
}
protected function asyncReadError($o, $stream, $index) {
$o->results[$index]->reject($this->getLastError('response read error'));
$this->free($o, $index);
unset($o->responses[(integer)$stream]);
fclose($stream);
$this->removeStream($stream, $o->readpool);
}
protected function getBodyLength($stream) {
$header = $this->readHeader($stream, 4);
if ($header === false) return false;
list(, $length) = unpack('N', $header);
return $length;
}
protected function getResponse($stream, $o) {
$stream_id = (integer)$stream;
$response = $o->responses[$stream_id];
if ($response->length === 0) {
$length = $this->getBodyLength($stream);
if ($length === false) return false;
$response->length = $length;
}
return $response;
}
protected function afterRead($stream, $o, $response) {
if ($o->current < $o->count) {
$o->writepool[] = $stream;
}
$this->removeStream($stream, $o->readpool);
}
}
\ No newline at end of file
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/Tags.php *
* *
* hprose tags enum for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
class Tags {
/* Serialize Tags */
const TagInteger = 'i';
const TagLong = 'l';
const TagDouble = 'd';
const TagNull = 'n';
const TagEmpty = 'e';
const TagTrue = 't';
const TagFalse = 'f';
const TagNaN = 'N';
const TagInfinity = 'I';
const TagDate = 'D';
const TagTime = 'T';
const TagUTC = 'Z';
const TagBytes = 'b';
const TagUTF8Char = 'u';
const TagString = 's';
const TagGuid = 'g';
const TagList = 'a';
const TagMap = 'm';
const TagClass = 'c';
const TagObject = 'o';
const TagRef = 'r';
/* Serialize Marks */
const TagPos = '+';
const TagNeg = '-';
const TagSemicolon = ';';
const TagOpenbrace = '{';
const TagClosebrace = '}';
const TagQuote = '"';
const TagPoint = '.';
/* Protocol Tags */
const TagFunctions = 'F';
const TagCall = 'C';
const TagResult = 'R';
const TagArgument = 'A';
const TagError = 'E';
const TagEnd = 'z';
}
<?php
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/TimeoutException.php *
* *
* hprose TimeoutException for php 5.3+ *
* *
* LastModified: Jul 11, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose;
use Exception;
class TimeoutException extends Exception {}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment