private function ensureDocumentHasMongoId(&$document)
{
$checkKeys = function ($array) {
foreach (array_keys($array) as $key) {
if (empty($key) && $key !== 0) {
throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
}
}
};
if (is_array($document)) {
if (!isset($document['_id'])) {
$document['_id'] = new \MongoId();
}
$checkKeys($document);
return $document['_id'];
} elseif (is_object($document)) {
$reflectionObject = new \ReflectionObject($document);
foreach ($reflectionObject->getProperties() as $property) {
if (!$property->isPublic()) {
throw new \MongoException('zero-length keys are not allowed, did you use $ with double quotes?');
}
}
if (!isset($document->_id)) {
$document->_id = new \MongoId();
}
$checkKeys((array) $document);
return $document->_id;
}
return null;
}