Create the document database for a mapped class.

@param string $documentName
@throws \InvalidArgumentException
771540
public function createDocumentDatabase($documentName)
    {
        $class = $this->dm->getClassMetadata($documentName);
        if ($class->isMappedSuperclass || $class->isEmbeddedDocument) {
            throw new \InvalidArgumentException('Cannot delete document indexes for mapped super classes or embedded documents.');
        }
        $this->dm->getDocumentDatabase($documentName)->execute("function() { return true; }");
    }
1131869
private function processDocument(
        $className,
        array $doctrineMapping,
        \DOMElement $serializerMapping = null,
        array $schemaMapping = null
    ) {
        if ($serializerMapping === null) {
            $serializerFields = [];
        } else {
            $serializerFields = array_reduce(
                $this->getSerializerFields($serializerMapping),
                function (array $fields, array $field) {
                    $fields[$field['fieldName']] = $field;
                    return $fields;
                },
                []
            );
        }

        if ($schemaMapping === null) {
            $schemaFields = [];
        } else {
            $schemaFields = $schemaMapping;
        }

        $fields = [];
        foreach ($this->getDoctrineFields($doctrineMapping) as $doctrineField) {
            $serializerField = isset($serializerFields[$doctrineField['name']]) ?
                $serializerFields[$doctrineField['name']] :
                null;
            $schemaField = isset($schemaFields[$doctrineField['name']]) ?
                $schemaFields[$doctrineField['name']] :
                null;

            if ($doctrineField['type'] === 'collection') {
                $fields[] = new ArrayField(
                    $serializerField === null ? 'array<string>' : $serializerField['fieldType'],
                    $doctrineField['name'],
                    $serializerField === null ? $doctrineField['name'] : $serializerField['exposedName'],
                    !isset($schemaField['readOnly']) ? false : $schemaField['readOnly'],
                    ($schemaField === null || !isset($schemaField['required'])) ? false : $schemaField['required'],
                    !isset($schemaField['recordOriginException']) ? false : $schemaField['recordOriginException'],
                    !isset($schemaField['restrictions']) ? [] : $schemaField['restrictions']
                );
            } else {
                $fields[] = new Field(
                    $doctrineField['type'],
                    $doctrineField['name'],
                    $serializerField === null ? $doctrineField['name'] : $serializerField['exposedName'],
                    !isset($schemaField['readOnly']) ? false : $schemaField['readOnly'],
                    ($schemaField === null || !isset($schemaField['required'])) ? false : $schemaField['required'],
                    $serializerField === null ? false : $serializerField['searchable'],
                    !isset($schemaField['recordOriginException']) ? false : $schemaField['recordOriginException'],
                    !isset($schemaField['restrictions']) ? [] : $schemaField['restrictions']
                );
            }
        }
        foreach ($this->getDoctrineEmbedOneFields($doctrineMapping) as $doctrineField) {
            $serializerField = isset($serializerFields[$doctrineField['name']]) ?
                $serializerFields[$doctrineField['name']] :
                null;
            $schemaField = isset($schemaFields[$doctrineField['name']]) ?
                $schemaFields[$doctrineField['name']] :
                null;

            $fields[] = new EmbedOne(
                $this->getDocument($doctrineField['type']),
                $doctrineField['name'],
                $serializerField === null ? $doctrineField['name'] : $serializerField['exposedName'],
                !isset($schemaField['readOnly']) ? false : $schemaField['readOnly'],
                ($schemaField === null || !isset($schemaField['required'])) ? false : $schemaField['required'],
                !isset($schemaField['recordOriginException']) ? false : $schemaField['recordOriginException'],
                !isset($schemaField['restrictions']) ? [] : $schemaField['restrictions']
            );
        }
        foreach ($this->getDoctrineEmbedManyFields($doctrineMapping) as $doctrineField) {
            $serializerField = isset($serializerFields[$doctrineField['name']]) ?
                $serializerFields[$doctrineField['name']] :
                null;
            $schemaField = isset($schemaFields[$doctrineField['name']]) ?
                $schemaFields[$doctrineField['name']] :
                null;

            $fields[] = new EmbedMany(
                $this->getDocument($doctrineField['type']),
                $doctrineField['name'],
                $serializerField === null ? $doctrineField['name'] : $serializerField['exposedName'],
                !isset($schemaField['readOnly']) ? false : $schemaField['readOnly'],
                ($schemaField === null || !isset($schemaField['required'])) ? false : $schemaField['required'],
                !isset($schemaField['recordOriginException']) ? false : $schemaField['recordOriginException'],
                !isset($schemaField['restrictions']) ? [] : $schemaField['restrictions']
            );
        }

        $doc = new Document($className, $fields);

        // stuff that belongs to the whole document
        if (isset($schemaMapping['_base']['solr']['fields'])) {
            $doc->setSolrFields($schemaMapping['_base']['solr']['fields']);
        }
        if (isset($schemaMapping['_base']['solr']['aggregate'])) {
            $doc->setSolrAggregate($schemaMapping['_base']['solr']['aggregate']);
        }

        return $doc;
    }
