Ejemplo n.º 1
0
 /**
  * @param $filePath string
  * @param $owner
  * @return bool|File
  * @throws \Exception
  * @throws \yii\base\InvalidConfigException
  */
 public function attachFile($filePath, $owner)
 {
     if (!$owner->id) {
         throw new \Exception('Owner must have id when you attach file');
     }
     if (!file_exists($filePath)) {
         throw new \Exception('File not exist :' . $filePath);
     }
     $fileHash = md5(microtime(true) . $filePath);
     $fileType = pathinfo($filePath, PATHINFO_EXTENSION);
     $fileName = pathinfo($filePath, PATHINFO_FILENAME);
     $newFileName = $fileHash . '.' . $fileType;
     $fileDirPath = $this->getFilesDirPath($fileHash);
     $newFilePath = $fileDirPath . DIRECTORY_SEPARATOR . $newFileName;
     copy($filePath, $newFilePath);
     if (!file_exists($filePath)) {
         throw new \Exception('Cannot copy file! ' . $filePath . ' to ' . $newFilePath);
     }
     $file = new File();
     $file->name = $fileName;
     $file->model = $this->getShortClass($owner);
     $file->itemId = $owner->id;
     $file->hash = $fileHash;
     $file->size = filesize($filePath);
     $file->type = $fileType;
     $file->mime = FileHelper::getMimeType($filePath);
     if ($file->save()) {
         unlink($filePath);
         return $file;
     } else {
         if (count($file->getErrors()) > 0) {
             $errors = $file->getErrors();
             $ar = array_shift($errors);
             unlink($newFilePath);
             throw new \Exception(array_shift($ar));
         }
         return false;
     }
 }