/** * Parse Payload Data * * @param string $payload * * @throws ParserException * * @return array */ public function parse($payload) { if (function_exists('MongoDB\\BSON\\toPHP') && !function_exists('bson_decode')) { require_once __DIR__ . '/BSONPolyfill.php'; //@codeCoverageIgnore } elseif (!(function_exists('bson_decode') || function_exists('MongoDB\\BSON\\toPHP'))) { throw new ParserException('Failed To Parse BSON - Supporting Library Not Available'); // @codeCoverageIgnore } if ($payload) { $prevHandler = set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { throw new \Exception($errstr); // @codeCoverageIgnore }); try { $bson = bson_decode(trim($payload, " \t\n\r\v")); // Don't trim \0, as it has valid meaning in BSON if (!$bson) { throw new \Exception('Unknown error'); // @codeCoverageIgnore } } catch (\Exception $e) { set_error_handler($prevHandler); throw new ParserException('Failed To Parse BSON - ' . $e->getMessage()); } set_error_handler($prevHandler); return $bson; } return []; }
function testGetBSONDocument() { $d = new Dummy(); $d->dum = 'dum-dum'; $d->username = '******'; $doc = $d->getBSONDocument(); $this->assertTrue(array_key_exists('username', bson_decode($doc))); $this->assertTrue(array_key_exists('dum', bson_decode($doc))); }
protected function read_response() { // Read the header. $data = $this->read_n(self::LEN_PACK_SIZE); $len = unpack(self::LEN_PACK_FORMAT, $data)[1]; $header = $data . $this->read_n($len - self::LEN_PACK_SIZE); // Read the body. $data = $this->read_n(self::LEN_PACK_SIZE); $len = unpack(self::LEN_PACK_FORMAT, $data)[1]; $body = $data . $this->read_n($len - self::LEN_PACK_SIZE); // Decode and return. return new GoRpcResponse(bson_decode($header), bson_decode($body)); }
/** * Parse Payload Data * * @param string $payload * * @return array * * @throws ParserException */ public function parse($payload) { if (function_exists('bson_decode')) { if ($payload) { $bson = bson_decode(trim($payload)); if (!$bson) { throw new ParserException('Failed To Parse BSON'); } return $bson; } return array(); } throw new ParserException('Failed To Parse BSON - Supporting Library Not Available'); }
protected function readResponse(VTContext $ctx) { // Read the header. $data = $this->readN($ctx, self::LEN_PACK_SIZE); $unpack = unpack(self::LEN_PACK_FORMAT, $data); $len = $unpack[1]; $header = $data . $this->readN($ctx, $len - self::LEN_PACK_SIZE); // Read the body. $data = $this->readN($ctx, self::LEN_PACK_SIZE); $unpack = unpack(self::LEN_PACK_FORMAT, $data); $len = $unpack[1]; $body = $data . $this->readN($ctx, $len - self::LEN_PACK_SIZE); // Decode and return. return new GoRpcResponse(bson_decode($header), bson_decode($body)); }
function receive() { $this->rbuf = ''; $ret = socket_recv($this->socket, $this->rbuf, 4, MSG_PEEK | MSG_WAITALL); if (!$ret) { throw new Exception("socket read error"); } $msg_len = unpack('N', strrev($this->rbuf)); $this->rbuf = ''; echo "receiving message size = {$msg_len['1']}"; $ret = socket_recv($this->socket, $this->rbuf, $msg_len[1], MSG_WAITALL); if (!$ret) { throw new Exception("socket read error"); } return bson_decode($this->rbuf); }
function decode($arg) { foreach ($arg as $num => $param) { switch ($param) { case '-t': case '--type': $type = strtolower($arg[$num + 1]); break; case '-s': case '--source-file': $source = $arg[$num + 1]; break; } } if (isset($source)) { $src = file_get_contents($source); } if ($type == 'json') { $res = json_decode($src); } if ($type == 'url') { $res = urldecode($src); } if ($type == 'base64') { $res = base64_decode($src); } if ($type == 'html') { $res = htmlspecialchars_decode($src); } if ($type == 'bson') { $res = bson_decode($src); } if ($type == 'session') { $res = session_decode($src); } if ($type == 'utf8') { $res = utf8_decode($src); } if ($type == 'xmlrpc') { $res = xmlrpc_decode($src); } return $res; }
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(); }
/** * @param string $data * @param string $format * @param array $context * * @return mixed */ public function decode($data, $format, array $context = array()) { return bson_decode($data); }
/** * Finds one object in collection * @param array Hash of properties (offset, opts, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog) * @param mixed Callback called when response received * @param string Optional. Distribution key * @return void */ public function findOne($p, $callback, $key = '') { if (isset($p['cachekey'])) { $db = $this; $this->cache->get($p['cachekey'], function ($r) use($db, $p, $callback, $key) { if ($r->result !== NULL) { call_user_func($callback, bson_decode($r->result)); } else { unset($p['cachekey']); $db->findOne($p, $callback, $key); } }); return; } if (!isset($p['offset'])) { $p['offset'] = 0; } if (!isset($p['opts'])) { $p['opts'] = 0; } if (!isset($p['where'])) { $p['where'] = array(); } if (strpos($p['col'], '.') === false) { $p['col'] = $this->dbname . '.' . $p['col']; } if (isset($p['fields']) && is_string($p['fields'])) { $e = explode(',', $p['fields']); $p['fields'] = array(); foreach ($e as &$f) { $p['fields'][$f] = 1; } } if (is_string($p['where'])) { $p['where'] = new MongoCode($p['where']); } $o = array(); $s = false; foreach ($p as $k => $v) { if ($k === 'sort' || $k === 'hint' || $k === 'explain' || $k === 'snapshot') { if (!$s) { $s = true; } if ($k === 'sort') { $o['orderby'] = $v; } elseif ($k === 'parse_oplog') { } else { $o[$k] = $v; } } } if ($s) { $o['query'] = $p['where']; } else { $o = $p['where']; } $reqId = $this->request($key, self::OP_QUERY, pack('V', $p['opts']) . $p['col'] . "" . pack('VV', $p['offset'], -1) . bson_encode($o) . (isset($p['fields']) ? bson_encode($p['fields']) : ''), true); $this->requests[$reqId] = array($p['col'], $callback, true); }
/** * @dataProvider data */ public function testDecode($encoded, $decoded) { $this->assertEquals($decoded, bson_decode($encoded)); }
/** * deserialize -- by default with BSON * * @param string $string * * @return object */ function deserialize($string) { return bson_decode($string); }
/** * Finds one object in collection * @param array $p Hash of properties (offset, opts, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog) * @param callable $cb Callback called when response received * @callback $cb ( ) * @return void */ public function findOne($p, $cb) { if (isset($p['cachekey'])) { $db = $this; $this->cache->get($p['cachekey'], function ($r) use($db, $p, $cb) { if ($r->result !== null) { $cb(bson_decode($r->result)); } else { unset($p['cachekey']); $db->findOne($p, $cb); } }); return; } if (!isset($p['where'])) { $p['where'] = []; } $this->_params($p); $o = []; $s = false; foreach ($p as $k => $v) { if ($k === 'sort' || $k === 'hint' || $k === 'explain' || $k === 'snapshot') { if (!$s) { $s = true; } if ($k === 'sort') { $o['orderby'] = $v; } elseif ($k === 'parse_oplog') { } elseif ($k === 'rp') { $o['$readPreference'] = $v; } else { $o[$k] = $v; } } } if (empty($o['orderby'])) { unset($o['orderby']); } if ($s) { $o['query'] = $p['where']; } else { $o = $p['where']; } $cb = CallbackWrapper::wrap($cb); if ($this->safeMode) { static::safeModeEnc($o); } try { $this->request(self::OP_QUERY, pack('V', $p['opts']) . $p['col'] . "" . pack('VV', $p['offset'], -1) . bson_encode($o) . (isset($p['fields']) ? bson_encode($p['fields']) : ''), true, null, function ($conn, $reqId = null) use($p, $cb) { if (!$conn) { !$cb || $cb(['$err' => 'Connection error.']); return; } $conn->requests[$reqId] = [$p['col'], $cb, true]; }); } catch (\MongoException $e) { Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString()); if ($cb !== null) { $cb(['$err' => $e->getMessage(), '$query' => $o, '$fields' => isset($p['fields']) ? $p['fields'] : null]); } } }
/** * @iterations 10000 */ public function complexNestedDecode() { $doc = bson_decode($this->complexNestedBson); }
public function testEncodeDate() { $timestamp = strtotime('2014-03-01 14:30:33 UTC', 123120); $input = new MongoDate($timestamp); $bson = bson_encode(['date' => $input]); $out = bson_decode($bson)['date']; $this->assertEquals($input, $out); $this->assertEquals('1300000009646174650028bb0d7e4401000000', bin2hex($bson)); $input = new MongoDate(-$timestamp, 123120); $bson = bson_encode(['date' => $input]); $out = bson_decode($bson)['date']; $this->assertEquals($input, $out); $this->assertEquals('130000000964617465005345f281bbfeffff00', bin2hex($bson)); }
public function convertStringToArray($strData) { $this->checkForBson(); /** @noinspection PhpUndefinedFunctionInspection */ return bson_decode($strData); }
/** * Called when new data received * @param string New data * @return void */ public function stdin($buf) { $this->buf .= $buf; start: $l = strlen($this->buf); if ($l < 16) { // we have not enough data yet return; } $h = unpack('Vlen/VreqId/VresponseTo/VopCode', binarySubstr($this->buf, 0, 16)); $plen = (int) $h['len']; if ($plen > $l) { // we have not enough data yet return; } if ($h['opCode'] === MongoClient::OP_REPLY) { $r = unpack('Vflag/VcursorID1/VcursorID2/Voffset/Vlength', binarySubstr($this->buf, 16, 20)); //Daemon::log(array($r,$h)); $r['cursorId'] = binarySubstr($this->buf, 20, 8); $id = (int) $h['responseTo']; $flagBits = str_pad(strrev(decbin($r['flag'])), 8, '0', STR_PAD_LEFT); $cur = $r['cursorId'] !== "" ? 'c' . $r['cursorId'] : 'r' . $h['responseTo']; if (isset($this->pool->requests[$id][2]) && $this->pool->requests[$id][2] === false && !isset($this->pool->cursors[$cur])) { $this->pool->cursors[$cur] = new MongoClientCursor($cur, $this->pool->requests[$id][0], $this); $this->pool->cursors[$cur]->failure = $flagBits[1] == '1'; $this->pool->cursors[$cur]->await = $flagBits[3] == '1'; $this->pool->cursors[$cur]->callback = $this->pool->requests[$id][1]; $this->pool->cursors[$cur]->parseOplog = isset($this->pool->requests[$id][3]) && $this->pool->requests[$id][3]; $this->pool->cursors[$cur]->tailable = isset($this->pool->requests[$id][4]) && $this->pool->requests[$id][4]; } //Daemon::log(array(Debug::exportBytes($cur),get_Class($this->pool->cursors[$cur]))); if (isset($this->pool->cursors[$cur]) && ($r['length'] === 0 || binarySubstr($cur, 0, 1) === 'r')) { if ($this->pool->cursors[$cur]->tailable) { if ($this->pool->cursors[$cur]->finished = $flagBits[0] == '1') { $this->pool->cursors[$cur]->destroy(); } } else { $this->pool->cursors[$cur]->finished = true; } } $p = 36; while ($p < $plen) { $dl = unpack('Vlen', binarySubstr($this->buf, $p, 4)); $doc = bson_decode(binarySubstr($this->buf, $p, $dl['len'])); if (isset($this->pool->cursors[$cur]) && @$this->pool->cursors[$cur]->parseOplog && isset($doc['ts'])) { $tsdata = unpack('Vsec/Vinc', binarySubstr($this->buf, $p + 1 + 4 + 3, 8)); $doc['ts'] = $tsdata['sec'] . ' ' . $tsdata['inc']; } $this->pool->cursors[$cur]->items[] = $doc; $p += $dl['len']; } $this->setFree(true); if (isset($this->pool->requests[$id][2]) && $this->pool->requests[$id][2] && $this->pool->requests[$id][1]) { call_user_func($this->pool->requests[$id][1], isset($this->pool->cursors[$cur]->items[0]) ? $this->pool->cursors[$cur]->items[0] : false); if (isset($this->pool->cursors[$cur])) { if ($this->pool->cursors[$cur] instanceof MongoClientCursor) { $this->pool->cursors[$cur]->destroy(); } else { unset($this->pool->cursors[$cur]); } } } elseif (isset($this->pool->cursors[$cur])) { call_user_func($this->pool->cursors[$cur]->callback, $this->pool->cursors[$cur]); } unset($this->pool->requests[$id]); } $this->buf = binarySubstr($this->buf, $plen); goto start; }
public function stdin($buf) { $this->buf .= $buf; start: $l = strlen($this->buf); if ($l < 16) { return; } // we have not enough data yet $h = unpack('Vlen/VreqId/VresponseTo/VopCode', binarySubstr($this->buf, 0, 16)); $plen = (int) $h['len']; if ($plen > $l) { return; } // we have not enough data yet if ($h['opCode'] === MongoClient::OP_REPLY) { $r = unpack('Vflag/VcursorID1/VcursorID2/Voffset/Vlength', binarySubstr($this->buf, 16, 20)); $r['cursorId'] = binarySubstr($this->buf, 20, 8); $id = (int) $h['responseTo']; $cur = $r['cursorId'] !== "" ? 'c' . $r['cursorId'] : 'r' . $h['responseTo']; if (isset($this->appInstance->requests[$id][2]) && $this->appInstance->requests[$id][2] === FALSE && !isset($this->appInstance->cursors[$cur])) { $this->appInstance->cursors[$cur] = new MongoClientCursor($cur, $this->appInstance->requests[$id][0], $this); $this->appInstance->cursors[$cur]->callback = $this->appInstance->requests[$id][1]; $this->appInstance->cursors[$cur]->parseOplog = isset($this->appInstance->requests[$id][3]) && $this->appInstance->requests[$id][3]; } if (isset($this->appInstance->cursors[$cur]) && ($r['length'] === 0 || binarySubstr($cur, 0, 1) === 'r')) { $this->appInstance->cursors[$cur]->finished = TRUE; } $p = 36; while ($p < $plen) { $dl = unpack('Vlen', binarySubstr($this->buf, $p, 4)); $doc = bson_decode(binarySubstr($this->buf, $p, $dl['len'])); if (isset($this->appInstance->cursors[$cur]) && $this->appInstance->cursors[$cur]->parseOplog && isset($doc['ts'])) { $tsdata = unpack('Vsec/Vinc', binarySubstr($this->buf, $p + 1 + 4 + 3, 8)); $doc['ts'] = $tsdata['sec'] . ' ' . $tsdata['inc']; } $this->appInstance->cursors[$cur]->items[] = $doc; $p += $dl['len']; } $this->busy = FALSE; if (isset($this->appInstance->requests[$id][2]) && $this->appInstance->requests[$id][2]) { call_user_func($this->appInstance->requests[$id][1], isset($this->appInstance->cursors[$cur]->items[0]) ? $this->appInstance->cursors[$cur]->items[0] : FALSE); if (isset($this->appInstance->cursors[$cur]) && $this->appInstance->cursors[$cur] instanceof MongoClientCursor) { $this->appInstance->cursors[$cur]->destroy(); } } elseif (isset($this->appInstance->cursors[$cur])) { call_user_func($this->appInstance->cursors[$cur]->callback, $this->appInstance->cursors[$cur]); } unset($this->appInstance->requests[$id]); } $this->buf = binarySubstr($this->buf, $plen); goto start; }
/** * Called when new data received * @return void */ public function onRead() { start: if ($this->freed) { return; } if ($this->state === self::STATE_ROOT) { if (false === ($hdr = $this->readExact(16))) { return; // we do not have a header } $this->hdr = unpack('Vlen/VreqId/VresponseTo/VopCode', $hdr); $this->hdr['plen'] = $this->hdr['len'] - 16; $this->setWatermark($this->hdr['plen'], $this->hdr['plen']); $this->state = self::STATE_PACKET; } if ($this->state === self::STATE_PACKET) { if (false === ($pct = $this->readExact($this->hdr['plen']))) { return; //we do not have a whole packet } $this->state = self::STATE_ROOT; $this->setWatermark(16, 0xffffff); if ($this->hdr['opCode'] === Pool::OP_REPLY) { $r = unpack('Vflag/VcursorID1/VcursorID2/Voffset/Vlength', binarySubstr($pct, 0, 20)); $r['cursorId'] = binarySubstr($pct, 4, 8); $id = (int) $this->hdr['responseTo']; if (isset($this->requests[$id])) { $req = $this->requests[$id]; if (sizeof($req) === 1) { // get more $r['cursorId'] = $req[0]; } } else { $req = false; } $flagBits = str_pad(strrev(decbin($r['flag'])), 8, '0', STR_PAD_LEFT); $curId = $r['cursorId'] !== "" ? 'c' . $r['cursorId'] : 'r' . $this->hdr['responseTo']; if ($req && isset($req[2]) && $req[2] === false && !isset($this->cursors[$curId])) { $cur = new Cursor($curId, $req[0], $this); $this->cursors[$curId] = $cur; $cur->failure = $flagBits[1] === '1'; $cur->await = $flagBits[3] === '1'; $cur->callback = $req[1]; $cur->parseOplog = isset($req[3]) && $req[3]; $cur->tailable = isset($req[4]) && $req[4]; } else { $cur = isset($this->cursors[$curId]) ? $this->cursors[$curId] : false; } if ($cur && ($r['length'] === 0 || binarySubstr($curId, 0, 1) === 'r')) { if ($cur->tailable) { if ($cur->finished = $flagBits[0] === '1') { $cur->destroy(); } } else { $cur->finished = true; } } $p = 20; $items = []; while ($p < $this->hdr['plen']) { $dl = unpack('Vlen', binarySubstr($pct, $p, 4)); $doc = bson_decode(binarySubstr($pct, $p, $dl['len'])); if ($cur) { if ($cur->parseOplog && isset($doc['ts'])) { $tsdata = unpack('Vsec/Vinc', binarySubstr($pct, $p + 8, 8)); $doc['ts'] = $tsdata['sec'] . ' ' . $tsdata['inc']; } $cur->items[] = $doc; ++$cur->counter; } else { $items[] = $doc; } $p += $dl['len']; } $this->setFree(true); if (isset($req[2]) && $req[2] && $req[1]) { call_user_func($req[1], sizeof($items) ? $items[0] : false); if ($cur) { if ($cur instanceof Cursor) { $cur->destroy(); } else { unset($this->cursors[$curId]); } } } elseif ($cur) { call_user_func($cur->callback, $cur); } unset($this->requests[$id]); $req = null; } } goto start; }
try { $idmap = $client->mg_find_one($ctx, 'default', 'idmap', 0, bson_encode(array('snsid' => '100003391571259')), bson_encode('')); echo "[Client] mg_find_one received: \n"; print_r(bson_decode($idmap)); } catch (TMongoMissed $ex) { echo $ex->getMessage(), "\n"; } // mg.count echo "[Client] mg_count received:", $client->mg_count($ctx, 'default', 'idmap', 0, bson_encode(array('uid' => array('$gte' => 1)))), "\n"; echo "[Client] mg_count received:", $client->mg_count($ctx, 'default', 'idmap', 0, bson_encode(array('uid' => array('$gte' => 100000)))), "\n"; // mg.findAll echo "[Client] mg_find_all received: \n"; try { $docs = $client->mg_find_all($ctx, 'default', 'idmap', 0, bson_encode(array('uid' => array('$gte' => 1))), bson_encode(array()), 0, 0, array()); $r = array(); foreach ($docs as $doc) { $r[] = bson_decode($doc); } print_r($r); } catch (TProtocolException $ex) { print_r($ex); } // mg.findAndModify $r = $client->mg_find_and_modify($ctx, 'default', 'idsquence', 0, bson_encode(array('table_name' => 'idMap')), bson_encode(array('$inc' => array('value' => 1))), true, false, true); $val = bson_decode($r); echo "[Client] mg.find_and_modify received: ", $val['value'], "\n"; } $transport->close(); } catch (Exception $tx) { print 'Something went wrong: ' . $tx->getMessage() . "\n"; }
/** * @param $filename * @return array of arrays */ function file_bson($filename) { $ret = []; $file = fopen($filename, 'r'); while (true) { $packedLength = fread($file, 4); if (feof($file)) { break; } $unpacked = unpack('V', $packedLength); $length = array_shift($unpacked); fseek($file, -4, SEEK_CUR); $ret[] = bson_decode(fread($file, $length)); } fclose($file); return $ret; }