public function attachFile($filePath, $owner)
{
if (empty($owner->id)) {
throw new Exception('Parent model must have ID when you attaching a file');
}
if (!file_exists($filePath)) {
throw new Exception("File {$filePath} not exists");
}
$fileHash = md5(microtime(true) . $filePath);
$fileType = pathinfo($filePath, PATHINFO_EXTENSION);
$newFileName = "{$fileHash}.{$fileType}";
$fileDirPath = $this->getFilesDirPath($fileHash);
$newFilePath = $fileDirPath . DIRECTORY_SEPARATOR . $newFileName;
if (!copy($filePath, $newFilePath)) {
throw new Exception("Cannot copy file! {$filePath} to {$newFilePath}");
}
$file = new File();
$file->name = pathinfo($filePath, PATHINFO_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 {
return false;
}
}