private function buildFileDocument(FileDocument $document, $file, $original)
    {
        $now = new \DateTime();

        // If only a file is posted, check if there is a original object and clone it
        if ($file && $original && !$document->getMetadata()) {
            $document = clone $original;
        }

        // Basic Metadata update
        $metadata = $document->getMetadata() ?: new FileMetadataEmbedded();

        // File related, if no file uploaded we keep original file info.
        if ($file) {
            $hash = $metadata->getHash();
            if (!$hash || strlen($hash)>64) {
                $hash = hash('sha256', file_get_contents($file->getRealPath()));
            } else {
                $hash = preg_replace('/[^a-z0-9_-]/i', '-', $hash);
            }
            $metadata->setHash($hash);
            $metadata->setMime($file->getMimeType());
            $metadata->setSize($file->getSize());
            if (!$metadata->getFilename()) {
                $fileName = $file->getClientOriginalName() ? $file->getClientOriginalName() : $file->getFilename();
                $fileName = preg_replace("/[^a-zA-Z0-9.]/", "-", $fileName);
                $metadata->setFilename($fileName);
            }
        } elseif ($original && ($originalMetadata = $original->getMetadata())) {
            if (!$metadata->getFilename()) {
                $metadata->setFilename($originalMetadata->getFilename());
            }
            $metadata->setHash($originalMetadata->getHash());
            $metadata->setMime($originalMetadata->getMime());
            $metadata->setSize($originalMetadata->getSize());
        }

        // Creation date. keep original if available
        if ($original && $original->getMetadata() && $original->getMetadata()->getCreatedate()) {
            $metadata->setCreatedate($original->getMetadata()->getCreatedate());
        } else {
            $metadata->setCreatedate($now);
        }

        $metadata->setModificationdate($now);
        $document->setMetadata($metadata);

        return $document;
    }