Skip to content

Commit

Permalink
Merge pull request #59 from viljums/master
Browse files Browse the repository at this point in the history
Added maintenance command
  • Loading branch information
uldisn authored Oct 8, 2021
2 parents 782e00a + afa4055 commit 3d3dcfa
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,20 @@ $model = Users::findOne($id);
D3filesModel::createCopy($fileModelId, Users::class, $model->id);
```

### Maintenance commands

Soft delete

```bash
d3files/remove-older-than full/model/name yyyy-mm-dd
```

Deletes files and corresponding records in database

```bash
d3files/remove-files full/model/name
```

### Change log
- 0.9.0 (Feb 26, 2017) - added RU translation
- 0.9.3 (May 29, 2017) - auto creating upload directories
Expand Down
94 changes: 94 additions & 0 deletions commands/CleanFilesController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php


namespace d3yii2\d3files\commands;

use yii\console\Controller;
use d3yii2\d3files\models\D3filesModel;
use d3yii2\d3files\components\FileHandler;

class CleanFilesController extends Controller
{

/**
* soft deletes all the file models older than date provided
*
* date must be in format yyyy-mm-dd
* example:
* date -d '-3 year' '+%Y-%d-%m'
*
* @param $modelName
* @param $date
* @throws \ReflectionException
* @throws \Throwable
* @throws \yii\db\StaleObjectException
*
* @return int
*/
public function actionRemoveOlderThan($modelName, $date)
{

$oldFiles = D3filesModel::find()
->innerJoin('d3files', '`d3files`.`id` = `d3files_model`.`d3files_id`')
->innerJoin(['d3files_model_name', '`d3file_model_name`.id = `d3files_model`.`model_name_id'])
->where(['`d3files_model_name`.`name`' => $modelName ])
->andWhere(['deleted' => 0])
->andWhere(['<', '`add_datetime`', $date ])
->all()
;

$this->stdout('Deleting ' . count($oldFiles) . ' files.');

foreach ($oldFiles as $file) {

$file->deleted = 1;
$file->save();
}

return 0;
}

/**
* deletes all files saved under the model name
* with value "deleted = 1"
*
* @param $modelName
* @throws \ReflectionException
*
* @return int
*/
public function actionRemoveFiles($modelName)
{
$deletedFiles = D3filesModel::find()
->where(['deleted' => 1])
->all();

foreach ($deletedFiles as $fileModel) {

$file = $fileModel->getD3files()->one();

$fileHandler = new FileHandler(
[
'model_name' => $modelName,
'model_id' => $fileModel->d3files_id,
'file_name' => $file->file_name,
]
);

$filePath = $fileHandler->getFilePath();
$fileModel->delete();

if (!D3filesModel::findOne(['d3files_id' => $file->id])) {

$file->delete();

if (file_exists($filePath)) {
unlink($filePath);
}
}
}

return 0;
}

}

0 comments on commit 3d3dcfa

Please sign in to comment.