/** * Saves file to a random folder * @param \stdClass $fileData, example: * object(stdClass)[82] * public 'name' => string 'SampleVideo_1080x720_20mb (1).mp4' (length=33) * public 'size' => int 21069678 * public 'type' => string 'video/mp4' (length=9) * public 'extension' => string 'mp4' (length=3) * * @return int File record id * @author Alex Makhorin */ public function saveFileToStorage($fileData) { $tmpFilePath = $this->tmpDirectory . $fileData->name; $randomDir = $this->generateRandomDirectory($fileData->name); $randomName = $this->generateRandomName(); $newPath = $this->storageDirectory . $randomDir . '/' . $randomName . '.' . $fileData->extension; $this->createFolders($newPath); rename($tmpFilePath, $newPath); $url = $this->storageUrl . $randomDir . '/' . $randomName . '.' . $fileData->extension; if (strpos($fileData->type, 'video/') === 0) { $type = FileType::TYPE_VIDEO; } elseif (strpos($fileData->type, 'image/') === 0) { $type = FileType::TYPE_IMAGE; } else { is_file($newPath) && unlink($newPath); throw new HttpException(400, 'No data to handle'); } $file = new File(); $file->file_type = $type; $file->mime_type = $fileData->type; $file->url = $url; $isSaved = $file->save(); if (!$isSaved) { throw new HttpException(500, 'DB error occured: ' . \yii\helpers\VarDumper::dumpAsString($file->getErrors())); } return $file->primaryKey; }