Skip to content

Commit b95723e

Browse files
committed
Auto remove old backup files
1 parent 70666e9 commit b95723e

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

app/Lio/Backup/BackupManager.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
namespace Lio\Backup;
3+
4+
use Illuminate\Support\Collection;
5+
use League\Flysystem\Filesystem;
6+
7+
class BackupManager
8+
{
9+
/**
10+
* @var \League\Flysystem\Filesystem
11+
*/
12+
private $filesystem;
13+
14+
/**
15+
* @param \League\Flysystem\Filesystem $filesystem
16+
*/
17+
public function __construct(Filesystem $filesystem)
18+
{
19+
$this->filesystem = $filesystem;
20+
}
21+
22+
/**
23+
* Remove old backups based on their timestamps
24+
*
25+
* @param int $keep The amount of backup files to keep
26+
* @return array
27+
*/
28+
public function removeOldBackups($keep = 5)
29+
{
30+
// Get all the files from the backup folder
31+
$files = new Collection($this->filesystem->listFiles());
32+
33+
// Sort the backup files by their creation date.
34+
$files->sortBy(function ($file) {
35+
return $this->filesystem->getTimestamp($file);
36+
});
37+
38+
// Slice the old backup files off from the amount to keep.
39+
$filesToDelete = $files->slice($keep);
40+
41+
// Delete all the old backup files.
42+
foreach ($filesToDelete as $file) {
43+
$this->filesystem->delete($file);
44+
}
45+
46+
// Return the files which were deleted.
47+
return $filesToDelete->toArray();
48+
}
49+
}

spec/Lio/Backup/BackupManagerSpec.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
namespace spec\Lio\Backup;
3+
4+
use League\Flysystem\Filesystem;
5+
use PhpSpec\ObjectBehavior;
6+
7+
class BackupManagerSpec extends ObjectBehavior
8+
{
9+
function let(Filesystem $filesystem)
10+
{
11+
$this->beConstructedWith($filesystem);
12+
}
13+
14+
function it_is_initializable()
15+
{
16+
$this->shouldHaveType('Lio\Backup\BackupManager');
17+
}
18+
19+
function it_can_remove_old_backups(Filesystem $filesystem)
20+
{
21+
$files = ['foo.sql', 'foo1.sql', 'foo2.sql', 'foo3.sql', 'foo4.sql', 'foo5.sql', 'foo6.sql'];
22+
23+
$filesystem->listFiles()->willReturn($files);
24+
$filesystem->getTimestamp('foo.sql')->willReturn(100);
25+
$filesystem->getTimestamp('foo1.sql')->willReturn(10000);
26+
$filesystem->getTimestamp('foo2.sql')->willReturn(100);
27+
$filesystem->getTimestamp('foo3.sql')->willReturn(100);
28+
$filesystem->getTimestamp('foo4.sql')->willReturn(500);
29+
$filesystem->getTimestamp('foo5.sql')->willReturn(100);
30+
$filesystem->getTimestamp('foo6.sql')->willReturn(100);
31+
$filesystem->delete('foo1.sql')->shouldBeCalled();
32+
$filesystem->delete('foo4.sql')->shouldBeCalled();
33+
34+
$this->removeOldBackups(5)->willReturn(['foo1.sql', 'foo4.sql']);
35+
}
36+
}

0 commit comments

Comments
 (0)