Skip to content

Commit 726ccb5

Browse files
committed
PHPLIB-547: Implement listCollectionNames helper
1 parent d2bebc4 commit 726ccb5

12 files changed

+513
-89
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
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 = []): Generator
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+
A generator containing the name of each collection in the database.
38+
39+
Example
40+
-------
41+
42+
The following example lists all of the collections in the ``test`` database:
43+
44+
.. code-block:: php
45+
46+
<?php
47+
48+
$database = (new MongoDB\Client)->test;
49+
50+
foreach ($database->listCollectionNames() as $collectionName) {
51+
var_dump($collectionName);
52+
}
53+
54+
The output would then resemble::
55+
56+
string(11) "restaurants"
57+
string(5) "users"
58+
string(6) "restos"
59+
60+
The following example lists all collections whose name starts with ``"rest"``
61+
in the ``test`` database:
62+
63+
.. code-block:: php
64+
65+
<?php
66+
67+
$database = (new MongoDB\Client)->test;
68+
69+
$collections = $database->listCollectionNames([
70+
'filter' => [
71+
'name' => new MongoDB\BSON\Regex('^rest.*'),
72+
],
73+
]);
74+
75+
foreach ($collections as $collectionName) {
76+
var_dump($collectionName);
77+
}
78+
79+
The output would then resemble::
80+
81+
string(11) "restaurants"
82+
string(6) "restos"
83+
84+
.. note::
85+
86+
When enumerating collection names, a filter expression can only filter based
87+
on a collection's name and type. No other fields are available.
88+
89+
See Also
90+
--------
91+
92+
- :phpmethod:`MongoDB\\Database::listCollections()`
93+
- :manual:`listCollections </reference/command/listCollections` command
94+
reference in the MongoDB manual
95+
- `Enumerating Collections
96+
<https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst>`_
97+
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: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
<?php
2+
/*
3+
* Copyright 2015-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\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+
* * session (MongoDB\Driver\Session): Client session.
57+
*
58+
* Sessions are not supported for server versions < 3.6.
59+
*
60+
* @param string $databaseName Database name
61+
* @param array $options Command options
62+
* @throws InvalidArgumentException for parameter/option parsing errors
63+
*/
64+
public function __construct($databaseName, array $options = [])
65+
{
66+
if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
67+
throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], 'array or object');
68+
}
69+
70+
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
71+
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
72+
}
73+
74+
if (isset($options['nameOnly']) && ! is_bool($options['nameOnly'])) {
75+
throw InvalidArgumentException::invalidType('"nameOnly" option', $options['nameOnly'], 'boolean');
76+
}
77+
78+
if (isset($options['session']) && ! $options['session'] instanceof Session) {
79+
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
80+
}
81+
82+
$this->databaseName = (string) $databaseName;
83+
$this->options = $options;
84+
}
85+
86+
/**
87+
* Execute the operation.
88+
*
89+
* @see Executable::execute()
90+
* @param Server $server
91+
* @return CachingIterator
92+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
93+
*/
94+
public function execute(Server $server)
95+
{
96+
$cmd = ['listCollections' => 1];
97+
98+
if (! empty($this->options['filter'])) {
99+
$cmd['filter'] = (object) $this->options['filter'];
100+
}
101+
102+
if (isset($this->options['maxTimeMS'])) {
103+
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
104+
}
105+
106+
if (isset($this->options['nameOnly'])) {
107+
$cmd['nameOnly'] = $this->options['nameOnly'];
108+
}
109+
110+
$cursor = $server->executeReadCommand($this->databaseName, new Command($cmd), $this->createOptions());
111+
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
112+
113+
return new CachingIterator($cursor);
114+
}
115+
116+
/**
117+
* Create options for executing the command.
118+
*
119+
* Note: read preference is intentionally omitted, as the spec requires that
120+
* the command be executed on the primary.
121+
*
122+
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
123+
* @return array
124+
*/
125+
private function createOptions()
126+
{
127+
$options = [];
128+
129+
if (isset($this->options['session'])) {
130+
$options['session'] = $this->options['session'];
131+
}
132+
133+
return $options;
134+
}
135+
}

src/Database.php

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

1818
namespace MongoDB;
1919

20+
use Generator;
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;
@@ -408,6 +410,23 @@ public function getWriteConcern()
408410
return $this->writeConcern;
409411
}
410412

413+
/**
414+
* Returns the names of all collections in this database
415+
*
416+
* @see ListCollectionNames::__construct() for supported options
417+
* @param array $options
418+
* @return Generator
419+
* @throws InvalidArgumentException for parameter/option parsing errors
420+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
421+
*/
422+
public function listCollectionNames(array $options = [])
423+
{
424+
$operation = new ListCollectionNames($this->databaseName, $options);
425+
$server = select_server($this->manager, $options);
426+
427+
yield from $operation->execute($server);
428+
}
429+
411430
/**
412431
* Returns information for all collections in this database.
413432
*

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)