1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SimpleImageManager\Managers; |
4
|
|
|
|
5
|
|
|
trait CanDelete |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* List of deleted configuration formats. |
9
|
|
|
* Useful if you deleted some configuration but still files exists for old created files |
10
|
|
|
* and you need do delete these formats on delete file. |
11
|
|
|
* |
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
public array $deletedFormats = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Clear empty directory after deletion files. |
18
|
|
|
* Warning: this function is memory and time-consuming when there can be too many files. |
19
|
|
|
* |
20
|
|
|
* @var bool |
21
|
|
|
*/ |
22
|
|
|
public bool $truncateDir = false; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param array $formats |
26
|
|
|
* |
27
|
|
|
* @return $this |
28
|
|
|
*/ |
29
|
17 |
|
public function setDeletedFormats(array $formats = []): static |
30
|
|
|
{ |
31
|
17 |
|
$this->deletedFormats = $formats; |
32
|
|
|
|
33
|
17 |
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @param bool $truncateDir |
38
|
|
|
* @return $this |
39
|
|
|
*/ |
40
|
17 |
|
public function truncateDir(bool $truncateDir = true): static |
41
|
|
|
{ |
42
|
17 |
|
$this->truncateDir = $truncateDir; |
43
|
|
|
|
44
|
17 |
|
return $this; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Get files list with all formats to delete. |
49
|
|
|
* |
50
|
|
|
* @param string $fileName |
51
|
|
|
* @return array |
52
|
|
|
*/ |
53
|
7 |
|
protected function filesToDelete(string $fileName): array |
54
|
|
|
{ |
55
|
7 |
|
if (!$fileName) { |
56
|
1 |
|
return []; |
57
|
|
|
} |
58
|
|
|
|
59
|
6 |
|
$filesToDelete = [ |
60
|
6 |
|
$fileName, |
61
|
6 |
|
]; |
62
|
|
|
|
63
|
6 |
|
[$name, $extension] = $this->explodeFilename($fileName); |
|
|
|
|
64
|
|
|
|
65
|
6 |
|
foreach (array_keys($this->formats) as $format) { |
66
|
6 |
|
$filesToDelete[] = "{$name}-{$format}.{$extension}"; |
67
|
|
|
} |
68
|
|
|
|
69
|
6 |
|
foreach ($this->deletedFormats as $format) { |
70
|
5 |
|
$filesToDelete[] = "{$name}-{$format}.{$extension}"; |
71
|
|
|
} |
72
|
|
|
|
73
|
6 |
|
return array_unique($filesToDelete); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Clear empty directory if this is required. |
78
|
|
|
* |
79
|
|
|
* @param string $fileName |
80
|
|
|
* @return bool |
81
|
|
|
*/ |
82
|
6 |
|
protected function truncateDirectory(string $fileName): bool |
83
|
|
|
{ |
84
|
6 |
|
if (!$this->truncateDir) { |
85
|
2 |
|
return false; |
86
|
|
|
} |
87
|
|
|
|
88
|
4 |
|
$directoryName = dirname($fileName); |
89
|
|
|
|
90
|
|
|
if ( |
91
|
4 |
|
!$directoryName || |
92
|
4 |
|
!empty($this->storage()->allFiles($directoryName)) |
|
|
|
|
93
|
|
|
) { |
94
|
2 |
|
return false; |
95
|
|
|
} |
96
|
|
|
|
97
|
2 |
|
return $this->storage()->deleteDirectory($directoryName); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|