Skip to content

Commit 2e39482

Browse files
committed
PHPLIB-547: Implement listCollectionNames helper
1 parent 28d5377 commit 2e39482

12 files changed

+516
-89
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
========================================
2+
MongoDB\\Database::listCollectionNames()
3+
========================================
4+
5+
.. versionadded:: 1.7
6+
7+
.. default-domain:: mongodb
8+
9+
.. contents:: On this page
10+
:local:
11+
:backlinks: none
12+
:depth: 1
13+
:class: singlecol
14+
15+
Definition
16+
----------
17+
18+
.. phpmethod:: MongoDB\\Database::listCollectionNames()
19+
20+
Returns names for all collections in this database.
21+
22+
.. code-block:: php
23+
24+
function listCollectionNames(array $options = []): Iterator
25+
26+
This method has the following parameters:
27+
28+
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-param.rst
29+
30+
The ``$options`` parameter supports the following options:
31+
32+
.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-option.rst
33+
34+
Return Values
35+
-------------
36+
37+
An :php:`Iterator <class.iterator.php>`, which provides the name of each
38+
collection in the database.
39+
40+
Example
41+
-------
42+
43+
The following example lists all of the collections in the ``test`` database:
44+
45+
.. code-block:: php
46+
47+
<?php
48+
49+
$database = (new MongoDB\Client)->test;
50+
51+
foreach ($database->listCollectionNames() as $collectionName) {
52+
var_dump($collectionName);
53+
}
54+
55+
The output would then resemble::
56+
57+
string(11) "restaurants"
58+
string(5) "users"
59+
string(6) "restos"
60+
61+
The following example lists all collections whose name starts with ``"rest"``
62+
in the ``test`` database:
63+
64+
.. code-block:: php
65+
66+
<?php
67+
68+
$database = (new MongoDB\Client)->test;
69+
70+
$collections = $database->listCollectionNames([
71+
'filter' => [
72+
'name' => new MongoDB\BSON\Regex('^rest.*'),
73+
],
74+
]);
75+
76+
foreach ($collections as $collectionName) {
77+
var_dump($collectionName);
78+
}
79+
80+
The output would then resemble::
81+
82+
string(11) "restaurants"
83+
string(6) "restos"
84+
85+
.. note::
86+
87+
When enumerating collection names, a filter expression can only filter based
88+
on a collection's name and type. No other fields are available.
89+
90+
See Also
91+
--------
92+
93+
- :phpmethod:`MongoDB\\Database::listCollections()`
94+
- :manual:`listCollections </reference/command/listCollections` command
95+
reference in the MongoDB manual
96+
- `Enumerating Collections
97+
<https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst>`_
98+
specification

docs/reference/method/MongoDBDatabase-listCollections.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ The output would then resemble::
114114
See Also
115115
--------
116116

