mirror of
https://github.com/henrywhitaker3/Speedtest-Tracker.git
synced 2025-12-27 15:41:39 +01:00
Added methods to generate a backup in CSV
This commit is contained in:
@@ -3,14 +3,43 @@
|
||||
namespace App\Helpers;
|
||||
|
||||
use App\Speedtest;
|
||||
use DateTime;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class BackupHelper {
|
||||
public static function backup()
|
||||
public static function backup($format = 'json')
|
||||
{
|
||||
$data = Speedtest::get();
|
||||
$timestamp = new DateTime();
|
||||
$timestamp = $timestamp->format('Y-m-d_H:i:s');
|
||||
$name = 'speedtest_backup_' . $timestamp;
|
||||
|
||||
return $data;
|
||||
switch($format) {
|
||||
case 'csv':
|
||||
$data = Speedtest::get();
|
||||
|
||||
$csv = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix() . $name . '.csv';
|
||||
$name = $name . '.csv';
|
||||
$handle = fopen($csv, 'w+');
|
||||
fputcsv($handle, array('id', 'ping', 'download', 'upload', 'created_at', 'updated_at'));
|
||||
|
||||
foreach($data as $d) {
|
||||
fputcsv($handle, array($d->id, $d->ping, $d->download, $d->upload, $d->created_at, $d->updated_at));
|
||||
}
|
||||
|
||||
fclose($handle);
|
||||
|
||||
break;
|
||||
case 'json':
|
||||
default:
|
||||
$data = Speedtest::get()->toJson();
|
||||
$name = $name . '.json';
|
||||
Storage::disk('local')->put($name, $data);
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
public static function restore($array)
|
||||
|
||||
@@ -10,15 +10,19 @@ use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class BackupController extends Controller
|
||||
{
|
||||
public function backup()
|
||||
public function backup(Request $request)
|
||||
{
|
||||
$data = BackupHelper::backup();
|
||||
$timestamp = new DateTime();
|
||||
$timestamp = $timestamp->format('Y-m-d_H:i:s');
|
||||
$name = 'speedtest_backup_' . $timestamp . '.json';
|
||||
Storage::disk('local')->put($name, $data);
|
||||
$validator = Validator::make($request->all(), [ 'format' => 'in:json,csv' ]);
|
||||
if($validator->fails()) {
|
||||
return response()->json([
|
||||
'method' => 'backup data',
|
||||
'error' => $validator->errors(),
|
||||
], 422);
|
||||
}
|
||||
|
||||
return Storage::disk('local')->download($name);
|
||||
$filename = BackupHelper::backup($request->format);
|
||||
|
||||
return Storage::disk('local')->download($filename);
|
||||
}
|
||||
|
||||
public function restore(Request $request)
|
||||
|
||||
Reference in New Issue
Block a user