Add Backupper class

This commit is contained in:
Giuseppe Criscione 2018-09-18 22:07:07 +02:00
parent df5dc5130f
commit 041e781b5a
3 changed files with 95 additions and 0 deletions

80
admin/src/Backupper.php Normal file
View File

@ -0,0 +1,80 @@
<?php
namespace Formwork\Admin;
use Formwork\Core\Formwork;
use Formwork\Utils\FileSystem;
use ZipArchive;
class Backupper
{
const DATE_FORMAT = 'YmdHis';
protected $options;
public function __construct($options = array())
{
$this->options = array_merge($this->defaults(), $options);
}
public function defaults()
{
return array(
'maxExecutionTime' => 180,
'name' => 'formwork-backup',
'path' => Formwork::instance()->option('backup.path'),
'ignore' => array(
'.git/*',
'*.DS_Store',
'*.gitignore',
'*.gitkeep',
'admin/node_modules/*',
'backup/*'
)
);
}
public function backup()
{
$previousMaxExecutionTime = ini_set('max_execution_time', $this->options['maxExecutionTime']);
$source = ROOT_PATH;
$path = $this->options['path'];
if (!FileSystem::exists($this->options['path'])) {
FileSystem::createDirectory($this->options['path'], true);
}
$destination = $path . $this->options['name'] . '-' . date(self::DATE_FORMAT) . '.zip';
$files = FileSystem::scanRecursive($source, true);
$files = array_filter($files, function ($item) use ($source) {
return $this->isCopiable(substr($item, strlen($source)));
});
$zip = new ZipArchive();
if ($zip->open($destination, ZipArchive::CREATE)) {
foreach ($files as $file) {
$zip->addFile($file, substr($file, strlen($source)));
}
$zip->close();
}
if ($previousMaxExecutionTime !== false) {
ini_set('max_execution_time', $previousMaxExecutionTime);
}
return $destination;
}
protected function isCopiable($file)
{
foreach ($this->options['ignore'] as $pattern) {
if (fnmatch($pattern, $file)) {
return false;
}
}
return true;
}
}

View File

@ -86,6 +86,7 @@ class Formwork
'cache.enabled' => false,
'cache.path' => ROOT_PATH . 'cache' . DS,
'cache.time' => 604800,
'backup.path' => ROOT_PATH . 'backup' . DS,
'admin.enabled' => true,
'admin.lang' => 'en',
'admin.logout_redirect' => 'login'

View File

@ -300,6 +300,20 @@ class FileSystem
return $items;
}
public static function scanRecursive($path, $all = false)
{
$list = array();
$path = static::normalize($path);
foreach (FileSystem::scan($path, $all) as $item) {
if (FileSystem::isDirectory($path . $item)) {
$list = array_merge($list, static::scanRecursive($path . $item, $all));
} else {
$list[] = $path . $item;
}
}
return $list;
}
public static function listFiles($path = null, $all = false)
{
$path = static::normalize($path);