Ejemplo n.º 1
0
 public function storeAttachmentByFile($databaseName, Document $doc, $attachmentId, $attachmentFilePath, $contentType = null)
 {
     if (!file_exists($attachmentFilePath) || !is_readable($attachmentFilePath)) {
         throw new AttachmentFileIsNotReadableException(sprintf('the file "%s" is not readable', $attachmentFilePath));
     }
     if ($attachmentId === null) {
         $attachmentId = basename($attachmentFilePath);
     }
     if ($contentType == null) {
         $fileInfo = pathinfo($attachmentFilePath);
         if (!isset($fileInfo['extension'])) {
             throw new \RuntimeException('can`t detect the conntent type form a file without file extension');
         }
         switch ($fileInfo['extension']) {
             case 'png':
             case 'jpg':
             case 'jpeg':
             case 'gif':
                 $contentType = 'image/' . $ending;
                 break;
             case 'txt':
             case 'text':
                 $contentType = 'text/plain';
                 break;
             default:
                 throw new \RuntimeException(sprintf('can`t detect the conntent type for "%s"', $fileInfo['extension']));
         }
     }
     $fileSize = filesize($attachmentFilePath);
     $parameters = array('rev' => $doc->get('_rev'));
     $uriOptions = array('database' => $databaseName, 'docId' => $doc->get('_id'), 'attachmentId' => $attachmentId, 'parameters' => array_merge($parameters, $this->getRequestParameters()));
     $uri = $this->buildUri($uriOptions);
     $request = $this->getRequest();
     $request->setUri($uri);
     $request->setMethod($request::METHOD_PUT);
     $request->setContent(fopen($attachmentFilePath, 'r'));
     $request->getHeaders()->addHeaderLine('Content-Type', $contentType);
     $request->getHeaders()->addHeaderLine('Content-Length', $fileSize);
     $response = $this->sendRequest();
     if (!is_string($response) && isset($response->error)) {
         throw $this->createExceptionInstance($response, $uriOptions, array('uri' => $uri));
     }
     $doc->updateRev($response->rev);
     return $response;
 }