-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathMigratePhotos.php
More file actions
367 lines (296 loc) · 12.2 KB
/
MigratePhotos.php
File metadata and controls
367 lines (296 loc) · 12.2 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
#[Signature('photos:migrate {--dry-run : Only show actions without moving or deleting files and/or folders}')]
#[Description('Migrate old photo folder structure (photos, photos-096, photos-384) into the new unified structure with original + variants')]
class MigratePhotos extends Command
{
public function handle(): int
{
$dryRun = $this->option('dry-run');
$this->info($dryRun ? 'Starting photo migration (DRY RUN)...' : 'Starting photo migration...');
$basePath = storage_path('app/public');
// Check if migration has already been run
if ($this->hasMigrationAlreadyRun($basePath)) {
$prefix = $dryRun ? '[DRY] ' : '';
$this->warn($prefix . '❌ Migration has already been completed!');
$this->warn($prefix . 'The old folder structure (photos-096 and photos-384) no longer exists.');
$this->warn($prefix . 'This command can only be run once. If you need to re-run it, restore the old folder structure first.');
return self::FAILURE;
}
if ($dryRun) {
$this->info('🔍 DRY RUN MODE: No files will be moved or deleted. Showing what would happen:');
}
// Create backups before migration
$this->createBackups($basePath, $dryRun);
$photosRoot = "{$basePath}/photos";
$photos096Root = "{$basePath}/photos-096";
$photos384Root = "{$basePath}/photos-384";
if (! is_dir($photosRoot)) {
$this->error('❌ Main photos folder not found. Cannot proceed with migration.');
return self::FAILURE;
}
$this->info('Scanning photos folder for images to migrate...');
$migratedCount = 0;
$skippedCount = 0;
// Get all files from the main photos folder (these become our originals)
foreach ($this->getAllFiles($photosRoot) as $originalPath) {
if (str_contains($originalPath, '.gitignore')) {
continue;
}
$relativePath = Str::after($originalPath, "{$photosRoot}/");
$parts = explode('/', $relativePath);
if (count($parts) < 2) {
$this->warn("⚠ Unexpected file structure: {$relativePath}");
$skippedCount++;
continue;
}
$teamId = $parts[0];
$filename = $parts[1];
$personId = Str::before($filename, '_');
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$baseFilename = pathinfo($filename, PATHINFO_FILENAME);
// Build paths for all variants
$newDir = "{$basePath}/photos/{$teamId}/{$personId}";
$newOriginalPath = "{$newDir}/{$filename}";
$newLargePath = "{$newDir}/{$baseFilename}_large.{$extension}";
$newMediumPath = "{$newDir}/{$baseFilename}_medium.{$extension}";
$newSmallPath = "{$newDir}/{$baseFilename}_small.{$extension}";
// Find corresponding files in other folders (optional)
$mediumPath = "{$photos384Root}/{$teamId}/{$filename}";
$smallPath = "{$photos096Root}/{$teamId}/{$filename}";
if ($dryRun) {
$this->line("[DRY] Processing: {$baseFilename}");
$this->line("[DRY] Original: {$originalPath} → {$newOriginalPath}");
$this->line("[DRY] Large: {$originalPath} → {$newLargePath}");
if (file_exists($mediumPath)) {
$this->line("[DRY] Medium: {$mediumPath} → {$newMediumPath}");
} else {
$this->line('[DRY] Medium: ⚠ Not found, skipping');
}
if (file_exists($smallPath)) {
$this->line("[DRY] Small: {$smallPath} → {$newSmallPath}");
} else {
$this->line('[DRY] Small: ⚠ Not found, skipping');
}
$migratedCount++;
} else {
// Create directory if needed
if (! is_dir($newDir)) {
mkdir($newDir, 0755, true);
}
// Copy original file (no suffix)
copy($originalPath, $newOriginalPath);
// Copy original as large variant
copy($originalPath, $newLargePath);
// Copy medium if exists
if (file_exists($mediumPath)) {
copy($mediumPath, $newMediumPath);
unlink($mediumPath);
}
// Copy small if exists
if (file_exists($smallPath)) {
copy($smallPath, $newSmallPath);
unlink($smallPath);
}
// Delete original after successful copy
unlink($originalPath);
$this->line("✔ Migrated: {$baseFilename}");
$migratedCount++;
}
}
// Cleanup old folders
if (! $dryRun) {
if (is_dir($photos096Root)) {
$this->cleanupFolder($photos096Root, false);
}
if (is_dir($photos384Root)) {
$this->cleanupFolder($photos384Root, false);
}
} else {
$this->line("[DRY] Would cleanup: {$photos096Root}");
$this->line("[DRY] Would cleanup: {$photos384Root}");
}
$this->newLine();
$this->info('✅ Migration completed!');
$this->info(" Photos migrated: {$migratedCount}");
if ($skippedCount > 0) {
$this->warn(" Photos skipped: {$skippedCount}");
}
if ($dryRun) {
$this->newLine();
$this->info('💡 This was a DRY RUN. Run without --dry-run to perform actual migration.');
} else {
$this->newLine();
$this->info('💡 Migration successful! Your photos are now organized in the new structure.');
$this->info(' - Originals are preserved as .webp files');
$this->info(' - Large, medium, and small variants are created');
$this->info(' - Old folder structure has been cleaned up');
}
return self::SUCCESS;
}
/**
* Check if the migration has already been run by verifying if the old folders exist
*/
private function hasMigrationAlreadyRun(string $basePath): bool
{
$photos096Exists = is_dir("{$basePath}/photos-096");
$photos384Exists = is_dir("{$basePath}/photos-384");
// If both folders are missing, migration has likely been completed
return ! $photos096Exists && ! $photos384Exists;
}
/**
* @return array<int, string>
*/
private function getAllFiles(string $dir): array
{
$files = [];
if (! is_dir($dir)) {
return $files;
}
foreach (scandir($dir) as $teamId) {
if (in_array($teamId, ['.', '..'])) {
continue;
}
$teamPath = "{$dir}/{$teamId}";
if (! is_dir($teamPath)) {
continue;
}
foreach (scandir($teamPath) as $file) {
if (in_array($file, ['.', '..']) || $file === '.gitignore') {
continue;
}
// Only process actual image files
$extension = mb_strtolower(pathinfo($file, PATHINFO_EXTENSION));
$validExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'svg'];
if (! in_array($extension, $validExtensions)) {
continue;
}
$files[] = "{$teamPath}/{$file}";
}
}
return $files;
}
private function cleanupFolder(string $folderPath, bool $dryRun = false): void
{
if (! is_dir($folderPath)) {
return;
}
if ($dryRun) {
$this->line("[DRY] Would delete folder and contents: {$folderPath}");
return;
}
$globResult = glob("{$folderPath}/*");
$remainingFiles = array_filter(
$globResult !== false ? $globResult : [],
fn ($file) => basename($file) !== '.gitignore'
);
foreach ($remainingFiles as $item) {
if (is_dir($item)) {
$this->deleteDirectory($item);
} elseif (is_file($item)) {
unlink($item);
}
}
// Delete .gitignore if present
$gitignore = "{$folderPath}/.gitignore";
if (is_file($gitignore)) {
unlink($gitignore);
}
// Remove folder if empty
if (count(scandir($folderPath)) <= 2) {
@rmdir($folderPath);
$this->line("🧹 Deleted folder: {$folderPath}");
} else {
$this->warn("⚠ Not removing {$folderPath}, still contains files.");
}
}
private function deleteDirectory(string $dir): void
{
$globVisible = glob("{$dir}/*");
$globHidden = glob("{$dir}/.*");
$items = array_merge(
$globVisible !== false ? $globVisible : [],
$globHidden !== false ? $globHidden : []
);
foreach ($items as $item) {
$basename = basename($item);
if (in_array($basename, ['.', '..'])) {
continue;
}
if (is_file($item)) {
// Delete all files including .gitignore
unlink($item);
} elseif (is_dir($item)) {
// Recursively clean subdirectories
$this->deleteDirectory($item);
}
}
@rmdir($dir);
}
/**
* Create timestamped backups of existing photo folders
*/
private function createBackups(string $basePath, bool $dryRun = false): void
{
$timestamp = date('Y-m-d_H-i-s');
$backupRoot = "{$basePath}/photo-backups/{$timestamp}";
$foldersToBackup = ['photos', 'photos-096', 'photos-384'];
$hasBackups = false;
foreach ($foldersToBackup as $folderName) {
$sourcePath = "{$basePath}/{$folderName}";
$backupPath = "{$backupRoot}/{$folderName}";
if (! is_dir($sourcePath)) {
continue;
}
if ($dryRun) {
$this->line("[DRY] Would create backup: {$sourcePath} → {$backupPath}");
$hasBackups = true;
continue;
}
// Create backup directory structure
if (! is_dir($backupRoot)) {
mkdir($backupRoot, 0755, true);
}
// Copy entire folder structure
$this->copyDirectory($sourcePath, $backupPath);
$this->line("📦 Created backup: {$folderName} → photo-backups/{$timestamp}/{$folderName}");
$hasBackups = true;
}
if ($hasBackups) {
$prefix = $dryRun ? '[DRY] ' : '';
$this->info("{$prefix}✅ Backup completed. Files saved to: photo-backups/{$timestamp}/");
} else {
$this->warn('⚠ No folders found to backup.');
}
}
/**
* Recursively copy a directory and all its contents
*/
private function copyDirectory(string $source, string $destination): void
{
if (! is_dir($destination)) {
mkdir($destination, 0755, true);
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
$targetPath = $destination . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
if ($item->isDir()) {
if (! is_dir($targetPath)) {
mkdir($targetPath, 0755, true);
}
} else {
copy($item->getRealPath(), $targetPath);
}
}
}
}