1257623
public function mCreateDocument($documents, array $options = [])
    {
        if (!is_array($documents)) {
            throw new InvalidArgumentException('Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)');
        }

        $documents = array_map(function ($document) {
            return $document instanceof Document ? $document->serialize() : $document;
        }, $documents);

        $data = ['body' => ['documents' => $documents]];

        $response = $this->kuzzle->query(
            $this->buildQueryArgs('document', 'mCreate'),
            $this->kuzzle->addHeaders($data, $this->headers),
            $options
        );

        return $response['result'];
    }
90178
public function deleteGeneratorTablesFor($documentName)
    {
        $class  = $this->dm->getClassMetadata($documentName);
        $tables = $this->getGeneratorTablesFor($class);

        foreach ($tables as $tableName => $definition) {
            $this->doCreateTable($tableName, $definition);
        }
    }
1309966
public function getDatabase(string $name): Database
    {
        if (!array_key_exists($name, $this->databases)) {
            throw new InvalidArgumentException('Database '.$name.' not added');
        }

        return $this->databases[$name];
    }
1355015
private function createCollection(DocumentManager $documentManager, ClassMetadata $classMetadata, $collectionName)
    {

        $database = $documentManager->getDatabase();

        $exists = false;
        foreach ($database->listCollections() as $collection) {
            if ($collection->getName() == $collectionName) {
                $exists = true;
            }
        }

        $creationOptions = $classMetadata->getCollectionCreationOptions();
        if (!empty($creationOptions) && !$exists) {
            $database->createCollection($collectionName, $creationOptions);
        }

        $collectionOptions = $classMetadata->getCollectionOptions();

        return $database->selectCollection($collectionName, $collectionOptions);
    }
1016470
public function ensureDocumentSharding($documentName, array $indexOptions = array())
    {
        $class = $this->dm->getClassMetadata($documentName);
        if ( ! $class->isSharded()) {
            return;
        }

        $this->enableShardingForDbByDocumentName($documentName);

        do {
            $result = $this->runShardCollectionCommand($documentName);
            $done = true;
            $try = 0;

            if ($result['ok'] != 1 && isset($result['proposedKey'])) {
                $this->dm->getDocumentCollection($documentName)->ensureIndex($result['proposedKey'], $indexOptions);
                $done = false;
                $try++;
            }
        } while (!$done && $try < 2);

        if ($result['ok'] != 1 && $result['errmsg'] !== 'already sharded') {
            throw MongoDBException::failedToEnsureDocumentSharding($documentName, $result['errmsg']);
        }
    }
190204
public function setDocumentType($documentType)
    {
    	if (!in_array($documentType, self::getDocumentTypeValues())) {
    		throw new \InvalidArgumentException(
				sprintf('Invalid value for document.documentType : %s.', $documentType)
    		);
    	}
    	
        $this->documentType = $documentType;
    
        return $this;
    }
1119212
public function setDefaultRepositoryClassName($className): void
    {
        $reflectionClass = new \ReflectionClass($className);

        if (! $reflectionClass->implementsInterface(DocumentRepositoryInterface::class)) {
            throw new InvalidDocumentRepositoryException($className);
        }

        $this->defaultRepositoryClassName = $className;
    }
997556
public function createDocumentCollection(string $documentName, ?int $maxTimeMs = null, ?WriteConcern $writeConcern = null) : void
    {
        $class = $this->dm->getClassMetadata($documentName);

        if ($class->isMappedSuperclass || $class->isEmbeddedDocument || $class->isQueryResultDocument) {
            throw new InvalidArgumentException('Cannot create document collection for mapped super classes, embedded documents or query result documents.');
        }

        if ($class->isFile) {
            $options = $this->getWriteOptions($maxTimeMs, $writeConcern);

            $this->dm->getDocumentDatabase($documentName)->createCollection($class->getBucketName() . '.files', $options);
            $this->dm->getDocumentDatabase($documentName)->createCollection($class->getBucketName() . '.chunks', $options);

            return;
        }

        $options = [
            'capped' => $class->getCollectionCapped(),
            'size' => $class->getCollectionSize(),
            'max' => $class->getCollectionMax(),
        ];

        $this->dm->getDocumentDatabase($documentName)->createCollection(
            $class->getCollection(),
            $this->getWriteOptions($maxTimeMs, $writeConcern, $options)
        );
    }
