1
|
|
|
<?php |
2
|
|
|
namespace phpbu\App\Backup\Cleaner; |
3
|
|
|
|
4
|
|
|
use phpbu\App\Backup\Cleaner; |
5
|
|
|
use phpbu\App\Backup\Collector; |
6
|
|
|
use phpbu\App\Backup\Target; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Cleanup backup directory. |
10
|
|
|
* |
11
|
|
|
* Removes oldest backup till the given quantity isn't exceeded anymore. |
12
|
|
|
* |
13
|
|
|
* @package phpbu |
14
|
|
|
* @subpackage Backup |
15
|
|
|
* @author Sebastian Feldmann <[email protected]> |
16
|
|
|
* @copyright Sebastian Feldmann <[email protected]> |
17
|
|
|
* @license https://opensource.org/licenses/MIT The MIT License (MIT) |
18
|
|
|
* @link http://phpbu.de/ |
19
|
|
|
* @since Class available since Release 1.0.0 |
20
|
|
|
*/ |
21
|
|
|
class Quantity extends Abstraction implements Cleaner |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* Amount of backups to keep |
25
|
|
|
* |
26
|
|
|
* @var integer |
27
|
|
|
*/ |
28
|
|
|
protected $amount; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Setup the Cleaner. |
32
|
|
|
* |
33
|
|
|
* @see \phpbu\App\Backup\Cleanup::setup() |
34
|
|
|
* @param array $options |
35
|
|
|
* @throws \phpbu\App\Backup\Cleaner\Exception |
36
|
|
|
*/ |
37
|
14 |
|
public function setup(array $options) |
38
|
|
|
{ |
39
|
14 |
|
if (!isset($options['amount'])) { |
40
|
1 |
|
throw new Exception('option \'amount\' is missing'); |
41
|
|
|
} |
42
|
13 |
|
if (!is_numeric($options['amount'])) { |
43
|
1 |
|
throw new Exception(sprintf('invalid value for \'amount\': %s', $options['amount'])); |
44
|
|
|
} |
45
|
12 |
|
if ($options['amount'] < 1) { |
46
|
1 |
|
throw new Exception(sprintf('value for \'amount\' must be greater 0, %s given', $options['amount'])); |
47
|
|
|
} |
48
|
11 |
|
$this->amount = intval($options['amount']); |
49
|
11 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Return list of files to delete. |
53
|
|
|
* |
54
|
|
|
* @param \phpbu\App\Backup\Target $target |
55
|
|
|
* @param \phpbu\App\Backup\Collector $collector |
56
|
|
|
* @return \phpbu\App\Backup\File[] |
57
|
|
|
*/ |
58
|
11 |
|
protected function getFilesToDelete(Target $target, Collector $collector) |
59
|
|
|
{ |
60
|
11 |
|
$files = $collector->getBackupFiles(); |
61
|
11 |
|
$delete = []; |
62
|
|
|
|
63
|
11 |
|
if ($this->isCapacityExceeded($files)) { |
64
|
|
|
// oldest backups first |
65
|
2 |
|
ksort($files); |
66
|
|
|
|
67
|
2 |
|
while ($this->isCapacityExceeded($files)) { |
68
|
2 |
|
$file = array_shift($files); |
69
|
2 |
|
if ($file === null) { |
70
|
|
|
break; |
71
|
|
|
} |
72
|
2 |
|
$delete[] = $file; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
11 |
|
return $delete; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Returns true when the capacity is exceeded. |
81
|
|
|
* |
82
|
|
|
* @param array $files |
83
|
|
|
* @return bool |
84
|
|
|
*/ |
85
|
11 |
|
private function isCapacityExceeded(array $files) |
86
|
|
|
{ |
87
|
11 |
|
return count($files) > $this->amount; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|