PK Ǫ?Vk> > phpunit.xml.distnu W+A
The full result document as an array, including partial data if available and additional keys.
*/ public function getDocument() { } public $document; } PK Ǫ?VoK K lib/Mongo/MongoCommandCursor.phpnu W+A command = $command; } /** * @param MongoClient $connection * @param string $hash * @param array $document * @return MongoCommandCursor */ public static function createFromDocument(MongoClient $connection, $hash, array $document) { throw new \Exception('Not implemented'); } /** * @return \MongoDB\Driver\Cursor */ protected function ensureCursor() { if ($this->cursor === null) { $convertedCommand = TypeConverter::fromLegacy($this->command); if (isset($convertedCommand->cursor)) { if ($convertedCommand->cursor === true || $convertedCommand->cursor === []) { $convertedCommand->cursor = new \stdClass(); } } $originalReadPreference = null; if (!$this->supportsReadPreference()) { $originalReadPreference = $this->readPreference; $this->setReadPreference(\MongoClient::RP_PRIMARY); } try { $this->cursor = $this->db->command($convertedCommand, $this->getOptions()); } finally { if ($originalReadPreference) { $this->readPreference = $originalReadPreference; } } } return $this->cursor; } /** * @return array */ protected function getCursorInfo() { return [ 'ns' => $this->ns, 'limit' => 0, 'batchSize' => $this->batchSize, 'skip' => 0, 'flags' => 0, 'query' => $this->command, 'fields' => null, ]; } /** * @return array */ protected function getIterationInfo() { $iterationInfo = parent::getIterationInfo(); if ($iterationInfo['started_iterating']) { $iterationInfo += [ 'firstBatchAt' => $iterationInfo['at'], 'firstBatchNumReturned' => $iterationInfo['numReturned'], ]; $iterationInfo['at'] = 0; $iterationInfo['numReturned'] = 0; } return $iterationInfo; } /** * @return array */ public function __sleep() { return ['command'] + parent::__sleep(); } /** * @see https://github.com/mongodb/mongo-php-driver-legacy/blob/1.6.14/db.c#L51 * @return bool */ private function supportsReadPreference() { if ($this->command === []) { return false; } $firstKey = array_keys($this->command)[0]; switch ($firstKey) { case 'count': case 'group': case 'dbStats': case 'geoNear': case 'geoWalk': case 'distinct': case 'aggregate': case 'collStats': case 'geoSearch': case 'parallelCollectionScan': return true; case 'mapreduce': case 'mapReduce': return (isset($this->command['out']) && is_array($this->command['out']) && array_key_exists('inline', $this->command['out'])); default: return false; } } } PK Ǫ?VϐF F lib/Mongo/MongoDB.phpnu W+A checkDatabaseName($name); $this->connection = $conn; $this->name = (string) $name; $this->setReadPreferenceFromArray($conn->getReadPreference()); $this->setWriteConcernFromArray($conn->getWriteConcern()); $this->createDatabaseObject(); } /** * @return \MongoDB\Database * @internal This method is not part of the ext-mongo API */ public function getDb() { return $this->db; } /** * The name of this database * * @link http://www.php.net/manual/en/mongodb.--tostring.php * @return string Returns this database's name. */ public function __toString() { return $this->name; } /** * Gets a collection * * @link http://www.php.net/manual/en/mongodb.get.php * @param string $name The name of the collection. * @return MongoCollection */ public function __get($name) { // Handle w and wtimeout properties that replicate data stored in $readPreference if ($name === 'w' || $name === 'wtimeout') { return $this->getWriteConcern()[$name]; } return $this->selectCollection($name); } /** * @param string $name * @param mixed $value */ public function __set($name, $value) { if ($name === 'w' || $name === 'wtimeout') { trigger_error("The '{$name}' property is read-only", E_USER_DEPRECATED); } } /** * Returns information about collections in this database * * @link http://www.php.net/manual/en/mongodb.getcollectioninfo.php * @param array $options An array of options for listing the collections. * @return array */ public function getCollectionInfo(array $options = []) { $includeSystemCollections = false; // The includeSystemCollections option is no longer supported in the command if (isset($options['includeSystemCollections'])) { $includeSystemCollections = $options['includeSystemCollections']; unset($options['includeSystemCollections']); } try { $collections = $this->db->listCollections($options); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } $getCollectionInfo = function (CollectionInfo $collectionInfo) { // @todo do away with __debugInfo once https://jira.mongodb.org/browse/PHPLIB-226 is fixed $info = $collectionInfo->__debugInfo(); return array_filter( [ 'name' => $collectionInfo->getName(), 'type' => isset($info['type']) ? $info['type'] : null, 'options' => $collectionInfo->getOptions(), 'info' => isset($info['info']) ? (array) $info['info'] : null, 'idIndex' => isset($info['idIndex']) ? (array) $info['idIndex'] : null, ], function ($item) { return $item !== null; } ); }; $eligibleCollections = array_filter( iterator_to_array($collections), $this->getSystemCollectionFilterClosure($includeSystemCollections) ); return array_map($getCollectionInfo, $eligibleCollections); } /** * Get all collections from this database * * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php * @param array $options An array of options for listing the collections. * @return array Returns the names of the all the collections in the database as an array */ public function getCollectionNames(array $options = []) { $includeSystemCollections = false; // The includeSystemCollections option is no longer supported in the command if (isset($options['includeSystemCollections'])) { $includeSystemCollections = $options['includeSystemCollections']; unset($options['includeSystemCollections']); } try { $collections = $this->db->listCollections($options); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } $getCollectionName = function (CollectionInfo $collectionInfo) { return $collectionInfo->getName(); }; $eligibleCollections = array_filter( iterator_to_array($collections), $this->getSystemCollectionFilterClosure($includeSystemCollections) ); return array_map($getCollectionName, $eligibleCollections); } /** * @return MongoClient * @internal This method is not part of the ext-mongo API */ public function getConnection() { return $this->connection; } /** * Fetches toolkit for dealing with files stored in this database * * @link http://www.php.net/manual/en/mongodb.getgridfs.php * @param string $prefix The prefix for the files and chunks collections. * @return MongoGridFS Returns a new gridfs object for this database. */ public function getGridFS($prefix = "fs") { return new \MongoGridFS($this, $prefix); } /** * Gets this database's profiling level * * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php * @return int Returns the profiling level. */ public function getProfilingLevel() { $result = $this->command(['profile' => -1]); return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0; } /** * Sets this database's profiling level * * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php * @param int $level Profiling level. * @return int Returns the previous profiling level. */ public function setProfilingLevel($level) { $result = $this->command(['profile' => $level]); return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0; } /** * Drops this database * * @link http://www.php.net/manual/en/mongodb.drop.php * @return array Returns the database response. */ public function drop() { return TypeConverter::toLegacy($this->db->drop()); } /** * Repairs and compacts this database * * @link http://www.php.net/manual/en/mongodb.repair.php * @param bool $preserve_cloned_files [optional]If cloned files should be kept if the repair fails.
* @param bool $backup_original_files [optional]If original files should be backed up.
* @return arrayReturns db response.
*/ public function repair($preserve_cloned_files = false, $backup_original_files = false) { $command = [ 'repairDatabase' => 1, 'preserveClonedFilesOnFailure' => $preserve_cloned_files, 'backupOriginalFiles' => $backup_original_files, ]; return $this->command($command); } /** * Gets a collection * * @link http://www.php.net/manual/en/mongodb.selectcollection.php * @param string $name The collection name. * @throws Exception if the collection name is invalid. * @return MongoCollection Returns a new collection object. */ public function selectCollection($name) { return new MongoCollection($this, $name); } /** * Creates a collection * * @link http://www.php.net/manual/en/mongodb.createcollection.php * @param string $name The name of the collection. * @param array $options * @return MongoCollection Returns a collection object representing the new collection. */ public function createCollection($name, $options = []) { try { if (isset($options['capped'])) { $options['capped'] = (bool) $options['capped']; } $this->db->createCollection($name, $options); } catch (\MongoDB\Driver\Exception\Exception $e) { return false; } return $this->selectCollection($name); } /** * Drops a collection * * @link http://www.php.net/manual/en/mongodb.dropcollection.php * @param MongoCollection|string $coll MongoCollection or name of collection to drop. * @return array Returns the database response. * * @deprecated Use MongoCollection::drop() instead. */ public function dropCollection($coll) { if ($coll instanceof MongoCollection) { $coll = $coll->getName(); } return TypeConverter::toLegacy($this->db->dropCollection((string) $coll)); } /** * Get a list of collections in this database * * @link http://www.php.net/manual/en/mongodb.listcollections.php * @param array $options * @return MongoCollection[] Returns a list of MongoCollections. */ public function listCollections(array $options = []) { return array_map([$this, 'selectCollection'], $this->getCollectionNames($options)); } /** * Creates a database reference * * @link http://www.php.net/manual/en/mongodb.createdbref.php * @param string $collection The collection to which the database reference will point. * @param mixed $document_or_id * @return array Returns a database reference array. */ public function createDBRef($collection, $document_or_id) { if ($document_or_id instanceof \MongoId) { $id = $document_or_id; } elseif (is_object($document_or_id)) { if (! isset($document_or_id->_id)) { $id = $document_or_id; } else { $id = $document_or_id->_id; } } elseif (is_array($document_or_id)) { if (! isset($document_or_id['_id'])) { return null; } $id = $document_or_id['_id']; } else { $id = $document_or_id; } return MongoDBRef::create($collection, $id); } /** * Fetches the document pointed to by a database reference * * @link http://www.php.net/manual/en/mongodb.getdbref.php * @param array $ref A database reference. * @return array Returns the document pointed to by the reference. */ public function getDBRef(array $ref) { $db = (isset($ref['$db']) && $ref['$db'] !== $this->name) ? $this->connection->selectDB($ref['$db']) : $this; return MongoDBRef::get($db, $ref); } /** * Runs JavaScript code on the database server. * * @link http://www.php.net/manual/en/mongodb.execute.php * @param MongoCode|string $code Code to execute. * @param array $args [optional] Arguments to be passed to code. * @return array Returns the result of the evaluation. */ public function execute($code, array $args = []) { return $this->command(['eval' => $code, 'args' => $args]); } /** * Execute a database command * * @link http://www.php.net/manual/en/mongodb.command.php * @param array $data The query to send. * @param array $options * @return array Returns database response. */ public function command(array $data, $options = [], &$hash = null) { try { $cursor = new \MongoCommandCursor($this->connection, $this->name, $data); $cursor->setReadPreference($this->getReadPreference()); return iterator_to_array($cursor)[0]; } catch (\MongoDB\Driver\Exception\Exception $e) { return ExceptionConverter::toResultArray($e); } } /** * Check if there was an error on the most recent db operation performed * * @link http://www.php.net/manual/en/mongodb.lasterror.php * @return array Returns the error, if there was one. */ public function lastError() { return $this->command(array('getLastError' => 1)); } /** * Checks for the last error thrown during a database operation * * @link http://www.php.net/manual/en/mongodb.preverror.php * @return array Returns the error and the number of operations ago it occurred. */ public function prevError() { return $this->command(array('getPrevError' => 1)); } /** * Clears any flagged errors on the database * * @link http://www.php.net/manual/en/mongodb.reseterror.php * @return array Returns the database response. */ public function resetError() { return $this->command(array('resetError' => 1)); } /** * Creates a database error * * @link http://www.php.net/manual/en/mongodb.forceerror.php * @return boolean Returns the database response. */ public function forceError() { return $this->command(array('forceerror' => 1)); } /** * Log in to this database * * @link http://www.php.net/manual/en/mongodb.authenticate.php * @param string $username The username. * @param string $password The password (in plaintext). * @return array Returns database response. If the login was successful, it will return 1. * * @deprecated This method is not implemented, supply authentication credentials through the connection string instead. */ public function authenticate($username, $password) { throw new \Exception('The MongoDB::authenticate method is not supported. Please supply authentication credentials through the connection string'); } /** * {@inheritdoc} */ public function setReadPreference($readPreference, $tags = null) { $result = $this->setReadPreferenceFromParameters($readPreference, $tags); $this->createDatabaseObject(); return $result; } /** * {@inheritdoc} */ public function setWriteConcern($wstring, $wtimeout = 0) { $result = $this->setWriteConcernFromParameters($wstring, $wtimeout); $this->createDatabaseObject(); return $result; } protected function notImplemented() { throw new \Exception('Not implemented'); } /** * @return \MongoDB\Database */ private function createDatabaseObject() { $options = [ 'readPreference' => $this->readPreference, 'writeConcern' => $this->writeConcern, ]; if ($this->db === null) { $this->db = $this->connection->getClient()->selectDatabase($this->name, $options); } else { $this->db = $this->db->withOptions($options); } } private function checkDatabaseName($name) { if (empty($name)) { throw new \Exception('Database name cannot be empty'); } if (strlen($name) >= 64) { throw new \Exception('Database name cannot exceed 63 characters'); } if (strpos($name, chr(0)) !== false) { throw new \Exception('Database name cannot contain null bytes'); } $invalidCharacters = ['.', '$', '/', ' ', '\\']; foreach ($invalidCharacters as $char) { if (strchr($name, $char) !== false) { throw new \Exception('Database name contains invalid characters'); } } } /** * @param bool $includeSystemCollections * @return Closure */ private function getSystemCollectionFilterClosure($includeSystemCollections = false) { return function (CollectionInfo $collectionInfo) use ($includeSystemCollections) { return $includeSystemCollections || ! preg_match('#^system\.#', $collectionInfo->getName()); }; } /** * @return array */ public function __sleep() { return ['connection', 'name']; } } PK Ǫ?V# " lib/Mongo/MongoGridFSException.phpnu W+A true], array $driverOptions = []) { if ($server === 'default') { $server = 'mongodb://' . self::DEFAULT_HOST . ':' . self::DEFAULT_PORT; } if (isset($options['readPreferenceTags'])) { $options['readPreferenceTags'] = [$this->getReadPreferenceTags($options['readPreferenceTags'])]; } $this->applyConnectionOptions($server, $options); $this->server = $server; if (false === strpos($this->server, '://')) { $this->server = 'mongodb://' . $this->server; } $this->client = new Client($this->server, $options, $driverOptions); $info = $this->client->__debugInfo(); $this->manager = $info['manager']; if (isset($options['connect']) && $options['connect']) { $this->connect(); } } /** * Closes this database connection * * @link http://www.php.net/manual/en/mongoclient.close.php * @param boolean|string $connection * @return boolean If the connection was successfully closed. */ public function close($connection = null) { $this->connected = false; return false; } /** * Connects to a database server * * @link http://www.php.net/manual/en/mongoclient.connect.php * * @throws MongoConnectionException * @return boolean If the connection was successful. */ public function connect() { $this->connected = true; return true; } /** * Drops a database * * @link http://www.php.net/manual/en/mongoclient.dropdb.php * @param mixed $db The database to drop. Can be a MongoDB object or the name of the database. * @return array The database response. * @deprecated Use MongoDB::drop() instead. */ public function dropDB($db) { return $this->selectDB($db)->drop(); } /** * Gets a database * * @link http://php.net/manual/en/mongoclient.get.php * @param string $dbname The database name. * @return MongoDB The database name. */ public function __get($dbname) { return $this->selectDB($dbname); } /** * Gets the client for this object * * @internal This part is not of the ext-mongo API and should not be used * @return Client */ public function getClient() { return $this->client; } /** * Get connections * * Returns an array of all open connections, and information about each of the servers * * @return array */ public static function getConnections() { return []; } /** * Get hosts * * This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the * set. Without a replica set, it will just return an array with one element containing the host that you are * connected to. * * @return array */ public function getHosts() { $this->forceConnect(); $results = []; try { $servers = $this->manager->getServers(); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } foreach ($servers as $server) { $key = sprintf('%s:%d;-;.;%d', $server->getHost(), $server->getPort(), getmypid()); $info = $server->getInfo(); switch ($server->getType()) { case \MongoDB\Driver\Server::TYPE_RS_PRIMARY: $state = 1; break; case \MongoDB\Driver\Server::TYPE_RS_SECONDARY: $state = 2; break; default: $state = 0; } $results[$key] = [ 'host' => $server->getHost(), 'port' => $server->getPort(), 'health' => (int) $info['ok'], 'state' => $state, 'ping' => $server->getLatency(), 'lastPing' => null, ]; } return $results; } /** * Kills a specific cursor on the server * * @link http://www.php.net/manual/en/mongoclient.killcursor.php * @param string $server_hash The server hash that has the cursor. * @param int|MongoInt64 $id The ID of the cursor to kill. * @return bool */ public function killCursor($server_hash, $id) { $this->notImplemented(); } /** * Lists all of the databases available * * @link http://php.net/manual/en/mongoclient.listdbs.php * @return array Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving the database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully. */ public function listDBs() { try { $databaseInfoIterator = $this->client->listDatabases(); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } $databases = [ 'databases' => [], 'totalSize' => 0, 'ok' => 1.0, ]; foreach ($databaseInfoIterator as $databaseInfo) { $databases['databases'][] = [ 'name' => $databaseInfo->getName(), 'empty' => $databaseInfo->isEmpty(), 'sizeOnDisk' => $databaseInfo->getSizeOnDisk(), ]; $databases['totalSize'] += $databaseInfo->getSizeOnDisk(); } return $databases; } /** * Gets a database collection * * @link http://www.php.net/manual/en/mongoclient.selectcollection.php * @param string $db The database name. * @param string $collection The collection name. * @return MongoCollection Returns a new collection object. * @throws Exception Throws Exception if the database or collection name is invalid. */ public function selectCollection($db, $collection) { return new MongoCollection($this->selectDB($db), $collection); } /** * Gets a database * * @link http://www.php.net/manual/en/mongo.selectdb.php * @param string $name The database name. * @return MongoDB Returns a new db object. * @throws InvalidArgumentException */ public function selectDB($name) { return new MongoDB($this, $name); } /** * {@inheritdoc} */ public function setReadPreference($readPreference, $tags = null) { return $this->setReadPreferenceFromParameters($readPreference, $tags); } /** * {@inheritdoc} */ public function setWriteConcern($wstring, $wtimeout = 0) { return $this->setWriteConcernFromParameters($wstring, $wtimeout); } /** * String representation of this connection * * @link http://www.php.net/manual/en/mongoclient.tostring.php * @return string Returns hostname and port for this connection. */ public function __toString() { return $this->server; } /** * Forces a connection by executing the ping command */ private function forceConnect() { try { $command = new \MongoDB\Driver\Command(['ping' => 1]); $this->manager->executeCommand('db', $command); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } } private function notImplemented() { throw new \Exception('Not implemented'); } /** * @return array */ public function __sleep() { return [ 'connected', 'status', 'server', 'persistent' ]; } /** * @param $server * @return array */ private function extractUrlOptions($server) { $queryOptions = explode('&', parse_url($server, PHP_URL_QUERY)); $options = []; foreach ($queryOptions as $option) { if (strpos($option, '=') === false) { continue; } $keyValue = explode('=', $option); if ($keyValue[0] === 'readPreferenceTags') { $options[$keyValue[0]][] = $this->getReadPreferenceTags($keyValue[1]); } elseif (ctype_digit($keyValue[1])) { $options[$keyValue[0]] = (int) $keyValue[1]; } else { $options[$keyValue[0]] = $keyValue[1]; } } return $options; } /** * @param $readPreferenceTagString * @return array */ private function getReadPreferenceTags($readPreferenceTagString) { $tagSets = []; foreach (explode(',', $readPreferenceTagString) as $index => $tagSet) { $tags = explode(':', $tagSet); $tagSets[$tags[0]] = $tags[1]; } return $tagSets; } /** * @param string $server * @param array $options */ private function applyConnectionOptions($server, array $options) { $urlOptions = $this->extractUrlOptions($server); if (isset($urlOptions['wTimeout'])) { $urlOptions['wTimeoutMS'] = $urlOptions['wTimeout']; unset($urlOptions['wTimeout']); } if (isset($options['wTimeout'])) { $options['wTimeoutMS'] = $options['wTimeout']; unset($options['wTimeout']); } // Special handling for readPreferenceTags which are merged if (isset($options['readPreferenceTags']) && isset($urlOptions['readPreferenceTags'])) { $options['readPreferenceTags'] = array_merge($urlOptions['readPreferenceTags'], $options['readPreferenceTags']); unset($urlOptions['readPreferenceTags']); } $urlOptions = array_merge($urlOptions, $options); if (isset($urlOptions['slaveOkay'])) { $this->setReadPreferenceFromSlaveOkay($urlOptions['slaveOkay']); } elseif (isset($urlOptions['readPreference']) || isset($urlOptions['readPreferenceTags'])) { $readPreference = isset($urlOptions['readPreference']) ? $urlOptions['readPreference'] : null; $tags = isset($urlOptions['readPreferenceTags']) ? $urlOptions['readPreferenceTags'] : null; $this->setReadPreferenceFromParameters($readPreference, $tags); } if (isset($urlOptions['w']) || isset($urlOptions['wTimeoutMs'])) { $writeConcern = (isset($urlOptions['w'])) ? $urlOptions['w'] : 1; $wTimeout = (isset($urlOptions['wTimeoutMs'])) ? $urlOptions['wTimeoutMs'] : null; $this->setWriteConcern($writeConcern, $wTimeout); } } } PK Ǫ?V lib/Mongo/MongoInt32.phpnu W+A value = (string) $value; } /** * @return string */ public function __toString() { return (string) $this->value; } /** * Converts this MongoInt32 to a native integer * * @return int * @internal This method is not part of the ext-mongo API */ public function toBSONType() { return (int) $this->value; } } PK Ǫ?V!Y8 8 lib/Mongo/MongoCursor.phpnu W+A query = $query; $this->projection = $fields; } /** * Adds a top-level key/value pair to a query * @link http://www.php.net/manual/en/mongocursor.addoption.php * @param string $key Fieldname to add. * @param mixed $value Value to add. * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function addOption($key, $value) { $this->errorIfOpened(); $this->options[$key] = $value; return $this; } /** * (PECL mongo >= 1.2.11)If the cursor should wait for more data to become available.
* @return MongoCursor Returns this cursor. */ public function awaitData($wait = true) { $this->errorIfOpened(); $this->awaitData = $wait; return $this; } /** * Counts the number of results for this query * @link http://www.php.net/manual/en/mongocursor.count.php * @param bool $foundOnly Send cursor limit and skip information to the count function, if applicable. * @return int The number of documents returned by this cursor's query. */ public function count($foundOnly = false) { $optionNames = ['hint', 'maxTimeMS']; if ($foundOnly) { $optionNames = array_merge($optionNames, ['limit', 'skip']); } $options = $this->getOptions($optionNames) + $this->options; try { $count = $this->collection->count(TypeConverter::fromLegacy($this->query), $options); } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) { throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } return $count; } /** * Execute the query * @link http://www.php.net/manual/en/mongocursor.doquery.php * @throws MongoConnectionException if it cannot reach the database. * @return void */ protected function doQuery() { $options = $this->getOptions() + $this->options; try { $this->cursor = $this->collection->find(TypeConverter::fromLegacy($this->query), $options); } catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) { throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e); } catch (\MongoDB\Driver\Exception\Exception $e) { throw ExceptionConverter::toLegacy($e); } } /** * Return an explanation of the query, often useful for optimization and debugging * @link http://www.php.net/manual/en/mongocursor.explain.php * @return array Returns an explanation of the query. */ public function explain() { $optionNames = [ 'allowPartialResults', 'batchSize', 'cursorType', 'limit', 'maxTimeMS', 'noCursorTimeout', 'projection', 'skip', 'sort', ]; $options = $this->getOptions($optionNames); $command = [ 'explain' => [ 'find' => $this->collection->getCollectionName(), 'filter' => TypeConverter::fromLegacy($this->query), ] + $options, ]; $explained = TypeConverter::toLegacy(iterator_to_array($this->db->command($command))[0]); unset($explained['ok']); return $explained; } /** * Sets the fields for a query * @link http://www.php.net/manual/en/mongocursor.fields.php * @param array $f Fields to return (or not return). * @throws MongoCursorException * @return MongoCursor */ public function fields(array $f) { $this->errorIfOpened(); $this->projection = $f; return $this; } /** * Advances the cursor to the next result, and returns that result * @link http://www.php.net/manual/en/mongocursor.getnext.php * @throws MongoConnectionException * @throws MongoCursorTimeoutException * @return array Returns the next object */ public function getNext() { return $this->next(); } /** * Checks if there are any more elements in this cursor * @link http://www.php.net/manual/en/mongocursor.hasnext.php * @throws MongoConnectionException * @throws MongoCursorTimeoutException * @return bool Returns true if there is another element */ public function hasNext() { if (! $this->startedIterating) { $this->ensureIterator(); $this->startedIterating = true; $this->storeIteratorState(); $this->cursorNeedsAdvancing = false; } elseif ($this->cursorNeedsAdvancing) { $this->ensureIterator()->next(); $this->cursorNeedsAdvancing = false; } return $this->ensureIterator()->valid(); } /** * Gives the database a hint about the query * @link http://www.php.net/manual/en/mongocursor.hint.php * @param array|string $keyPattern Indexes to use for the query. * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function hint($keyPattern) { $this->errorIfOpened(); $this->hint = $keyPattern; return $this; } /** * Sets whether this cursor will timeout * @link http://www.php.net/manual/en/mongocursor.immortal.php * @param bool $liveForever If the cursor should be immortal. * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function immortal($liveForever = true) { $this->errorIfOpened(); $this->noCursorTimeout = $liveForever; return $this; } /** * Limits the number of results returned * @link http://www.php.net/manual/en/mongocursor.limit.php * @param int $num The number of results to return. * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function limit($num) { $this->errorIfOpened(); $this->limit = $num; return $this; } /** * @param int $ms * @return $this * @throws MongoCursorException */ public function maxTimeMS($ms) { $this->errorIfOpened(); $this->maxTimeMS = $ms; return $this; } /** * @link http://www.php.net/manual/en/mongocursor.partial.php * @param bool $okay [optional]If receiving partial results is okay.
* @return MongoCursor Returns this cursor. */ public function partial($okay = true) { $this->allowPartialResults = $okay; return $this; } /** * Clears the cursor * @link http://www.php.net/manual/en/mongocursor.reset.php * @return void */ public function reset() { parent::reset(); } /** * @link http://www.php.net/manual/en/mongocursor.setflag.php * @param int $flag * @param bool $set * @return MongoCursor */ public function setFlag($flag, $set = true) { $this->notImplemented(); } /** * Skips a number of results * @link http://www.php.net/manual/en/mongocursor.skip.php * @param int $num The number of results to skip. * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function skip($num) { $this->errorIfOpened(); $this->skip = $num; return $this; } /** * Sets whether this query can be done on a slave * This method will override the static class variable slaveOkay. * @link http://www.php.net/manual/en/mongocursor.slaveOkay.php * @param boolean $okay If it is okay to query the slave. * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function slaveOkay($okay = true) { $this->errorIfOpened(); $this->setReadPreferenceFromSlaveOkay($okay); return $this; } /** * Use snapshot mode for the query * @link http://www.php.net/manual/en/mongocursor.snapshot.php * @throws MongoCursorException * @return MongoCursor Returns this cursor */ public function snapshot() { $this->errorIfOpened(); $this->snapshot = true; return $this; } /** * Sorts the results by given fields * @link http://www.php.net/manual/en/mongocursor.sort.php * @param array $fields An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort * @throws MongoCursorException * @return MongoCursor Returns the same cursor that this method was called on */ public function sort(array $fields) { $this->errorIfOpened(); $this->sort = $fields; return $this; } /** * Sets whether this cursor will be left open after fetching the last results * @link http://www.php.net/manual/en/mongocursor.tailable.php * @param bool $tail If the cursor should be tailable. * @return MongoCursor Returns this cursor */ public function tailable($tail = true) { $this->errorIfOpened(); $this->tailable = $tail; return $this; } /** * @return int|null */ protected function convertCursorType() { if (! $this->tailable) { return null; } return $this->awaitData ? Find::TAILABLE_AWAIT : Find::TAILABLE; } /** * @return array */ protected function convertModifiers() { $modifiers = array_key_exists('modifiers', $this->options) ? $this->options['modifiers'] : []; foreach (['hint', 'snapshot'] as $modifier) { if ($this->$modifier === null) { continue; } $modifiers['$' . $modifier] = $this->$modifier; } return $modifiers; } /** * @return array */ protected function convertProjection() { return TypeConverter::convertProjection($this->projection); } /** * @return Cursor */ protected function ensureCursor() { if ($this->cursor === null) { $this->doQuery(); } return $this->cursor; } /** * @param \Traversable $traversable * @return \Generator */ protected function wrapTraversable(\Traversable $traversable) { foreach ($traversable as $key => $value) { if (isset($value->_id) && ($value->_id instanceof \MongoDB\BSON\ObjectID || !is_object($value->_id))) { $key = (string) $value->_id; } yield $key => $value; } } /** * @return array */ protected function getCursorInfo() { return [ 'ns' => $this->ns, 'limit' => $this->limit, 'batchSize' => (int) $this->batchSize, 'skip' => $this->skip, 'flags' => $this->flags, 'query' => $this->query, 'fields' => $this->projection, ]; } /** * @return array */ public function __sleep() { return [ 'allowPartialResults', 'awaitData', 'flags', 'hint', 'limit', 'maxTimeMS', 'noCursorTimeout', 'optionNames', 'options', 'projection', 'query', 'skip', 'snapshot', 'sort', 'tailable', ] + parent::__sleep(); } } PK Ǫ?Vq ) lib/Mongo/MongoCursorTimeoutException.phpnu W+A collection = $collection; $this->batchType = $batchType; $this->writeOptions = $writeOptions; } /** * Adds a write operation to a batch * * @see http://php.net/manual/en/mongowritebatch.add.php * @param array|object $item * @return boolean */ public function add($item) { if (is_object($item)) { $item = (array) $item; } $this->validate($item); $this->addItem($item); return true; } /** * Executes a batch of write operations * * @see http://php.net/manual/en/mongowritebatch.execute.php * @param array $writeOptions * @return array */ final public function execute(array $writeOptions = []) { $writeOptions += $this->writeOptions; if (! count($this->items)) { return ['ok' => true]; } if (isset($writeOptions['j'])) { trigger_error('j parameter is not supported', E_USER_WARNING); } if (isset($writeOptions['fsync'])) { trigger_error('fsync parameter is not supported', E_USER_WARNING); } $options['writeConcern'] = $this->createWriteConcernFromArray($writeOptions); if (isset($writeOptions['ordered'])) { $options['ordered'] = $writeOptions['ordered']; } try { $writeResult = $this->collection->getCollection()->bulkWrite($this->items, $options); $resultDocument = []; $ok = true; } catch (BulkWriteException $e) { $writeResult = $e->getWriteResult(); $resultDocument = ['writeErrors' => $this->convertWriteErrors($writeResult)]; $ok = false; } $this->items = []; switch ($this->batchType) { case self::COMMAND_UPDATE: if ($options['writeConcern']->getW() === 0) { $resultDocument += [ 'nMatched' => 0, 'nModified' => 0, 'nUpserted' => 0, 'ok' => true, ]; break; } $upsertedIds = []; foreach ($writeResult->getUpsertedIds() as $index => $id) { $upsertedIds[] = [ 'index' => $index, '_id' => TypeConverter::toLegacy($id) ]; } $resultDocument += [ 'nMatched' => $writeResult->getMatchedCount(), 'nModified' => $writeResult->getModifiedCount(), 'nUpserted' => $writeResult->getUpsertedCount(), 'ok' => true, ]; if (count($upsertedIds)) { $resultDocument['upserted'] = $upsertedIds; } break; case self::COMMAND_DELETE: if ($options['writeConcern']->getW() === 0) { $resultDocument += [ 'nRemoved' => 0, 'ok' => true, ]; break; } $resultDocument += [ 'nRemoved' => $writeResult->getDeletedCount(), 'ok' => true, ]; break; case self::COMMAND_INSERT: if ($options['writeConcern']->getW() === 0) { $resultDocument += [ 'nInserted' => 0, 'ok' => true, ]; break; } $resultDocument += [ 'nInserted' => $writeResult->getInsertedCount(), 'ok' => true, ]; break; } if (! $ok) { // Exception code is hardcoded to the value in ext-mongo, see // https://github.com/mongodb/mongo-php-driver-legacy/blob/ab4bc0d90e93b3f247f6bcb386d0abc8d2fa7d74/batch/write.c#L428 throw new \MongoWriteConcernException('Failed write', 911, null, $resultDocument); } return $resultDocument; } private function validate(array $item) { switch ($this->batchType) { case self::COMMAND_UPDATE: if (! isset($item['q'])) { throw new Exception("Expected \$item to contain 'q' key"); } if (! isset($item['u'])) { throw new Exception("Expected \$item to contain 'u' key"); } break; case self::COMMAND_DELETE: if (! isset($item['q'])) { throw new Exception("Expected \$item to contain 'q' key"); } if (! isset($item['limit'])) { throw new Exception("Expected \$item to contain 'limit' key"); } break; } } private function addItem(array $item) { switch ($this->batchType) { case self::COMMAND_UPDATE: $method = isset($item['multi']) ? 'updateMany' : 'updateOne'; $options = []; if (isset($item['upsert']) && $item['upsert']) { $options['upsert'] = true; } $this->items[] = [$method => [TypeConverter::fromLegacy($item['q']), TypeConverter::fromLegacy($item['u']), $options]]; break; case self::COMMAND_INSERT: $this->items[] = ['insertOne' => [TypeConverter::fromLegacy($item)]]; break; case self::COMMAND_DELETE: $method = $item['limit'] === 0 ? 'deleteMany' : 'deleteOne'; $this->items[] = [$method => [TypeConverter::fromLegacy($item['q'])]]; break; } } /** * @param WriteResult $result * @return array */ private function convertWriteErrors(WriteResult $result) { $writeErrors = []; /** @var WriteError $writeError */ foreach ($result->getWriteErrors() as $writeError) { $writeErrors[] = [ 'index' => $writeError->getIndex(), 'code' => $writeError->getCode(), 'errmsg' => $writeError->getMessage(), ]; } return $writeErrors; } } PK Ǫ?VeTz lib/Mongo/MongoException.phpnu W+A sec = (int) $sec; $this->usec = (int) $this->truncateMicroSeconds($usec); } /** * Returns a string representation of this date * @return string */ public function __toString() { return (string) sprintf('%.8f', $this->truncateMicroSeconds($this->usec) / 1000000) . ' ' . $this->sec; } /** * Converts this MongoDate to the new BSON UTCDateTime type * * @return UTCDateTime * @internal This method is not part of the ext-mongo API */ public function toBSONType() { $milliSeconds = ($this->sec * 1000) + ($this->truncateMicroSeconds($this->usec) / 1000); return new UTCDateTime($milliSeconds); } /** * Returns a DateTime object representing this date * @link http://php.net/manual/en/mongodate.todatetime.php * @return DateTime */ public function toDateTime() { $datetime = new \DateTime(); $datetime->setTimestamp($this->sec); $microSeconds = $this->truncateMicroSeconds($this->usec); if ($microSeconds > 0) { $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u', $datetime->format('Y-m-d H:i:s') . '.' . str_pad($microSeconds, 6, '0', STR_PAD_LEFT)); } $datetime->setTimezone(new \DateTimeZone("UTC")); return $datetime; } /** * @param int $usec * @return int */ private function truncateMicroSeconds($usec) { return (int) floor($usec / 1000) * 1000; } } PK Ǫ?Vve lib/Mongo/MongoDeleteBatch.phpnu W+A (PECL mongo >= 1.5.0) * @link http://php.net/manual/en/class.mongoduplicatekeyexception.php */ class MongoDuplicateKeyException extends MongoWriteConcernException { } PK Ǫ?Vb$ $ , lib/Mongo/MongoExecutionTimeoutException.phpnu W+A (PECL mongo >= 1.5.0) * @link http://php.net/manual/en/class.mongoexecutiontimeoutexception.php */ class MongoExecutionTimeoutException extends MongoException { } PK Ǫ?V[ lib/Mongo/MongoRegex.phpnu W+A regex = $regex->getPattern(); $this->flags = $regex->getFlags(); return; } if (! preg_match('#^/(.*)/([imxslu]*)$#', $regex, $matches)) { throw new MongoException('invalid regex', 9); } $this->regex = $matches[1]; $this->flags = $matches[2]; } /** * Returns a string representation of this regular expression. * @return string This regular expression in the form "/expr/flags". */ public function __toString() { return '/' . $this->regex . '/' . $this->flags; } /** * Converts this MongoRegex to the new BSON Regex type * * @return Regex * @internal This method is not part of the ext-mongo API */ public function toBSONType() { return new Regex($this->regex, $this->flags); } } PK Ǫ?VUT" $ lib/Mongo/MongoProtocolException.phpnu W+A (PECL mongo >= 1.5.0) */ class MongoProtocolException extends MongoException { } PK Ǫ?Vފ lib/Mongo/MongoGridFSCursor.phpnu W+A gridfs = $gridfs; parent::__construct($connection, $ns, $query, $fields); } /** * Returns the current file * * @link http://php.net/manual/en/mongogridfscursor.current.php * @return MongoGridFSFile The current file */ public function current() { $file = parent::current(); return ($file !== null) ? new MongoGridFSFile($this->gridfs, $file) : null; } /** * Returns the current result's filename * * @link http://php.net/manual/en/mongogridfscursor.key.php * @return string The current results filename */ public function key() { $file = $this->current(); return ($file !== null) ? (string) $file->file['_id'] : null; } } PK Ǫ?V: : lib/Mongo/MongoGridFS.phpnu W+A Optional collection name prefix. * @param mixed $chunks [optional] * @throws \Exception */ public function __construct(MongoDB $db, $prefix = "fs", $chunks = null) { if ($chunks) { trigger_error("The 'chunks' argument is deprecated and ignored", E_USER_DEPRECATED); } if (empty($prefix)) { throw new \Exception('MongoGridFS::__construct(): invalid prefix'); } $this->database = $db; $this->prefix = (string) $prefix; $this->filesName = $prefix . '.files'; $this->chunksName = $prefix . '.chunks'; $this->chunks = $db->selectCollection($this->chunksName); parent::__construct($db, $this->filesName); } /** * Delete a file from the database * * @link http://php.net/manual/en/mongogridfs.delete.php * @param mixed $id _id of the file to remove * @return boolean Returns true if the remove was successfully sent to the database. */ public function delete($id) { $this->createChunksIndex(); $this->chunks->remove(['files_id' => $id], ['justOne' => false]); return parent::remove(['_id' => $id]); } /** * Drops the files and chunks collections * @link http://php.net/manual/en/mongogridfs.drop.php * @return array The database response */ public function drop() { $this->chunks->drop(); return parent::drop(); } /** * @link http://php.net/manual/en/mongogridfs.find.php * @param array $query The query * @param array $fields Fields to return * @param array $options Options for the find command * @return MongoGridFSCursor A MongoGridFSCursor */ public function find(array $query = [], array $fields = []) { $cursor = new MongoGridFSCursor($this, $this->db->getConnection(), (string) $this, $query, $fields); $cursor->setReadPreference($this->getReadPreference()); return $cursor; } /** * Returns a single file matching the criteria * * @link http://www.php.net/manual/en/mongogridfs.findone.php * @param mixed $query The fields for which to search or a filename to search for. * @param array $fields Fields of the results to return. * @param array $options Options for the find command * @return MongoGridFSFile|null */ public function findOne($query = [], array $fields = [], array $options = []) { if (! is_array($query)) { $query = ['filename' => (string) $query]; } $items = iterator_to_array($this->find($query, $fields)->limit(1)); return count($items) ? current($items) : null; } /** * Retrieve a file from the database * * @link http://www.php.net/manual/en/mongogridfs.get.php * @param mixed $id _id of the file to find. * @return MongoGridFSFile|null */ public function get($id) { return $this->findOne(['_id' => $id]); } /** * Stores a file in the database * * @link http://php.net/manual/en/mongogridfs.put.php * @param string $filename The name of the file * @param array $extra Other metadata to add to the file saved * @param array $options An array of options for the insert operations executed against the chunks and files collections. * @return mixed Returns the _id of the saved object */ public function put($filename, array $extra = [], array $options = []) { return $this->storeFile($filename, $extra, $options); } /** * Removes files from the collections * * @link http://www.php.net/manual/en/mongogridfs.remove.php * @param array $criteria Description of records to remove. * @param array $options Options for remove. * @throws MongoCursorException * @return boolean */ public function remove(array $criteria = [], array $options = []) { $this->createChunksIndex(); $matchingFiles = parent::find($criteria, ['_id' => 1]); $ids = []; foreach ($matchingFiles as $file) { $ids[] = $file['_id']; } $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false] + $options); return parent::remove(['_id' => ['$in' => $ids]], ['justOne' => false] + $options); } /** * Chunkifies and stores bytes in the database * @link http://php.net/manual/en/mongogridfs.storebytes.php * @param string $bytes A string of bytes to store * @param array $extra Other metadata to add to the file saved * @param array $options Options for the store. "safe": Check that this store succeeded * @return mixed The _id of the object saved */ public function storeBytes($bytes, array $extra = [], array $options = []) { $this->createChunksIndex(); $record = $extra + [ 'length' => mb_strlen($bytes, '8bit'), 'md5' => md5($bytes), ]; try { $file = $this->insertFile($record, $options); } catch (MongoException $e) { throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), $e->getCode(), $e); } try { $this->insertChunksFromBytes($bytes, $file); } catch (MongoException $e) { $this->delete($file['_id']); throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), $e->getCode(), $e); } return $file['_id']; } /** * Stores a file in the database * * @link http://php.net/manual/en/mongogridfs.storefile.php * @param string $filename The name of the file * @param array $extra Other metadata to add to the file saved * @param array $options Options for the store. "safe": Check that this store succeeded * @return mixed Returns the _id of the saved object * @throws MongoGridFSException * @throws Exception */ public function storeFile($filename, array $extra = [], array $options = []) { $this->createChunksIndex(); $record = $extra; if (is_string($filename)) { $record += [ 'md5' => md5_file($filename), 'length' => filesize($filename), 'filename' => $filename, ]; $handle = fopen($filename, 'r'); if (! $handle) { throw new MongoGridFSException('could not open file: ' . $filename); } } elseif (! is_resource($filename)) { throw new \Exception('first argument must be a string or stream resource'); } else { $handle = $filename; } $md5 = null; try { $file = $this->insertFile($record, $options); } catch (MongoException $e) { throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), $e->getCode(), $e); } try { $length = $this->insertChunksFromFile($handle, $file, $md5); } catch (MongoException $e) { $this->delete($file['_id']); throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), $e->getCode(), $e); } // Add length and MD5 if they were not present before $update = []; if (! isset($record['length'])) { $update['length'] = $length; } if (! isset($record['md5'])) { try { $update['md5'] = $md5; } catch (MongoException $e) { throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), $e->getCode(), $e); } } if (count($update)) { try { $result = $this->update(['_id' => $file['_id']], ['$set' => $update]); if (! $this->isOKResult($result)) { throw new MongoGridFSException('Could not store file'); } } catch (MongoException $e) { $this->delete($file['_id']); throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), $e->getCode(), $e); } } return $file['_id']; } /** * Saves an uploaded file directly from a POST to the database * * @link http://www.php.net/manual/en/mongogridfs.storeupload.php * @param string $name The name attribute of the uploaded file, from . * @param array $metadata An array of extra fields for the uploaded file. * @return mixed Returns the _id of the uploaded file. * @throws MongoGridFSException */ public function storeUpload($name, array $metadata = []) { if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) { throw new MongoGridFSException("Could not find uploaded file $name"); } if (! isset($_FILES[$name]['tmp_name'])) { throw new MongoGridFSException("Couldn't find tmp_name in the \$_FILES array. Are you sure the upload worked?"); } $uploadedFile = $_FILES[$name]; $uploadedFile['tmp_name'] = (array) $uploadedFile['tmp_name']; $uploadedFile['name'] = (array) $uploadedFile['name']; if (count($uploadedFile['tmp_name']) > 1) { foreach ($uploadedFile['tmp_name'] as $key => $file) { $metadata['filename'] = $uploadedFile['name'][$key]; $this->storeFile($file, $metadata); } return null; } else { $metadata += ['filename' => array_pop($uploadedFile['name'])]; return $this->storeFile(array_pop($uploadedFile['tmp_name']), $metadata); } } /** * Creates the index on the chunks collection */ private function createChunksIndex() { try { $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]); } catch (MongoDuplicateKeyException $e) { } } /** * Inserts a single chunk into the database * * @param mixed $fileId * @param string $data * @param int $chunkNumber * @return array|bool */ private function insertChunk($fileId, $data, $chunkNumber) { $chunk = [ 'files_id' => $fileId, 'n' => $chunkNumber, 'data' => new MongoBinData($data), ]; $result = $this->chunks->insert($chunk); if (! $this->isOKResult($result)) { throw new \MongoException('error inserting chunk'); } return $result; } /** * Splits a string into chunks and writes them to the database * * @param string $bytes * @param array $record */ private function insertChunksFromBytes($bytes, $record) { $chunkSize = $record['chunkSize']; $fileId = $record['_id']; $i = 0; $chunks = str_split($bytes, $chunkSize); foreach ($chunks as $chunk) { $this->insertChunk($fileId, $chunk, $i++); } } /** * Reads chunks from a file and writes them to the database * * @param resource $handle * @param array $record * @param string $md5 * @return int Returns the number of bytes written to the database */ private function insertChunksFromFile($handle, $record, &$md5) { $written = 0; $offset = 0; $i = 0; $fileId = $record['_id']; $chunkSize = $record['chunkSize']; $hash = hash_init('md5'); rewind($handle); while (! feof($handle)) { $data = stream_get_contents($handle, $chunkSize); hash_update($hash, $data); $this->insertChunk($fileId, $data, $i++); $written += strlen($data); $offset += $chunkSize; } $md5 = hash_final($hash); return $written; } /** * Writes a file record to the database * * @param $record * @param array $options * @return array */ private function insertFile($record, array $options = []) { $record += [ '_id' => new MongoId(), 'uploadDate' => new MongoDate(), 'chunkSize' => $this->defaultChunkSize, ]; $result = $this->insert($record, $options); if (! $this->isOKResult($result)) { throw new \MongoException('error inserting file'); } return $record; } private function isOKResult($result) { return (is_array($result) && $result['ok'] == 1.0) || (is_bool($result) && $result); } /** * @return array */ public function __sleep() { return ['chunks', 'chunksName', 'database', 'defaultChunkSize', 'filesName', 'prefix'] + parent::__sleep(); } } PK Ǫ?V9R lib/Mongo/MongoTimestamp.phpnu W+A :A MongoDB document, if available, as an array.
*/ public function getDocument() { return $this->document; } } PK Ǫ?V`Z(X X lib/Mongo/MongoGridFSFile.phpnu W+A gridfs = $gridfs; $this->file = $file; } /** * Returns this file's filename * @link http://php.net/manual/en/mongogridfsfile.getfilename.php * @return string Returns the filename */ public function getFilename() { return isset($this->file['filename']) ? $this->file['filename'] : null; } /** * Returns this file's size * @link http://php.net/manual/en/mongogridfsfile.getsize.php * @return int Returns this file's size */ public function getSize() { return $this->file['length']; } /** * Writes this file to the filesystem * @link http://php.net/manual/en/mongogridfsfile.write.php * @param string $filename The location to which to write the file (path+filename+extension). If none is given, the stored filename will be used. * @return int Returns the number of bytes written */ public function write($filename = null) { if ($filename === null) { $filename = $this->getFilename(); } if (empty($filename)) { $filename = 'file'; } if (! $handle = fopen($filename, 'w')) { trigger_error('Can not open the destination file', E_USER_ERROR); return 0; } $written = $this->copyToResource($handle); fclose($handle); return $written; } /** * This will load the file into memory. If the file is bigger than your memory, this will cause problems! * @link http://php.net/manual/en/mongogridfsfile.getbytes.php * @return string Returns a string of the bytes in the file */ public function getBytes() { $result = ''; foreach ($this->getChunks() as $chunk) { $result .= $chunk['data']->bin; } return $result; } /** * This method returns a stream resource that can be used to read the stored file with all file functions in PHP. * The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first. * At most two GridFSFile chunks will be loaded in memory. * * @link http://php.net/manual/en/mongogridfsfile.getresource.php * @return resource Returns a resource that can be used to read the file with */ public function getResource() { $handle = fopen('php://temp', 'w+'); $this->copyToResource($handle); rewind($handle); return $handle; } private function copyToResource($handle) { $written = 0; foreach ($this->getChunks() as $chunk) { $written += fwrite($handle, $chunk['data']->bin); } return $written; } private function getChunks() { return $chunks = $this->gridfs->chunks->find( ['files_id' => $this->file['_id']], ['data' => 1], ['n' => 1] ); } } PK Ǫ?VLq lib/Mongo/MongoCode.phpnu W+A getCode(); $scope = TypeConverter::toLegacy($javascript->getScope()); } $this->code = $code; $this->scope = $scope; } /** * Returns this code as a string * @return string */ public function __toString() { return $this->code; } /** * Converts this MongoCode to the new BSON JavaScript type * * @return \MongoDB\BSON\Javascript * @internal This method is not part of the ext-mongo API */ public function toBSONType() { return new \MongoDB\BSON\Javascript($this->code, $this->scope); } } PK Ǫ?V 'ޛ " lib/Mongo/MongoCursorException.phpnu W+A notImplemented(); } /** * Get pool size for connection pools * * @link http://php.net/manual/en/mongo.getpoolsize.php * @return int Returns the current pool size. * * @deprecated This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::getSize() instead. */ public function getPoolSize() { $this->notImplemented(); } /** * Returns the address being used by this for slaveOkay reads * * @link http://php.net/manual/en/mongo.getslave.php * @return bool The address of the secondary this connection is using for * reads. This returns NULL if this is not connected to a replica set or not yet * initialized. */ public function getSlave() { $this->notImplemented(); } /** * Get slaveOkay setting for this connection * * @link http://php.net/manual/en/mongo.getslaveokay.php * @return bool Returns the value of slaveOkay for this instance. */ public function getSlaveOkay() { $this->notImplemented(); } /** * Connects to paired database server * * @link http://www.php.net/manual/en/mongo.pairconnect.php * @throws MongoConnectionException * @return boolean * * @deprecated Pass a string of the form "mongodb://server1,server2" to the constructor instead of using this method. */ public function pairConnect() { $this->notImplemented(); } /** * Returns information about all connection pools. * * @link http://php.net/manual/en/mongo.pooldebug.php * @return array * @deprecated This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::info() instead. */ public function poolDebug() { $this->notImplemented(); } /** * Change slaveOkay setting for this connection * * @link http://php.net/manual/en/mongo.setslaveokay.php * @param bool $ok * @return bool returns the former value of slaveOkay for this instance. */ public function setSlaveOkay($ok) { $this->notImplemented(); } /** * Set the size for future connection pools. * * @link http://php.net/manual/en/mongo.setpoolsize.php * @param $sizeThe max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.
* @return bool Returns the former value of pool size. * @deprecated Relying on this feature is highly discouraged. Please use MongoPool::setSize() instead. */ public function setPoolSize($size) { $this->notImplemented(); } /** * Creates a persistent connection with a database server * * @link http://www.php.net/manual/en/mongo.persistconnect.php * @param string $username A username used to identify the connection. * @param string $password A password used to identify the connection. * @throws MongoConnectionException * @return boolean If the connection was successful. * @deprecated Pass array("persist" => $id) to the constructor instead of using this method. */ public function persistConnect($username = "", $password = "") { $this->notImplemented(); } /** * Creates a persistent connection with paired database servers * * @link http://www.php.net/manual/en/mongo.pairpersistconnect.php * @param string $username A username used to identify the connection. * @param string $password A password used to identify the connection. * @throws MongoConnectionException * @return boolean If the connection was successful. * @deprecated Pass "mongodb://server1,server2" and array("persist" => $id) to the constructor instead of using this method. */ public function pairPersistConnect($username = "", $password = "") { $this->notImplemented(); } /** * Connects with a database server * * @link http://www.php.net/manual/en/mongo.connectutil.php * @throws MongoConnectionException * @return boolean If the connection was successful. */ protected function connectUtil() { $this->notImplemented(); } /** * Check if there was an error on the most recent db operation performed * * @link http://www.php.net/manual/en/mongo.lasterror.php * @return array|null Returns the error, if there was one, or NULL. * @deprecated Use MongoDB::lastError() instead. */ public function lastError() { $this->notImplemented(); } /** * Checks for the last error thrown during a database operation * * @link http://www.php.net/manual/en/mongo.preverror.php * @return array Returns the error and the number of operations ago it occurred. * @deprecated Use MongoDB::prevError() instead. */ public function prevError() { $this->notImplemented(); } /** * Clears any flagged errors on the connection * * @link http://www.php.net/manual/en/mongo.reseterror.php * @return array Returns the database response. * @deprecated Use MongoDB::resetError() instead. */ public function resetError() { $this->notImplemented(); } /** * Choose a new secondary for slaveOkay reads * * @link www.php.net/manual/en/mongo.switchslave.php * @return string The address of the secondary this connection is using for reads. This may be the same as the previous address as addresses are randomly chosen. It may return only one address if only one secondary (or only the primary) is available. * @throws MongoException (error code 15) if it is called on a non-replica-set connection. It will also throw MongoExceptions if it cannot find anyone (primary or secondary) to read from (error code 16). */ public function switchSlave() { $this->notImplemented(); } /** * Creates a database error on the database. * * @link http://www.php.net/manual/en/mongo.forceerror.php * @return boolean The database response. * @deprecated Use MongoDB::forceError() instead. */ public function forceError() { $this->notImplemented(); } protected function notImplemented() { throw new \Exception('The Mongo class is deprecated and not supported through mongo-php-adapter'); } } PK Ǫ?V%H lib/Mongo/MongoMaxKey.phpnu W+A createObjectID($id); } /** * Check if a value is a valid ObjectId * * @link http://php.net/manual/en/mongoid.isvalid.php * @param mixed $value The value to check for validity. * @return bool */ public static function isValid($value) { if ($value instanceof ObjectID || $value instanceof MongoId) { return true; } elseif (! is_string($value)) { return false; } return (bool) preg_match('#^[a-f0-9]{24}$#i', $value); } /** * Returns a hexidecimal representation of this id * @link http://www.php.net/manual/en/mongoid.tostring.php * @return string */ public function __toString() { return (string) $this->objectID; } /** * Converts this MongoId to the new BSON ObjectID type * * @return ObjectID * @internal This method is not part of the ext-mongo API */ public function toBSONType() { return $this->objectID; } /** * @param string $name * * @return null|string */ public function __get($name) { if ($name === '$id') { return (string) $this->objectID; } return null; } /** * @param string $name * @param mixed $value */ public function __set($name, $value) { if ($name === 'id') { trigger_error("The '\$id' property is read-only", E_USER_DEPRECATED); return; } } /** * @param string $name * @return bool */ public function __isset($name) { return $name === 'id'; } /** * @param string $name */ public function __unset($name) { if ($name === 'id') { trigger_error("The '\$id' property is read-only", E_USER_DEPRECATED); return; } } /** * @return string */ public function serialize() { return (string) $this->objectID; } /** * @param string $serialized */ public function unserialize($serialized) { $this->createObjectID($serialized); } /** * Gets the incremented value to create this id * @link http://php.net/manual/en/mongoid.getinc.php * @return int Returns the incremented value used to create this MongoId. */ public function getInc() { return hexdec(substr((string) $this->objectID, -6)); } /** * (PECL mongo >= 1.0.11) * Gets the process ID * @link http://php.net/manual/en/mongoid.getpid.php * @return int Returns the PID of the MongoId. */ public function getPID() { $id = (string) $this->objectID; // PID is stored as little-endian, flip it around $pid = substr($id, 16, 2) . substr($id, 14, 2); return hexdec($pid); } /** * (PECL mongo >= 1.0.1) * Gets the number of seconds since the epoch that this id was created * @link http://www.php.net/manual/en/mongoid.gettimestamp.php * @return int */ public function getTimestamp() { return hexdec(substr((string) $this->objectID, 0, 8)); } /** * Gets the hostname being used for this machine's ids * @link http://www.php.net/manual/en/mongoid.gethostname.php * @return string */ public static function getHostname() { return gethostname(); } /** * (PECL mongo >= 1.0.8) * Create a dummy MongoId * @link http://php.net/manual/en/mongoid.set-state.php * @param array $propsTheoretically, an array of properties used to create the new id. However, as MongoId instances have no properties, this is not used.
* @return MongoId A new id with the value "000000000000000000000000". */ public static function __set_state(array $props) { } /** * @return stdClass */ public function jsonSerialize() { $object = new stdClass(); $object->{'$id'} = (string) $this->objectID; return $object; } /** * @param $id * @throws MongoException */ private function createObjectID($id) { try { if (is_string($id)) { $this->objectID = new ObjectID($id); } elseif ($id instanceof self || $id instanceof ObjectID) { $this->objectID = new ObjectID((string) $id); } else { $this->objectID = new ObjectID(); } } catch (\Exception $e) { throw new MongoException('Invalid object ID', 19); } } } PK Ǫ?V6o lib/Mongo/MongoUpdateBatch.phpnu W+A bin = $data->getData(); $this->type = $data->getType(); } else { $this->bin = $data; $this->type = $type; } } /** * Returns the string "* This function will set a callback function to be called for {@link http://www.php.net/manual/en/class.mongolog.php MongoLog} events * instead of triggering warnings. *
* @link http://www.php.net/manual/en/mongolog.setcallback.php * @param callable $log_function* The function to be called on events. *
** The function should have the following prototype *
* * log_function ( int $module , int $level, string $message) *One of the {@link http://www.php.net/manual/en/class.mongolog.php#mongolog.constants.module MongoLog module constants}.
*One of the {@link http://www.php.net/manual/en/class.mongolog.php#mongolog.constants.level MongoLog level constants}.
*The log message itself.
*