Completed
Push — master ( 8eb905...4f1d49 )
by Sebastian
03:16
created

Outdated::cleanup()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4
Metric Value
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.2
cc 4
eloc 9
nc 4
nop 3
crap 4
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
use phpbu\App\Result;
8
use phpbu\App\Util\Str;
9
use RuntimeException;
10
11
/**
12
 * Cleanup backup directory.
13
 *
14
 * Removes all files older then a given offset.
15
 *
16
 * @package    phpbu
17
 * @subpackage Backup
18
 * @author     Sebastian Feldmann <[email protected]>
19
 * @copyright  Sebastian Feldmann <[email protected]>
20
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
21
 * @link       http://phpbu.de/
22
 * @since      Class available since Release 1.0.0
23
 */
24
class Outdated extends Abstraction implements Simulator
25
{
26
    /**
27
     * Original XML value
28
     *
29
     * @var string
30
     */
31
    protected $offsetRaw;
32
33
    /**
34
     * Offset in seconds.
35
     *
36
     * @var integer
37
     */
38
    protected $offsetSeconds;
39
40
    /**
41
     * Setup the Cleaner.
42
     *
43
     * @see    \phpbu\App\Backup\Cleanup::setup()
44
     * @param  array $options
45
     * @throws \phpbu\App\Backup\Cleaner\Exception
46
     */
47 7
    public function setup(array $options)
48
    {
49 7
        if (!isset($options['older'])) {
50 1
            throw new Exception('option \'older\' is missing');
51
        }
52
        try {
53 6
            $seconds = Str::toTime($options['older']);
54 6
        } catch (RuntimeException $e) {
55 3
            throw new Exception($e->getMessage());
56
        }
57 3
        $this->offsetRaw     = $options['older'];
58 3
        $this->offsetSeconds = $seconds;
59 3
    }
60
61
    /**
62
     * Return list of files to delete.
63
     *
64
     * @param  \phpbu\App\Backup\Target    $target
65
     * @param  \phpbu\App\Backup\Collector $collector
66
     * @return \phpbu\App\Backup\File[]
67
     */
68
    protected function getFilesToDelete(Target $target, Collector $collector)
69
    {
70 3
        $minTime = time() - $this->offsetSeconds;
71
        $files   = $collector->getBackupFiles();
72 3
        $delete  = [];
73 3
74
        /** @var \phpbu\App\Backup\File $file */
75
        foreach ($files as $file) {
76 3
            // last mod date < min date? delete!
77
            if ($file->getMTime() < $minTime) {
78 3
                $delete[] = $file;
79 2
            }
80 1
        }
81
82 1
        return $delete;
83 1
    }
84
}
85