521221
private function getPropertyInfo(string $propertyName, string $className): stdClass
    {
        foreach ($this->getProperties($className) as $property) {
            if ($property->{'hydra:title'} === $propertyName) {
                return $property;
            }
        }

        throw new \InvalidArgumentException(sprintf('Property "%s" of class "%s" does\'nt exist', $propertyName, $className));
    }
654698
public function prepareAssociatedDocumentValue(PropertyMetadata $mapping, $document, $includeNestedCollections = false)
    {
        if ($document === null) {
            return Type::getNull();
        }

        if ($mapping->embedded) {
            return $this->prepareEmbeddedDocumentValue($mapping, $document, $includeNestedCollections);
        }

        if ($mapping->reference) {
            $class      = $this->dm->getClassMetadata(get_class($document));
            $identifier = $class->createIdentifier($document);

            return $this->prepareReferencedDocumentValue($mapping, $identifier);
        }

        throw new \InvalidArgumentException('Mapping is neither embedded nor reference.');
    }
63790
protected function createRepository(DocumentManagerInterface $dm, $documentName)
    {
        $metadata = $dm->getClassMetadata($documentName);
        $repositoryClassName = $metadata->customRepositoryClassName;

        if ($repositoryClassName === null) {
            $configuration = $dm->getConfiguration();
            $repositoryClassName = $configuration->getDefaultRepositoryClassName();
        }

        return new $repositoryClassName($dm, $metadata);
    }
754875
private function runShardCollectionCommand($documentName)
    {
        $class = $this->dm->getClassMetadata($documentName);
        $dbName = $this->dm->getDocumentDatabase($documentName)->getName();
        $shardKey = $class->getShardKey();
        $adminDb = $this->dm->getConnection()->selectDatabase('admin');

        $result = $adminDb->command(
            array(
                'shardCollection' => $dbName . '.' . $class->getCollection(),
                'key'             => $shardKey['keys']
            ),
            $shardKey['options']
        );

        return $result;
    }
158498
public function getDocumentBucket(string $className) : Bucket
    {
        $className = $this->classNameResolver->getRealClass($className);

        /** @var ClassMetadata $metadata */
        $metadata = $this->metadataFactory->getMetadataFor($className);
        if (! $metadata->isFile) {
            throw MongoDBException::documentBucketOnlyAvailableForGridFSFiles($className);
        }

        $bucketName = $metadata->getBucketName();

        if (! $bucketName) {
            throw MongoDBException::documentNotMappedToCollection($className);
        }

        if (! isset($this->documentBuckets[$className])) {
            $db = $this->getDocumentDatabase($className);

            $options = ['bucketName' => $bucketName];
            if ($metadata->readPreference !== null) {
                $options['readPreference'] = new ReadPreference($metadata->readPreference, $metadata->readPreferenceTags);
            }

            $this->documentBuckets[$className] = $db->selectGridFSBucket($options);
        }

        return $this->documentBuckets[$className];
    }
209403
public function dropDocumentCollection($documentName)
    {
        $class = $this->dm->getClassMetadata($documentName);
        if ($class->isMappedSuperclass || $class->isEmbeddedDocument) {
            throw new \InvalidArgumentException('Cannot delete document indexes for mapped super classes or embedded documents.');
        }
        $this->dm->getDocumentDatabase($documentName)->dropCollection(
            $class->getCollection()
        );
    }
59132
public function getDocumentCollection($className)
    {
        $className = ltrim($className, '\\');

        $metadata = $this->metadataFactory->getMetadataFor($className);
        $collectionName = $metadata->getCollection();

        if ( ! $collectionName) {
            throw MongoDBException::documentNotMappedToCollection($className);
        }

        if ( ! isset($this->documentCollections[$className])) {
            $db = $this->getDocumentDatabase($className);

            $this->documentCollections[$className] = $metadata->isFile()
                ? $db->getGridFS($collectionName)
                : $db->selectCollection($collectionName);
        }

        $collection = $this->documentCollections[$className];

        if ($metadata->slaveOkay !== null) {
            $collection->setSlaveOkay($metadata->slaveOkay);
        }

        return $this->documentCollections[$className];
    }