Count.php 5.17 KB
Newer Older
1 2 3 4 5
<?php

namespace MongoDB\Operation;

use MongoDB\Driver\Command;
6
use MongoDB\Driver\ReadConcern;
7
use MongoDB\Driver\ReadPreference;
8 9 10 11 12 13 14 15 16 17 18 19 20
use MongoDB\Driver\Server;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Exception\UnexpectedValueException;

/**
 * Operation for the count command.
 *
 * @api
 * @see MongoDB\Collection::count()
 * @see http://docs.mongodb.org/manual/reference/command/count/
 */
class Count implements Executable
{
21 22
    private static $wireVersionForReadConcern = 4;

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
    private $databaseName;
    private $collectionName;
    private $filter;
    private $options;

    /**
     * Constructs a count command.
     *
     * Supported options:
     *
     *  * hint (string|document): The index to use. If a document, it will be
     *    interpretted as an index specification and a name will be generated.
     *
     *  * limit (integer): The maximum number of documents to count.
     *
     *  * maxTimeMS (integer): The maximum amount of time to allow the query to
     *    run.
     *
41 42 43 44 45
     *  * readConcern (MongoDB\Driver\ReadConcern): Read concern.
     *
     *    For servers < 3.2, this option is ignored as read concern is not
     *    available.
     *
46 47
     *  * readPreference (MongoDB\Driver\ReadPreference): Read preference.
     *
48 49 50
     *  * skip (integer): The number of documents to skip before returning the
     *    documents.
     *
51 52 53 54
     * @param string       $databaseName   Database name
     * @param string       $collectionName Collection name
     * @param array|object $filter         Query by which to filter documents
     * @param array        $options        Command options
55 56
     * @throws InvalidArgumentException
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
57
    public function __construct($databaseName, $collectionName, $filter = [], array $options = [])
58
    {
59
        if ( ! is_array($filter) && ! is_object($filter)) {
60
            throw InvalidArgumentException::invalidType('$filter', $filter, 'array or object');
61 62
        }

63 64
        if (isset($options['hint'])) {
            if (is_array($options['hint']) || is_object($options['hint'])) {
65
                $options['hint'] = \MongoDB\generate_index_name($options['hint']);
66 67 68
            }

            if ( ! is_string($options['hint'])) {
69
                throw InvalidArgumentException::invalidType('"hint" option', $options['hint'], 'string or array or object');
70 71 72 73
            }
        }

        if (isset($options['limit']) && ! is_integer($options['limit'])) {
74
            throw InvalidArgumentException::invalidType('"limit" option', $options['limit'], 'integer');
75 76 77
        }

        if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
78
            throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
79 80
        }

81
        if (isset($options['readConcern']) && ! $options['readConcern'] instanceof ReadConcern) {
82
            throw InvalidArgumentException::invalidType('"readConcern" option', $options['readConcern'], 'MongoDB\Driver\ReadConcern');
83 84
        }

85
        if (isset($options['readPreference']) && ! $options['readPreference'] instanceof ReadPreference) {
86
            throw InvalidArgumentException::invalidType('"readPreference" option', $options['readPreference'], 'MongoDB\Driver\ReadPreference');
87 88
        }

89
        if (isset($options['skip']) && ! is_integer($options['skip'])) {
90
            throw InvalidArgumentException::invalidType('"skip" option', $options['skip'], 'integer');
91 92 93 94 95 96 97 98 99 100 101 102 103 104
        }

        $this->databaseName = (string) $databaseName;
        $this->collectionName = (string) $collectionName;
        $this->filter = $filter;
        $this->options = $options;
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
     * @return integer
105
     * @throws UnexpectedValueException if the command response was malformed
106 107 108
     */
    public function execute(Server $server)
    {
109 110
        $readPreference = isset($this->options['readPreference']) ? $this->options['readPreference'] : null;

111
        $cursor = $server->executeCommand($this->databaseName, $this->createCommand($server), $readPreference);
112 113
        $result = current($cursor->toArray());

114
        // Older server versions may return a float
115 116
        if ( ! isset($result->n) || ! (is_integer($result->n) || is_float($result->n))) {
            throw new UnexpectedValueException('count command did not return a numeric "n" value');
117 118
        }

119
        return (integer) $result->n;
120 121 122 123 124
    }

    /**
     * Create the count command.
     *
125
     * @param Server $server
126 127
     * @return Command
     */
128
    private function createCommand(Server $server)
129
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
130
        $cmd = ['count' => $this->collectionName];
131 132 133 134 135

        if ( ! empty($this->filter)) {
            $cmd['query'] = (object) $this->filter;
        }

Jeremy Mikola's avatar
Jeremy Mikola committed
136
        foreach (['hint', 'limit', 'maxTimeMS', 'skip'] as $option) {
137 138 139 140 141
            if (isset($this->options[$option])) {
                $cmd[$option] = $this->options[$option];
            }
        }

142 143 144 145
        if (isset($this->options['readConcern']) && \MongoDB\server_supports_feature($server, self::$wireVersionForReadConcern)) {
            $cmd['readConcern'] = \MongoDB\read_concern_as_document($this->options['readConcern']);
        }

146 147 148
        return new Command($cmd);
    }
}