117+
- :phpmethod:`MongoDB\\Database::listCollectionNames()`
117118
- :manual:`listCollections </reference/command/listCollections` command
118119
reference in the MongoDB manual
119120
- `Enumerating Collections

src/Command/ListCollections.php

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
<?php
2+
/*
3+
* Copyright 2020-present MongoDB, Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace MongoDB\Command;
19+
20+
use MongoDB\Driver\Command;
21+
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
22+
use MongoDB\Driver\Server;
23+
use MongoDB\Driver\Session;
24+
use MongoDB\Exception\InvalidArgumentException;
25+
use MongoDB\Model\CachingIterator;
26+
use MongoDB\Operation\Executable;
27+
use function is_array;
28+
use function is_bool;
29+
use function is_integer;
30+
use function is_object;
31+
32+
/**
33+
* Wrapper for the listCollections command.
34+
*
35+
* @internal
36+
* @see http://docs.mongodb.org/manual/reference/command/listCollections/
37+
*/
38+
class ListCollections implements Executable
39+
{
40+
/** @var string */
41+
private $databaseName;
42+
43+
/** @var array */
44+
private $options;
45+
46+
/**
47+
* Constructs a listCollections command.
48+
*
49+
* Supported options:
50+
*
51+
* * filter (document): Query by which to filter collections.
52+
*
53+
* * maxTimeMS (integer): The maximum amount of time to allow the query to
54+
* run.
55+
*
56+
* * nameOnly (boolean): A flag to indicate whether the command should
57+
* return just the collection/view names and type or return both the name
58+
* and other information.
59+
*
60+
* * session (MongoDB\Driver\Session): Client session.
61+
*
62+
* Sessions are not supported for server versions < 3.6.
63+
*
64+
* @param string $databaseName Database name
65+
* @param array $options Command options
66+
* @throws InvalidArgumentException for parameter/option parsing errors
67+
*/
68+
public function __construct($databaseName, array $options = [])
69+
{
70+
if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
71+
throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], 'array or object');
72+
}
73+
74+
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
75+
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
76+
}
77+
78+
if (isset($options['nameOnly']) && ! is_bool($options['nameOnly'])) {
79+
throw InvalidArgumentException::invalidType('"nameOnly" option', $options['nameOnly'], 'boolean');
80+
}
81+
82+
if (isset($options['session']) && ! $options['session'] instanceof Session) {
83+
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
84+
}
85+
86+
$this->databaseName = (string) $databaseName;
87+
$this->options = $options;
88+
}
89+
90+
/**
91+
* Execute the operation.
92+
*
93+
* @see Executable::execute()
94+
* @param Server $server
95+
* @return CachingIterator
96+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
97+
*/
98+
public function execute(Server $server)
99+
{
100+
$cmd = ['listCollections' => 1];
101+
102+
if (! empty($this->options['filter'])) {
103+
$cmd['filter'] = (object) $this->options['filter'];
104+
}
105+
106+
if (isset($this->options['maxTimeMS'])) {
107+
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
108+
}
109+
110+
if (isset($this->options['nameOnly'])) {
111+
$cmd['nameOnly'] = $this->options['nameOnly'];
112+
}
113+
114+
$cursor = $server->executeReadCommand($this->databaseName, new Command($cmd), $this->createOptions());
115+
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
116+
117+
return new CachingIterator($cursor);
118+
}
119+
120+
/**
121+
* Create options for executing the command.
122+
*
123+
* Note: read preference is intentionally omitted, as the spec requires that
124+
* the command be executed on the primary.
125+
*
126+
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
127+
* @return array
128+
*/
129+
private function createOptions()
130+
{
131+
$options = [];
132+
133+
if (isset($this->options['session'])) {
134+
$options['session'] = $this->options['session'];
135+
}
136+
137+
return $options;
138+
}
139+
}

src/Database.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
namespace MongoDB;
1919

20+
use Iterator;
2021
use MongoDB\Driver\Cursor;
2122
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
2223
use MongoDB\Driver\Manager;
@@ -35,6 +36,7 @@
3536
use MongoDB\Operation\DatabaseCommand;
3637
use MongoDB\Operation\DropCollection;
3738
use MongoDB\Operation\DropDatabase;
39+
use MongoDB\Operation\ListCollectionNames;
3840
use MongoDB\Operation\ListCollections;
3941
use MongoDB\Operation\ModifyCollection;
4042
use MongoDB\Operation\Watch;
@@ -404,6 +406,21 @@ public function getWriteConcern()
404406
return $this->writeConcern;
405407
}
406408

409+
/**
410+
* Returns the names of all collections in this database
411+
*
412+
* @see ListCollectionNames::__construct() for supported options
413+
* @throws InvalidArgumentException for parameter/option parsing errors
414+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
415+
*/
416+
public function listCollectionNames(array $options = []) : Iterator
417+
{
418+
$operation = new ListCollectionNames($this->databaseName, $options);
419+
$server = select_server($this->manager, $options);
420+
421+
return $operation->execute($server);
422+
}
423+
407424
/**
408425
* Returns information for all collections in this database.
409426
*

src/Model/CallbackIterator.php

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
<?php
2+
/*
3+
* Copyright 2017 MongoDB, Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace MongoDB\Model;
19+
20+
use Closure;
21+
use Iterator;
22+
use IteratorIterator;
23+
use Traversable;
24+
25+
/**
26+
* Iterator to apply a callback before returning an element
27+
*
28+
* @internal
29+
*/
30+
class CallbackIterator implements Iterator
31+
{
32+
/** @var Closure */
33+
private $callback;
34+
35+
/** @var IteratorIterator */
36+
private $iterator;
37+
38+
public function __construct(Traversable $traversable, Closure $callback)
39+
{
40+
$this->iterator = new IteratorIterator($traversable);
41+
$this->callback = $callback;
42+
}
43+
44+
/**
45+
* @see http://php.net/iterator.current
46+
* @return mixed
47+
*/
48+
public function current()
49+
{
50+
return ($this->callback)($this->iterator->current());
51+
}
52+
53+
/**
54+
* @see http://php.net/iterator.key
55+
* @return mixed
56+
*/
57+
public function key()
58+
{
59+
return $this->iterator->key();
60+
}
61+
62+
/**
63+
* @see http://php.net/iterator.next
64+
* @return void
65+
*/
66+
public function next()
67+
{
68+
$this->iterator->next();
69+
}
70+
71+
/**
72+
* @see http://php.net/iterator.rewind
73+
* @return void
74+
*/
75+
public function rewind()
76+
{
77+
$this->iterator->rewind();
78+
}
79+
80+
/**
81+
* @see http://php.net/iterator.valid
82+
* @return boolean
83+
*/
84+
public function valid()
85+
{
86+
return $this->iterator->valid();
87+
}
88+
}

0 commit comments

Comments
 (0)