Sokil\Mongo\Collection::initIndexes PHP Method

initIndexes() public method

Create indexes based on self::$_index metadata
public initIndexes ( ) : Collection
return Collection
    public function initIndexes()
    {
        // read index definition from collection options
        // if not specified - use defined in property
        $indexDefinition = $this->definition->getOption('index');
        // ensure indexes
        foreach ($indexDefinition as $options) {
            if (empty($options['keys'])) {
                throw new Exception('Keys not specified');
            }
            $keys = $options['keys'];
            unset($options['keys']);
            if (is_string($keys)) {
                $keys = array($keys => 1);
            }
            $this->getMongoCollection()->createIndex($keys, $options);
        }
        return $this;
    }

Usage Example

Example #1
0
 /**
  * @expectedException \Sokil\Mongo\Exception
  * @expectedExceptionMessage Keys not specified
  */
 public function testInitIndexes_KeysNotSpecified()
 {
     $reflection = new \ReflectionClass($this->collection);
     $property = $reflection->getProperty('definition');
     $property->setAccessible(true);
     $definition = $property->getValue($this->collection);
     $definition->setOption('index', array(array('unique' => true)));
     $this->collection->initIndexes();
     $indexes = $this->collection->getIndexes();
     $this->assertEquals(array('asc' => 1, 'desc' => -1), $indexes[1]['key']);
     $this->assertArrayHasKey('unique', $indexes[1]);
 }