function bench($value, $n = 1000000) { $benchmark = new Benchmark(); $benchmark->add('serialize', function () use(&$value) { serialize($value); }); $benchmark->add('json_encode', function () use(&$value) { json_encode($value); }); if (function_exists('bin_encode')) { $benchmark->add('bin_encode', function () use(&$value) { bin_encode($value); }); } if (function_exists('bson_encode')) { $benchmark->add('bson_encode', function () use(&$value) { bson_encode($value); }); } if (function_exists('msgpack_pack')) { $benchmark->add('msgpack_pack', function () use(&$value) { msgpack_pack($value); }); } if (function_exists('igbinary_serialize')) { $benchmark->add('igbinary_serialize', function () use(&$value) { igbinary_serialize($value); }); } $benchmark->add('var_export', function () use(&$value) { var_export($value, true); }); $benchmark->setCount($n); $benchmark->run(); }
function addProbe($name) { $reflectProbe = new ReflectionClass('Probe'); $probe = $reflectProbe->newInstanceArgs(func_get_args()); if (gettype($name) !== 'string') { $name = $name['name']; } $this->probes->{$name} = $probe; $_this = $this; $probe->on('sample', function ($event) use($_this, $probe) { $sample = $event->getParams(); $sample['probe'] = $probe; $_this->notify('sample', $sample); if (!isset($_this->samples)) { return; } $payload = $sample['payload']; $body = array('provider' => $_this->config['name'], 'module' => $_this->module, 'probe' => $probe->name, 'timestamp' => $payload->timestamp, 'hits' => $payload->hits, 'args' => $payload->args); $body = bson_encode($body); $probeKey = "{$_this->config['name']}.{$_this->module}.{$probe->name}"; try { if ($probe->instant) { publishSample($_this, $probeKey . '.all', $body); } else { if (isset($sample['consumerId'])) { publishSample($_this, $probeKey . '.' . $sample['consumerId'], $body); } } } catch (Exception $e) { $_this->disconnect(); return; } }); return $probe; }
public function opQuery($fullCollectionName, array $query, $numberToSkip, $numberToReturn, $flags, $timeout, array $returnFieldsSelector = null) { $data = pack('Va*VVa*', $flags, "{$fullCollectionName}", $numberToSkip, $numberToReturn, bson_encode($query)); if ($returnFieldsSelector) { $data .= bson_encode($returnFieldsSelector); } return $this->putReadMessage(self::OP_QUERY, $data, $timeout); }
protected function send_request(GoRpcRequest $req) { $this->write(bson_encode($req->header)); if ($req->body === NULL) { $this->write(bson_encode(array())); } else { $this->write(bson_encode($req->body)); } }
/** @test */ public function parser_validates_bson_data() { if (function_exists('bson_decode')) { $expected = array('status' => 123, 'message' => 'hello world'); $payload = bson_encode($expected); $parser = new Parser(); $this->assertEquals($expected, $parser->bson($payload)); } }
protected function sendRequest(VTContext $ctx, GoRpcRequest $req) { $this->write($ctx, bson_encode($req->header)); if ($req->body === NULL) { $this->write($ctx, bson_encode(array())); } else { $this->write($ctx, bson_encode($req->body)); } }
function send($msg) { $serialized_message = bson_encode($msg); $len = strlen($serialized_message); $off = 0; while ($off < $len) { $len_write = socket_write($this->socket, $off == 0 ? $serialized_message : $substr($serialized_message, $off), $len - $off); if (!$len_write) { throw new Exception("write error"); } $off += $len_write; } }
/** * Generate a BSON representation of the given {@link SS_List}. * * @param SS_List $set * @param null $fields * * @return string BSON */ public function convertDataObjectSet(SS_List $set, $fields = null) { $this->checkForBson(); $items = []; foreach ($set as $do) { /** @var DataObject $do */ if (!$do->canView()) { continue; } $items[] = $this->convertDataObjectToJSONObject($do, $fields); } $serobj = ArrayData::array_to_object(["totalSize" => is_numeric($this->totalSize) ? $this->totalSize : null, "items" => $items]); /** @noinspection PhpUndefinedFunctionInspection */ return bson_encode($serobj); }
/** * Method called when object received. * @param object Object. * @return void */ public function cacheObject($o) { if (Daemon::$config->logevents->value) { Daemon::log(__METHOD__ . '(' . json_encode($o) . ')'); } if (isset($o['_key'])) { $this->cache->set($o['_key'], bson_encode($o)); $this->cache->set('_id.' . (string) $o['_id'], $o['_key']); } if (isset($o['_ev'])) { $o['name'] = $o['_ev']; if (Daemon::$config->logevents->value) { Daemon::log('MongoNode send event ' . $o['name']); } $this->RTEPClient->client->request(array('op' => 'event', 'event' => $o)); } }
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(); }
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)); }
<?php $expected = chr(236) . chr(81) . chr(184) . chr(30) . chr(133) . chr(235) . chr(16) . chr(64); var_dump($expected === bson_encode(4.23));
public function remove($col, $cond = array(), $key = '') { if (strpos($col, '.') === FALSE) { $col = $this->dbname . '.' . $col; } if (is_string($cond)) { $cond = new MongoCode($cond); } $reqId = $this->request($key, self::OP_DELETE, "" . $col . "" . "" . bson_encode($cond)); }
/** * serialize -- by default with BSON * * @param object $object * * @return string */ function serialize($object) { return bson_encode($object); }
<?php var_dump('' === bson_encode(null));
/** * @param mixed $data * @param string $format * @param array $context * * @return string */ public function encode($data, $format, array $context = array()) { return bson_encode($data); }
/** * @dataProvider data */ public function testEncode($encoded, $decoded) { $this->assertEquals($encoded, bson_encode($decoded)); }
/** * Method called when object received. * @param object Object. * @return void */ public function cacheObject($o) { if (\PHPDaemon\Core\Daemon::$config->logevents->value) { \PHPDaemon\Core\Daemon::log(__METHOD__ . '(' . json_encode($o) . ')'); } if (isset($o['_key'])) { $this->cache->set($o['_key'], bson_encode($o)); $this->cache->set('_id.' . (string) $o['_id'], $o['_key']); } if (isset($o['_ev'])) { $o['name'] = $o['_ev']; if (\PHPDaemon\Core\Daemon::$config->logevents->value) { \PHPDaemon\Core\Daemon::log('MongoNode send event ' . $o['name']); } } }
<?php $hex = '0123456789abcdef01234567'; $expected = pack('H*', $hex); var_dump($expected === bson_encode(new MongoId($hex)));
/** * Gets the BSON encoded document (never normally needed) */ public function getBSONDocument() { return bson_encode($this->getRawDocument()); }
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"; }
public function testRegex() { $x = bson_encode(NULL); $this->assertEquals("", $x); }
/** * Remove objects from collection * @param string $col Collection's name * @param array $cond Conditions * @param callable $cb Optional. Callback called when response received * @param array $params Optional. Parameters * @callback $cb ( ) * @return void */ public function remove($col, $cond = [], $cb = NULL, $params = []) { if (strpos($col, '.') === false) { $col = $this->dbname . '.' . $col; } if (is_string($cond)) { $cond = new \MongoCode($cond); } if ($this->safeMode && is_array($cond)) { static::safeModeEnc($cond); } try { $this->request(self::OP_DELETE, "" . $col . "" . "" . bson_encode($cond), false, null, function ($conn, $reqId = null) use($col, $cb, $params) { if (!$conn) { !$cb || call_user_func($cb, ['$err' => 'Connection error.']); return; } if ($cb !== NULL) { $this->lastError($col, $cb, $params, $conn); } }); } catch (\MongoException $e) { Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString()); if ($cb !== null) { call_user_func($cb, ['$err' => $e->getMessage(), '$query' => $cond]); } } }
/** * Remove objects from collection * @param string Collection's name * @param array Conditions * @param mixed Optional. Callback called when response received. * @param string Optional. Distribution key. * @return void */ public function remove($col, $cond = array(), $cb = NULL, $key = '') { if (strpos($col, '.') === false) { $col = $this->dbname . '.' . $col; } if (is_string($cond)) { $cond = new MongoCode($cond); } $reqId = $this->request($key, self::OP_DELETE, "" . $col . "" . "" . bson_encode($cond)); if ($cb !== NULL) { $this->lastError($col, $cb, $this->lastRequestSession); } }
protected function createLastErrorMessage(array $options) { $command = array_merge(['getLastError' => 1], $options); if (!isset($command['w'])) { $command['w'] = 1; } if (!isset($command['j'])) { $command['j'] = false; } if (!isset($command['wtimeout'])) { $command['wtimeout'] = 10000; } if ($command['w'] === 0 && $command['j'] === false) { return; } return pack('Va*VVa*', 0, "admin.\$cmd", 0, -1, bson_encode($command)); }
/** * @iterations 10000 */ public function complexNestedEncode() { $bson = bson_encode($this->complexNestedDoc); return $bson; }
public function setResult($result = null, $multi = false) { if ($this->dataType === 'json') { try { $this->header('Content-Type: text/json'); } catch (RequestHeadersAlreadySent $e) { } $this->out(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ($multi ? "\n" : '')); } elseif ($this->dataType === 'jsonp') { try { $this->header('Content-Type: text/plain'); } catch (RequestHeadersAlreadySent $e) { } $this->out(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . ($multi ? "\n" : '')); } elseif ($this->dataType === 'xml') { $converter = new Array2XML(); $converter->setRootName($this->xmlRootName); try { $this->header('Content-Type: text/xml'); } catch (RequestHeadersAlreadySent $e) { } $this->out($converter->convert($result)); } elseif ($this->dataType === 'bson') { try { $this->header('Content-Type: application/octet-stream'); } catch (RequestHeadersAlreadySent $e) { } $this->out(bson_encode($result)); } elseif ($this->dataType === 'dump') { try { $this->header('Content-Type: text/plain'); } catch (RequestHeadersAlreadySent $e) { } $this->out(Debug::dump($result)); } else { $this->header('Content-Type: application/x-javascript'); $this->out(json_encode(['errmsg' => 'Unsupported data-type.'])); } if (!$multi) { $this->finish(); } }
public function saslScrumSHA1Conversation($dbname, $query, $cb, $conn = null) { if ($this->safeMode) { static::safeModeEnc($query); } try { $this->request(self::OP_QUERY, pack('V', 0) . $dbname . '.$cmd' . "" . pack('VV', 0, -1) . bson_encode($query), true, $conn, function ($conn, $reqId = null) use($dbname, $cb) { if (!$conn) { !$cb || $cb(['$err' => 'Connection error.']); return; } $conn->requests[$reqId] = [$dbname, $cb, true]; }); } catch (\MongoException $e) { Daemon::log('MongoClient exception: ' . $e->getMessage() . ': ' . $e->getTraceAsString()); if ($cb !== null) { $cb(['$err' => $e->getMessage(), '$query' => $query, '$fields' => isset($p['fields']) ? $p['fields'] : null]); } } }
<?php var_dump('foobar' === bson_encode('foobar'));
<?php var_dump(chr(1) === bson_encode(true)); var_dump(chr(0) === bson_encode(false));