public function ensureDocumentSharding($documentName, array $indexOptions = array())
{
$class = $this->dm->getClassMetadata($documentName);
if (!$class->isSharded()) {
return;
}
$this->enableShardingForDbByDocumentName($documentName);
$try = 0;
do {
$result = $this->runShardCollectionCommand($documentName);
$done = true;
// Need to check error message because MongoDB 3.0 does not return a code for this error
if ($result['ok'] != 1 && strpos($result['errmsg'], 'please create an index that starts') !== false) {
// The proposed key is not returned when using mongo-php-adapter with ext-mongodb.
// See https://github.com/mongodb/mongo-php-driver/issues/296 for details
if (isset($result['proposedKey'])) {
$key = $result['proposedKey'];
} else {
$key = $this->dm->getClassMetadata($documentName)->getShardKey()['keys'];
}
$this->dm->getDocumentCollection($documentName)->ensureIndex($key, $indexOptions);
$done = false;
$try++;
}
} while (!$done && $try < 2);
// Starting with MongoDB 3.2, this command returns code 20 when a collection is already sharded.
// For older MongoDB versions, check the error message
if ($result['ok'] == 1 || isset($result['code']) && $result['code'] == 20 || $result['errmsg'] == 'already sharded') {
return;
}
throw MongoDBException::failedToEnsureDocumentSharding($documentName, $result['errmsg']);
}