Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class FileShardingCommand
- extends EConsoleCommand
- {
- public function actionIndex()
- {
- $transaction = \Yii::app()->db->beginTransaction();
- try
- {
- while (true)
- {
- $sql = <<<SQL
- SELECT * FROM tbl_file WHERE migration_status is null or migration_status = '';
- SQL;
- $file = File::model()->findBySql($sql);
- if (!$file)
- {
- exit;
- }
- $file->prepareUpdateList()
- ->setPlainField('migration_status', 'in_progress')
- ->apply();
- $fileName = $this->getFileName($file->id);
- $filePath = $this->getFilePath($fileName);
- if ($newFilePath = $this->saveFile($file, $filePath))
- {
- $file->prepareUpdateList()
- ->setPlainField('migration_status', 'done')
- ->setPlainField('spec', $this->makeSpec($newFilePath))
- ->apply();
- echo "ok";
- $transaction->commit();
- }
- else
- {
- continue;
- }
- }
- }
- catch (Throwable $e)
- {
- $transaction->rollback();
- throw $e;
- }
- }
- public function makeSpec(string $newFilePath):string
- {
- return str_replace(\Yii::app()->env->get(\env\files_path), 'file:%files_path%', $newFilePath);
- }
- public function getFileName(int $id): string
- {
- $id = (string)$id;
- $idLength = strlen($id);
- $fileNameLength = 12;
- $zeroNum = $fileNameLength - $idLength;
- if (0 === $zeroNum)
- {
- return strrev($id);
- }
- return strrev(str_repeat("0", $zeroNum) . $id);
- }
- public function getFilePath(string $fileName): string
- {
- return \Yii::app()->env->get(\env\files_path) . DIRECTORY_SEPARATOR .
- substr($fileName, 0, 3) . DIRECTORY_SEPARATOR .
- substr($fileName, 3, 3) . DIRECTORY_SEPARATOR .
- substr($fileName, 6, 3) . DIRECTORY_SEPARATOR .
- substr($fileName, 9, 3);
- }
- public function saveFile(File $file, string $newFilePath)
- {
- $oldFilePath = $file->getHandler()->getPathname();
- if (!file_exists($oldFilePath))
- {
- $file->prepareUpdateList()
- ->setPlainField('migration_status', 'error')
- ->apply();
- return;
- }
- $oldHash = hash_file('md5', $file->getHandler()->getPathname());
- if (is_dir($newFilePath))
- {
- $newFilePath = $newFilePath . DIRECTORY_SEPARATOR . $this->getFileNameToSave($file);
- if (file_exists($newFilePath))
- {
- throw new RuntimeException('уже есть такой файл');
- }
- if (copy($oldFilePath, $newFilePath) && hash_file('md5', $newFilePath) === $oldHash)
- {
- return $newFilePath;
- }
- }
- else
- {
- if (mkdir($newFilePath, '0777', true))
- {
- $newFilePath = $newFilePath . DIRECTORY_SEPARATOR . $this->getFileNameToSave($file);
- if (copy($oldFilePath, $newFilePath) && hash_file('md5', $newFilePath) === $oldHash)
- {
- unlink($oldFilePath);
- @unlink($file->getSourcePathName());
- return $newFilePath;
- }
- }
- }
- return false;
- }
- public function getFileNameToSave(File $file)
- {
- $nameArray = explode('/', $file->getPathname());
- return array_pop($nameArray);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement