public function createIndex($keys, array $options = [])
{
if (is_string($keys)) {
if (empty($keys)) {
throw new MongoException('empty string passed as key field');
}
$keys = [$keys => 1];
}
if (is_object($keys)) {
$keys = (array) $keys;
}
if (!is_array($keys) || !count($keys)) {
throw new MongoException('index specification has no elements');
}
if (!isset($options['name'])) {
$options['name'] = \MongoDB\generate_index_name($keys);
}
$indexes = iterator_to_array($this->collection->listIndexes());
$indexCount = count($indexes);
$collectionExists = true;
$indexExists = false;
// listIndexes returns 0 for non-existing collections while the legacy driver returns 1
if ($indexCount === 0) {
$collectionExists = false;
$indexCount = 1;
}
foreach ($indexes as $index) {
if ($index->getKey() === $keys || $index->getName() === $options['name']) {
$indexExists = true;
break;
}
}
try {
foreach (['w', 'wTimeoutMS', 'safe', 'timeout', 'wtimeout'] as $invalidOption) {
if (isset($options[$invalidOption])) {
unset($options[$invalidOption]);
}
}
$this->collection->createIndex($keys, $options);
} catch (\MongoDB\Driver\Exception\Exception $e) {
throw ExceptionConverter::toLegacy($e, 'MongoResultException');
}
$result = ['createdCollectionAutomatically' => !$collectionExists, 'numIndexesBefore' => $indexCount, 'numIndexesAfter' => $indexCount, 'note' => 'all indexes already exist', 'ok' => 1.0];
if (!$indexExists) {
$result['numIndexesAfter']++;
unset($result['note']);
}
return $result;
}