-
Notifications
You must be signed in to change notification settings - Fork 684
Expand file tree
/
Copy pathDeleteEmptyVolumeFoldersController.php
More file actions
94 lines (82 loc) · 2.61 KB
/
DeleteEmptyVolumeFoldersController.php
File metadata and controls
94 lines (82 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\console\controllers\utils;
use Craft;
use craft\console\Controller;
use craft\db\Query;
use craft\db\Table;
use yii\console\ExitCode;
/**
* Deletes empty volume folders.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 4.14.0
*/
class DeleteEmptyVolumeFoldersController extends Controller
{
/**
* @var string|null The volume handle(s) to delete folders from. Can be set to multiple comma-separated volumes.
*/
public ?string $volume = null;
/**
* @inheritdoc
*/
public function options($actionID): array
{
return [
...parent::options($actionID),
'volume',
];
}
/**
* Deletes empty volume folders.
*
* @return int
*/
public function actionIndex(): int
{
$query = (new Query())
->select(['folders.id'])
->from(['folders' => Table::VOLUMEFOLDERS])
->leftJoin(['assets' => Table::ASSETS], '[[assets.folderId]] = [[folders.id]]')
->leftJoin(['subfolders' => Table::VOLUMEFOLDERS], '[[subfolders.parentId]] = [[folders.id]]')
->where([
'assets.id' => null,
'subfolders.id' => null,
])
->andWhere(['not', ['folders.parentId' => null]])
->andWhere(['not', ['folders.path' => null]]);
if ($this->volume) {
$volumeHandles = explode(',', $this->volume);
$volumeIds = [];
$volumesService = Craft::$app->getVolumes();
foreach ($volumeHandles as $handle) {
$volume = $volumesService->getVolumeByHandle($handle);
if (!$volume) {
$this->stderr("Invalid volume handle: $handle\n");
return ExitCode::UNSPECIFIED_ERROR;
}
$volumeIds[] = $volume->id;
}
$query->andWhere(['folders.volumeId' => $volumeIds]);
}
$emptyFolderIds = $query->column();
if (empty($emptyFolderIds)) {
$this->stdout("No empty folders found.\n");
return ExitCode::OK;
}
$message = sprintf(
'Deleting %s empty %s',
count($emptyFolderIds),
count($emptyFolderIds) === 1 ? 'folder' : 'folders',
);
$this->do($message, function() use ($emptyFolderIds) {
Craft::$app->getAssets()->deleteFoldersByIds($emptyFolderIds);
});
return ExitCode::OK;
}
}