IndexInput.php 2.39 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Model;

5
use MongoDB\BSON\Serializable;
6
use MongoDB\Exception\InvalidArgumentException;
7
use MongoDB\Exception\InvalidArgumentTypeException;
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

/**
 * Index input model class.
 *
 * This class is used to validate user input for index creation.
 *
 * @internal
 * @see MongoDB\Collection::createIndexes()
 * @see https://github.com/mongodb/specifications/blob/master/source/enumerate-indexes.rst
 * @see http://docs.mongodb.org/manual/reference/method/db.collection.createIndex/
 */
class IndexInput implements Serializable
{
    private $index;

    /**
    * Constructor.
    *
    * @param array $index Index specification
    */
    public function __construct(array $index)
    {
        if ( ! isset($index['key'])) {
            throw new InvalidArgumentException('Required "key" document is missing from index specification');
        }

        if ( ! is_array($index['key']) && ! is_object($index['key'])) {
35
            throw new InvalidArgumentTypeException('"key" option', $index['key'], 'array or object');
36 37
        }

38
        foreach ($index['key'] as $fieldName => $order) {
39
            if ( ! is_int($order) && ! is_float($order) && ! is_string($order)) {
40
                throw new InvalidArgumentTypeException(sprintf('order value for "%s" field within "key" option', $fieldName), $order, 'numeric or string');
41 42 43 44 45 46 47 48
            }
        }

        if ( ! isset($index['ns'])) {
            throw new InvalidArgumentException('Required "ns" option is missing from index specification');
        }

        if ( ! is_string($index['ns'])) {
49
            throw new InvalidArgumentTypeException('"ns" option', $index['ns'], 'string');
50 51 52
        }

        if ( ! isset($index['name'])) {
53
            $index['name'] = \MongoDB\generate_index_name($index['key']);
54 55 56
        }

        if ( ! is_string($index['name'])) {
57
            throw new InvalidArgumentTypeException('"name" option', $index['name'], 'string');
58 59 60 61 62 63
        }

        $this->index = $index;
    }

    /**
64
     * Return the index name.
65
     *
66
     * @param string
67
     */
68
    public function __toString()
69
    {
70
        return $this->index['name'];
71 72 73
    }

    /**
74
     * Serialize the index information to BSON for index creation.
75
     *
76
     * @see MongoDB\Collection::createIndexes()
77 78
     * @see http://php.net/mongodb-bson-serializable.bsonserialize
     * @return array
79
     */
80
    public function bsonSerialize()
81
    {
82
        return $this->index;
83 84
    }
}