aboutsummaryrefslogtreecommitdiff
path: root/app/Http/Controllers/AdminImportController.php
blob: dc32cec8e60d9bf41f8b0f67f923eb6ef0365358 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

namespace App\Http\Controllers;

use App\Models\BookmarkCategory;
use App\Models\BookmarkSite;
use App\Models\GuestbookEntry;
use Exception;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminImportController extends Controller
{
    public function show() : View {
        return view('admin.import');
    }

    public function submit(Request $request)
    {
        $request->validate([
            'data_file' => 'required|mimes:json',
        ]);

        $file = $request->file('data_file');
        $jsonContent = file_get_contents($file->getRealPath());
        $data = json_decode($jsonContent, true);
        $tables = [];
        foreach($data as $item) {
            if ($item['type'] !== "table") continue;
            $tables[$item['name']] = [
                'data' => $item['data'],
                'count' => count($item['data'])
            ];

            if ($item['name'] === "guestbook__entries") {
                GuestbookEntry::importGuestbookEntry($item['data']);
            }
            $this->import($item['data'], $item['name']);
        }
        return view('admin.import-success', ['tables' => $tables]);
    }

    /**
     * Imports the given data to the specified table
     *
     * @param array $data The data to import
     * @param string $table_name The name of the table to import to
     * @return void
     * @throws Exception Invalid table specified, to be replaced with custom exception
     */
    public function import(array $data, string $table_name): void {
        switch ($table_name) {
            case 'guestbook__entries':
                GuestbookEntry::importGuestbookEntry($data);
                break;
            case 'bookmark__categories'  :
                BookmarkCategory::importBookmarkCategory($data);
                break;
            case 'bookmark__sites':
                BookmarkSite::importBookmark($data);
                break;
            case 'guestbook__bans':
                break;
            default:
                // TODO: Replace with custom exception
                throw new Exception("Invalid table specified ($table_name)");
        }
    }
}