Ejemplo n.º 1
0
 /**
  * สร้าง record(document) ของ  document ใหม่ จากข้อมูลที่ระบุ
  * @param int $entity
  * @param string $refId
  * @param string $documentPath path ของไฟล์ต้นทาง
  * @param string $mode รูปแบบการ move file [upload, cp]
  * @return void|Document
  */
 public function newItem($entity, $refId, $documentPath, $documentName, $mode = 'upload')
 {
     if (!file_exists($documentPath)) {
         return;
     }
     $model = Entity::getInstance($entity, $refId);
     if ($model == null) {
         return;
     }
     $itemNo = \yii::$app->db->createCommand("select max(itemNo) from Document\n    \t\t\twhere type=:type and refId=:id", ['type' => $entity, 'id' => $refId])->queryScalar();
     $itemNo++;
     $finfo = finfo_open(FILEINFO_MIME_TYPE);
     // return mime type ala mimetype extension
     $mime = finfo_file($finfo, $documentPath);
     finfo_close($finfo);
     $document = new Document();
     $document->type = $entity;
     $document->refId = $refId;
     $document->itemNo = $itemNo;
     $document->status = Workflow::STATUS_PUBLISHED;
     $document->mime = $mime;
     $document->fileName = $documentName;
     $arr = explode(".", $documentName);
     $extension = $arr[count($arr) - 1];
     $document->srcPath = date('Y/m/d', strtotime($model->createTime)) . "/{$refId}_{$itemNo}.{$extension}";
     $retries = 0;
     do {
         try {
             if ($document->save()) {
                 break;
             }
         } catch (Exception $ex) {
             $document->itemNo++;
             $document->srcPath = date('Y/m/d', strtotime($model->createTime)) . "/{$refId}_{$document->itemNo}.{$extension}";
             $retries++;
             usleep(1000);
         }
     } while ($retries < 10);
     if ($retries >= 10) {
         $document = null;
     }
     if (!empty($document)) {
         $destination = $document->getFullPath();
         if (!is_readable(dirname($destination))) {
             mkdir(dirname($destination), 0755, true);
         }
         if ($mode == 'cp') {
             copy($documentPath, $destination);
         } elseif ($mode == 'mv') {
             rename($documentPath, $destination);
         } else {
             move_uploaded_file($documentPath, $destination);
         }
     }
     return $document;
 }