ptut-vhost/build/api/module/departement/saveController.php

94 lines
1.8 KiB
PHP

<?php
/**
* Created by PhpStorm.
* User: lucas
* Date: 15/03/18
* Time: 15:50
*/
namespace api\module\departement;
use database\core\Repo;
use database\repo\departement;
use Ifsnop\Mysqldump\Mysqldump;
class saveController
{
private $backupPath = "";
private function initDir(string $dbName){
if(!is_dir(__BACKUP__."/$dbName/")){
mkdir(__BACKUP__."/$dbName/");
}
$this->backupPath =__BACKUP__."/$dbName/";
}
private function scandir(string $path) : array {
//scan the directory
$arr = scandir($path);
//strip the useless "." and ".."
unset($arr[0],$arr[1]);
//make the arry start at 0 again
$arr = array_values($arr);
return $arr;
}
public function get($args){
$this->initDir($_SESSION["CurrentDatabase"]);
//strip extensions
$backupNames = array_map(function($e){
return pathinfo($e, PATHINFO_FILENAME);
}, $this->scandir($this->backupPath));
return ["data" => $backupNames];
}
public function post($args){
$this->initDir($_SESSION["CurrentDatabase"]);
$backupName = "";
extract($args);
//if the backup name is empty we create it
if($backupName == ""){
try {
$conf = Repo::getDBConfig();
$dump = new Mysqldump("mysql:host={$conf["host"]};dbname={$conf["dbname"]}", $conf["username"], $conf["password"],
[
"compress" => Mysqldump::GZIP
]);
$date = date("Y-W-d");
$dump->start($this->backupPath.$date.".sql");
return ["success" => true,"backupName" => $date];
} catch (\Exception $e) {
return ["success" => false];
}
}else{
//read the backup
ob_start();
readgzfile($this->backupPath.$backupName.".sql");
$sql = ob_get_clean();
/** @var departement $depRepo */
$depRepo = Repo::getRepo("departement");
$depRepo->restore($sql);
return ["success" => true];
}
}
}