Skip to content

Commit

Permalink
Merge pull request #60 from viljums/master
Browse files Browse the repository at this point in the history
older than uses months now, added messages
  • Loading branch information
uldisn authored Oct 14, 2021
2 parents 3d3dcfa + eaff6fb commit ea1f428
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,13 +343,13 @@ D3filesModel::createCopy($fileModelId, Users::class, $model->id);

### Maintenance commands

Soft delete
Soft deletes files (sets deleted=0)

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

Deletes files and corresponding records in database
Deletes files and corresponding records in database which have deleted=0

```bash
d3files/remove-files full/model/name
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
<?php


namespace d3yii2\d3files\commands;
namespace d3yii2\d3files\controllers;

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

class CleanFilesController extends Controller
class CleanFilesController extends D3CommandController
{

/**
* 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'
* older than number of months
*
* @param $modelName
* @param $date
* @param $months
* @throws \ReflectionException
* @throws \Throwable
* @throws \yii\db\StaleObjectException
*
* @return int
*/
public function actionRemoveOlderThan($modelName, $date)
public function actionRemoveOlderThan($modelName, $months)
{
$date = date('Y-m-d', strtotime('-'.$months.' month'));

$oldFiles = D3filesModel::find()
->innerJoin('d3files', '`d3files`.`id` = `d3files_model`.`d3files_id`')
Expand Down Expand Up @@ -63,6 +62,8 @@ public function actionRemoveFiles($modelName)
->where(['deleted' => 1])
->all();

$this->stdout('Deleting ' . count($deletedFiles) . ' file models.');

foreach ($deletedFiles as $fileModel) {

$file = $fileModel->getD3files()->one();
Expand All @@ -78,14 +79,17 @@ public function actionRemoveFiles($modelName)
$filePath = $fileHandler->getFilePath();
$fileModel->delete();

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

$file->delete();

if (file_exists($filePath)) {
unlink($filePath);
}
} else {
$this->stdout('Can\'t delete file ' . $file->file_name . ', in use with model: '. $usedModel->id);
}

}

return 0;
Expand Down

0 comments on commit ea1f428

Please sign in to comment.