/** * Decodes given value into the on-memory instance in accordance with * the predefined codec. * * @param mixed $value value to be decoded. * @return mixed instance which is decoded. */ public function decode($value) { if (function_exists('msgpack_unpack')) { return msgpack_unpack($value); } return unserialize($value); }
public function packData($var, $bool = true, $option = array()) { $option += array('packer' => $this->option['packer']); switch ($option['packer']) { case BoxConstants::ENCODER_JSON: if ($bool == true) { return json_encode($var); } else { return json_decode($var, true); } break; case BoxConstants::ENCODER_MSGPACK: if ($bool == true) { return msgpack_pack($var); } else { return msgpack_unpack($var); } break; case BoxConstants::ENCODER_SERIALIZE: default: if ($bool == true) { return serialize($var); } else { return unserialize($var); } break; } }
/** * Parse Payload Data * * @param string $payload * * @throws ParserException * * @return array */ public function parse($payload) { if (function_exists('msgpack_unpack')) { if ($payload) { $prevHandler = set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { throw new \Exception($errstr); // @codeCoverageIgnore }); try { $msg = msgpack_unpack(trim($payload)); if (!$msg) { throw new \Exception('Unknown error'); // @codeCoverageIgnore } } catch (\Exception $e) { set_error_handler($prevHandler); throw new ParserException('Failed To Parse MSGPack - ' . $e->getMessage()); } set_error_handler($prevHandler); return $msg; } return []; } throw new ParserException('Failed To Parse MSGPack - Supporting Library Not Available'); // @codeCoverageIgnore }
/** * @param string $encoded * @return mixed * @throws \Exception */ public function decode($encoded) { if (function_exists('msgpack_unpack')) { return msgpack_unpack(substr($encoded, 1)); } throw new \Exception('msgpack not installed'); }
public function unserialize($string) { if (!function_exists('msgpack_unpack')) { throw new \Exception('msgpack extension must be installed!'); } return msgpack_unpack($string); }
/** * Function pretreatment * @param $_get * @param $_post * @param $_version * @param $_scope * @param $_interface * @return array */ public static function get() { $_tmp_request = []; //MAKE URL REQUEST //MAKE HTTP HEADER REQUEST $_tmp_header_request = []; $_tmp_http_accept = explode(';', str_replace(' ', '', strtolower($_SERVER['HTTP_ACCEPT']))); $_tmp_request['content-type'] = $_tmp_http_accept[0] == TYPE_JSON || $_tmp_http_accept[0] == TYPE_MSGPACK ? $_tmp_http_accept[0] : TYPE_NULL; if (isset($_tmp_http_accept[1]) && !empty($_tmp_http_accept[1])) { $_tmp = explode('=', $_tmp_http_accept[1]); isset($_tmp[1]) && !empty($_tmp[1]) ? $_tmp_request['version'] = $_tmp[1] : FALSE; } //@todo Ranges //MAKE CONTENT REQUEST $_tmp_request['content'] = file_get_contents('php://input'); switch ($_tmp_request['content-type']) { case TYPE_MSGPACK: $_tmp_request['content'] = msgpack_unpack($_tmp_request['content']); break; case TYPE_JSON: $_tmp_request['content'] = json_decode($_tmp_request['content']); break; case TYPE_NULL: default: $_tmp_request['content'] = NULL; break; } return $_tmp_request; }
public function handleRequest() { $args = func_get_args(); $data = $args[0]; //TODO 简单实用 msgpack //FIXME 数据传输协议依赖swoole 底层组包功能,此处不在检查数据完整 $datastr = substr($data, 4); $params = (object) msgpack_unpack($datastr); if (empty($params->op)) { $params->op = 'main.main'; } //TODO 这里的处理应该完善点 list($ctrl, $method) = explode('.', $params->op); $className = $this->getCtrlNamespace() . '\\' . ucfirst($ctrl) . 'Ctrl'; $ctrl = new $className(); $ctrl->setParams($params); //发送msgpack编码数据,头部为数据长度 $result = $ctrl->{$method}(); if (Ping::$server->debug) { echo "swoole handle request:\n"; echo "\tctrl: {$ctrl} method: {$method}\n"; echo "\tparams:\n\t\t" . json_encode($params) . "\n"; echo "\tresponse:\n\t\t" . json_encode($result) . "\n"; echo "\n\n"; } $rawResult = msgpack_pack($result); $rawResult = pack('N1', strlen($rawResult)); return $rawResult; }
/** * 解包工具 * * @param string $raw * * @return mixed */ public static function unpack($raw, $prefix = true) { if ($prefix) { return msgpack_unpack(substr($raw, 4)); } else { return msgpack_unpack($raw); } }
/** * Unserializes the data * * @param array $data data to be unserialized * * @return array unserialized message */ public function unserialize($data) { $mssg = msgpack_unpack($data); //lets just make UUIDs readable incase we need to debug $mssg[0] = Helper::binToUuid($mssg[0]); $mssg[1] = Helper::binToUuid($mssg[1]); return $mssg; }
public function onData($data, Stream $conn) { $message = msgpack_unpack($data); printf("Request method: %s\n", $message['method']); printf("Request params: %s\n", print_r($message['params'], true)); $result = $this->handler->process($message); $conn->write($result); $conn->end(); }
public function testSend() { $io = m::mock(Io::class); $io->shouldReceive('write')->andReturnUsing(function ($data) { self::assertEquals(array(1, 2, 3), msgpack_unpack($data)); }); $messenger = new MsgpackMessenger($io); $messenger->send(array(1, 2, 3)); }
/** */ public function unpack($data) { ini_set('track_errors', 1); $out = @msgpack_unpack($data); ini_restore('track_errors'); if (!isset($php_errormsg)) { return $out; } throw new Horde_Pack_Exception('Error when unpacking Msgpack data.'); }
public function parse($rawBody, $contentType) { if (!extension_loaded('msgpack')) { throw new BadRequestHttpException('Msgpack is not supported in this app server'); } $unpacked = @msgpack_unpack($rawBody); if ($unpacked === null && $rawBody !== chr(0xc0)) { throw new BadRequestHttpException('Invalid MsgPack data in request body'); } return $unpacked; }
function test($type, $variable, $test = null) { $serialized = msgpack_pack($variable); $unserialized = msgpack_unpack($serialized); var_dump($unserialized); if (!is_bool($test)) { echo $unserialized === $variable ? 'OK' : 'ERROR', PHP_EOL; } else { echo $test || $unserialized == $variable ? 'OK' : 'ERROR', PHP_EOL; } }
function test($type, $variable, $object, $result = null) { $serialized = msgpack_pack($variable); $unserialized = msgpack_unpack($serialized, $object); var_dump($unserialized); if ($result) { echo $unserialized == $result ? 'OK' : 'ERROR', PHP_EOL; } else { echo 'SKIP', PHP_EOL; } }
public function onReceive($server, $fd, $fromId, $data) { /** * @var \Swoole\Server $server */ $tmp = @msgpack_unpack($data); if ($tmp && is_object($tmp)) { $data = $tmp; unset($tmp); if ($data instanceof \stdClass) { if ($data->bind) { # 绑定进程ID $server->bind($fd, $data->id); return; } if ($key = \MyQEE\Server\Register\Client::$host->key) { # 需要解密 $data = \MyQEE\Server\RPC\Server::decryption($data, $key); # 解密失败 if (!$data) { return; } } $eof = \MyQEE\Server\RPC\Server::$EOF; switch ($data->type) { case 'task': case 'taskWait': $rs = Server::$workerTask->onTask($server, $data->id, $data->wid, $data->data, $data->sid); if ($rs !== null || $data->type === 'taskWait') { # 执行 Finish $rsData = new \stdClass(); $rsData->id = $data->id; $rsData->data = $rs; $rsData->wname = $data->wname; if ($key) { # 加密数据 $rsData = \MyQEE\Server\RPC\Server::encrypt($rsData, $key) . $eof; } else { # 格式化数据 $rsData = msgpack_pack($rsData) . $eof; } $server->send($fd, $rsData, $fromId); } break; } } } else { Server::$instance->warn("task server get error msgpack data length: " . strlen($data)); Server::$instance->debug($data); $this->server->close($fd); } }
/** * 反序列化消息 * * @param string $encodedMsg 序列化的消息内容 * @return Message | null */ public static function messageUnserialize($serializedMsg) { $msgArr = msgpack_unpack($serializedMsg); if (!isset($msgArr['__lqcmc'])) { throw new \Exception('Bad message format'); } if ($msgArr['__lqcmc'] == Message::class) { $msg = new Message(); unset($msgArr['__lqcmc']); $msg->initByArray($msgArr); return $msg; } }
function test($type, $var) { echo "================\n" . $type . "\n"; $e = msgpack_pack($var); $d = msgpack_unpack($e); echo "\t" . bin2hex($e) . "\t" . $e . "\n\t"; echo str_replace("\n", "\n\t", var_export($d, true)) . "\n"; if ($var === $d) { echo "PASS\n"; } else { echo "FAIL\n"; } }
/** * Parse Payload Data * * @param string $payload * * @return array * * @throws ParserException */ public function parse($payload) { if (function_exists('msgpack_unpack')) { if ($payload) { $msg = msgpack_unpack(trim($payload)); if (!$msg) { throw new ParserException('Failed To Parse MSGPack'); } return $msg; } return array(); } throw new ParserException('Failed To Parse MSGPack - Supporting Library Not Available'); }
protected function decodeVal($str) { switch ($this->defaultOption['encode']) { case 'json': return json_decode($str, true); break; case 'msgpack': return msgpack_unpack($str); break; case 'serialize': default: return unserialize($str); break; } }
function get_seller_id($access_token) { try { $result = 1; $seller_id = 0; $access_token_data = msgpack_unpack(base64_decode($access_token)); $seller_id = $access_token_data['xid']; $db_result = get_instance()->seller_db_model->is_exists_seller($seller_id); if (!$db_result) { $seller_id = 0; } return $seller_id; } catch (Exception $e) { var_dump($e->getMessage()); } }
function check_token($access_token) { $result = 1; $config = config_get(); $access_token_data = msgpack_unpack(base64_decode($access_token)); if ($access_token_data['data']['service_key'] != $config['service_key']) { $result = 0; } else { if ($access_token_data['data']['version'] != $config['version']) { $result = 0; } else { $result = 1; } } return array('access_token' => $access_token, 'result' => $result); }
public static function deserialize($envelope, $payload) { $event = msgpack_unpack($payload); if (!is_array($event) || count($event) !== 3) { throw new EventException('Expected array of size 3'); } else { if (!is_array($event[0]) || !array_key_exists('message_id', $event[0])) { throw new EventException('Bad header'); } else { if (!is_string($event[1])) { throw new EventException('Bad name'); } } } return new Event($envelope, $event[0], $event[1], $event[2]); }
/** * {@inheritdoc} */ public function unpack($data) { $headerSize = PackUtils::getHeaderSize($data); if (!($header = substr($data, 0, $headerSize))) { throw new Exception('Unable to unpack data.'); } $header = msgpack_unpack($header); if (!is_array($header)) { throw new Exception('Unable to unpack data.'); } $code = $header[IProto::CODE]; $body = substr($data, $headerSize); $body = msgpack_unpack($body); if ($code >= Request::TYPE_ERROR) { throw new Exception($body[IProto::ERROR], $code & Request::TYPE_ERROR - 1); } return new Response($header[IProto::SYNC], $body ? $body[IProto::DATA] : null); }
function bench($value, $n = 1000000) { $benchmark = new Benchmark(); $serialized = serialize($value); $benchmark->add('unserialize', function () use(&$serialized) { unserialize($serialized); }); $jsonEncoded = json_encode($value); $benchmark->add('json_decode', function () use(&$jsonEncoded) { json_decode($jsonEncoded); }); if (function_exists('bin_decode')) { $binEncoded = bin_encode($value); $benchmark->add('bin_decode', function () use(&$binEncoded) { bin_decode($binEncoded); }); } if (function_exists('bson_decode')) { $bsonEncoded = bson_encode($value); $benchmark->add('bson_decode', function () use(&$bsonEncoded) { bson_decode($bsonEncoded); }); } if (function_exists('msgpack_pack')) { $msgPack = msgpack_pack($value); $benchmark->add('msgpack_unpack', function () use(&$msgPack) { msgpack_unpack($msgPack); }); } if (function_exists('igbinary_unserialize')) { $igbinarySerialized = igbinary_serialize($value); $benchmark->add('igbinary_unserialize', function () use(&$igbinarySerialized) { igbinary_unserialize($igbinarySerialized); }); } $benchmark->setCount($n); $benchmark->run(); }
/** * Function pretreatment * @param $_get * @param $_post * @param $_version * @param $_scope * @param $_interface * @return array */ public static function get($_http_method, $_mvc_parameters) { $_request = ['method' => HTTP_GET, 'url' => [], 'api' => ['service' => '', 'method' => '', 'resource' => ''], 'content-type' => TYPE_JSON, 'version' => REQUEST_VERSION_NULL, 'ranges' => ['columns' => NULL, 'order' => NULL, 'limit' => NULL], 'access-token' => NULL, 'client-token' => NULL, 'client-id' => NULL, 'client-ip' => NULL, 'content' => []]; //MAKE URL REQUEST $_request['method'] = constant('HTTP_' . $_http_method); $_request['url'] = $_SERVER['REQUEST_URI']; isset($_mvc_parameters['_service']) && !empty($_mvc_parameters['_service']) ? $_request['api']['service'] = $_mvc_parameters['_service'] : FALSE; isset($_mvc_parameters['_method']) && !empty($_mvc_parameters['_method']) ? $_request['api']['method'] = $_mvc_parameters['_method'] : FALSE; isset($_mvc_parameters['_resource']) && !empty($_mvc_parameters['_resource']) ? $_request['api']['resource'] = $_mvc_parameters['_resource'] : FALSE; //MAKE HTTP HEADER REQUEST $_tmp_header_request = []; $_tmp_http_accept = explode(';', str_replace(' ', '', strtolower($_SERVER['HTTP_ACCEPT']))); $_request['content-type'] = $_tmp_http_accept[0] == TYPE_JSON || $_tmp_http_accept[0] == TYPE_MSGPACK ? $_tmp_http_accept[0] : TYPE_NULL; if (isset($_tmp_http_accept[1]) && !empty($_tmp_http_accept[1])) { $_tmp = explode('=', $_tmp_http_accept[1]); isset($_tmp[1]) && !empty($_tmp[1]) ? $_request['version'] = $_tmp[1] : FALSE; } //@todo Ranges isset($_SERVER['HTTP_ACCESS_TOKEN']) ? $_request['access-token'] = $_SERVER['HTTP_ACCESS_TOKEN'] : FALSE; isset($_SERVER['HTTP_CLIENT_TOKEN']) ? $_request['client-token'] = $_SERVER['HTTP_CLIENT_TOKEN'] : FALSE; isset($_SERVER['HTTP_CLIENT_ID']) ? $_request['client-id'] = $_SERVER['HTTP_CLIENT_ID'] : FALSE; isset($_SERVER['REMOTE_ADDR']) ? $_request['client-ip'] = $_SERVER['REMOTE_ADDR'] : FALSE; //MAKE CONTENT REQUEST $_request['content'] = file_get_contents('php://input'); switch ($_request['content-type']) { case TYPE_MSGPACK: $_request['content'] = msgpack_unpack($_request['content']); break; case TYPE_JSON: $_request['content'] = json_decode($_request['content']); break; case TYPE_NULL: default: $_request['content'] = NULL; break; } return $_request; }
public function tryMsgPackSend($sendmg = null, $sizerp = 1024) { while (true) { $read = null; $write = array($this->cltf); $except = null; $w = stream_select($read, $write, $except, 0, 100 * self::MILLISECONDS); if ($w === false) { // TODO: error throw new RuntimeException('write stream'); } if ($w === 0) { continue; } $this->fwrite($sendmg); break; } while (true) { $read = array($this->cltf); $write = null; $except = null; $r = stream_select($read, $write, $except, 0, 100 * self::MILLISECONDS); if ($r === false) { // TODO: error throw new RuntimeException('read stream'); } if (0 === $r) { continue; } $buf = fread($this->cltf, $sizerp); break; } $this->tryConnClosing(); $buf = msgpack_unpack($buf); $this->cbMsgsReceived($buf); }
public static function unpack($string) { return msgpack_unpack($string); }
<?php $params = (require __DIR__ . '/params.php'); $config = ['name' => 'stat.ink', 'version' => require __DIR__ . '/version.php', 'id' => 'statink', 'language' => 'ja-JP', 'timeZone' => 'Asia/Tokyo', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'components' => ['assetManager' => ['class' => 'app\\components\\web\\AssetManager', 'appendTimestamp' => true, 'bundles' => ['yii\\web\\JqueryAsset' => ['js' => ['jquery.min.js']], 'yii\\bootstrap\\BootstrapAsset' => ['css' => ['css/bootstrap.min.css']], 'yii\\bootstrap\\BootstrapPluginAsset' => ['js' => ['js/bootstrap.min.js']]], 'converter' => ['class' => 'app\\components\\web\\AssetConverter']], 'urlManager' => ['enablePrettyUrl' => true, 'showScriptName' => false, 'enableStrictParsing' => true, 'rules' => ['login' => 'user/login', 'logout' => 'user/logout', 'profile' => 'user/profile', 'register' => 'user/register', 'u/<screen_name:\\w+>/<battle:\\d+>' => 'show/battle', 'u/<screen_name:\\w+>/<battle:\\d+>/edit' => 'show/edit-battle', 'u/<screen_name:\\w+>/stat/<by:[\\w-]+>' => 'show/user-stat-<by>', 'u/<screen_name:\\w+>' => 'show/user', 'fest/<region:\\w+>/<order:\\d+>' => 'fest/view', 'api/v1/<action:[\\w-]+>' => 'api-v1/<action>', 'api/internal/<action:[\\w-]+>' => 'api-internal/<action>', '<action:[\\w-]+>' => 'site/<action>', '<controller:[\\w-]+>/<action:[\\w-]+>' => '<controller>/<action>', 'robots.txt' => 'site/robots', '' => 'site/index']], 'request' => ['class' => 'app\\components\\web\\Request', 'cookieValidationKey' => include __DIR__ . '/cookie-secret.php', 'parsers' => ['application/json' => 'yii\\web\\JsonParser', 'application/x-msgpack' => 'app\\components\\web\\MessagePackParser']], 'response' => ['class' => 'app\\components\\web\\Response', 'formatters' => ['csv' => 'app\\components\\web\\CsvResponseFormatter', 'ikalog-json' => 'app\\components\\web\\IkalogJsonResponseFormatter', 'json' => 'app\\components\\web\\PrettyJsonResponseFormatter']], 'view' => ['renderers' => ['tpl' => ['class' => 'yii\\smarty\\ViewRenderer', 'options' => ['force_compile' => defined('YII_DEBUG') && YII_DEBUG, 'left_delimiter' => '{{', 'right_delimiter' => '}}'], 'pluginDirs' => ['//smarty/'], 'widgets' => ['functions' => ['AdWidget' => 'app\\components\\widgets\\AdWidget', 'SnsWidget' => 'app\\components\\widgets\\SnsWidget']]]]], 'cache' => ['class' => 'yii\\caching\\FileCache', 'serializer' => extension_loaded('msgpack') ? [function ($value) { return @gzencode(msgpack_pack($value), 1, FORCE_GZIP); }, function ($value) { return @msgpack_unpack(gzdecode($value)); }] : null], 'schemaCache' => ['class' => 'yii\\caching\\FileCache', 'cachePath' => '@runtime/schema-cache'], 'errorHandler' => ['errorAction' => 'site/error'], 'log' => ['traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [['class' => 'yii\\log\\FileTarget', 'levels' => ['error', 'warning']]]], 'db' => require __DIR__ . '/db.php', 'user' => ['identityClass' => 'app\\models\\User', 'enableAutoLogin' => false, 'loginUrl' => ['user/login']], 'i18n' => ['translations' => ['app*' => ['class' => 'yii\\i18n\\PhpMessageSource', 'fileMap' => ['app-ability' => 'ability.php', 'app-brand' => 'brand.php', 'app-death' => 'death.php', 'app-fest' => 'fest.php', 'app-gear' => 'gear.php', 'app-gearstat' => 'gearstat.php', 'app-map' => 'map.php', 'app-rank' => 'rank.php', 'app-reltime' => 'reltime.php', 'app-rule' => 'rule.php', 'app-special' => 'special.php', 'app-start' => 'start.php', 'app-subweapon' => 'subweapon.php', 'app-tz' => 'tz.php', 'app-weapon' => 'weapon.php']]]]], 'params' => $params]; if (YII_ENV_DEV) { $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = 'yii\\gii\\Module'; $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = ['class' => 'yii\\debug\\Module', 'allowedIPs' => require __DIR__ . '/debug-ips.php']; } return $config;
function run($client, $request = "") { $errno = 0; $error = ''; $display = 'json'; $b = cy_unpack($request, $this->config); if (!$b || empty($b['raw_header']) || empty($b['raw_len_head']) || $b['raw_len_head'] < 4) { $errno = CYE_PARAM_ERROR; $error = "invalid request."; goto error; } $r = cy_unpack($b['raw_header'], $this->config_head); $r['length'] = $b['raw_len_body']; $_ENV['module'] = $module = $r['module']; $_ENV['id'] = $id = $r['id']; $_ENV['method'] = $method = isset($r['method']) ? $r['method'] : 'get'; $_ENV['display'] = $display = $r['fmt']; $_ENV['version'] = $version = isset($r['version']) ? $r['version'] : 1; $classname = 'CA_Entry_' . $module; if (!method_exists($classname, $method) && !method_exists($classname, '__call')) { $classname .= '_' . $method; $run = isset($_GET['a']) ? $_GET['a'] : 'run'; if (!method_exists($classname, $run)) { $errno = CYE_PARAM_ERROR; $error = "method is not exists {$classname}:{$method}"; goto error; } } switch ($display) { case 'raw': $req = $b['raw_body']; break; case 'json': $req = json_decode($b['raw_body'], true); if (empty($req)) { $errno = json_last_error(); $error = json_last_error_msg(); goto error; } break; case 'mgp': $req = msgpack_unpack($b['raw_body']); $req = ['errno' => 0, 'data' => $data]; break; default: $errno = -1; $error = 'unkown formant'; break; } $eny = new $classname(); $dt = $eny->get($id, $req, $_ENV); unset($eny); response: switch ($display) { case 'raw': $body = $dt; break; case 'json': $body = json_encode($dt); break; case 'mpg': $body = msgpack_pack($dt); break; default: $body = 'unknown format ' . $display; break; } if (empty($body) || !is_string($body)) { return ['errno' => 0, 'error' => 'error response body.']; } $hd = ['raw_len_head' => 0, 'raw_header' => '']; if (isset($b['raw_len_head'])) { $hd['raw_len_head'] = $b['raw_len_head']; } if (isset($b['raw_header'])) { $hd['raw_header'] = $b['raw_header']; } $inputs = array([CY_TYPE_UINT16, $hd['raw_len_head']], [CY_TYPE_STRING, $hd['raw_header']], [CY_TYPE_UINT16, strlen($body)], [CY_TYPE_STRING, $body]); return ['errno' => $errno, 'error' => $error, 'data' => cy_pack($inputs)]; error: $dt = array('errno' => $errno, 'error' => $error); cy_log(CYE_WARNING, "{$client} " . $error); goto response; }