MaxSizeRotator::nominate()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 38
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5.0042

Importance

Changes 0
Metric Value
dl 0
loc 38
ccs 17
cts 18
cp 0.9444
rs 8.439
c 0
b 0
f 0
cc 5
eloc 17
nc 8
nop 1
crap 5.0042
1
<?php
2
/*
3
 * This file is part of the Backup package, an RunOpenCode project.
4
 *
5
 * (c) 2015 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * This project is fork of "kbond/php-backup", for full credits info, please
11
 * view CREDITS file that was distributed with this source code.
12
 */
13
namespace RunOpenCode\Backup\Rotator;
14
15
use RunOpenCode\Backup\Contract\BackupInterface;
16
use RunOpenCode\Backup\Contract\RotatorInterface;
17
use RunOpenCode\Backup\Utils\Filesize;
18
19
/**
20
 * Class MaxSizeRotator
21
 *
22
 * Rotator that nominates old backups when total backup size exceed maximum allowed backup size.
23
 *
24
 * @package RunOpenCode\Backup\Rotator
25
 */
26
final class MaxSizeRotator implements RotatorInterface
27
{
28
    /**
29
     * @var int
30
     */
31
    private $maxSize;
32
33
    /**
34
     * @param string|int $maxSize
35
     */
36 4
    public function __construct($maxSize)
37
    {
38 4
        $this->maxSize = Filesize::getBytes($maxSize);
39 4
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 4
    public function nominate(array $backups)
45
    {
46 4
        $list = array();
47 4
        $currentSize = 0;
48
49
        /**
50
         * @var BackupInterface $backup
51
         */
52 4
        foreach ($backups as $backup) {
53 4
            $list[$backup->getCreatedAt()->getTimestamp()] = $backup;
54 4
            $currentSize += $backup->getSize();
55 2
        }
56
57 4
        if ($currentSize > $this->maxSize) {
58
59 4
            ksort($list);
60
61 4
            $nominations = array();
62
63
            /**
64
             * @var BackupInterface $backup
65
             */
66 4
            foreach ($list as $backup) {
67
68 4
                $nominations[] = $backup;
69 4
                $currentSize -= $backup->getSize();
70
71 4
                if ($currentSize <= $this->maxSize) {
72 4
                    break;
73
                }
74 2
            }
75
76 4
            return $nominations;
77
78
        } else {
79
            return array();
80
        }
81
    }
82
}
83