Passed
Push — master ( b831b6...96f132 )
by John
06:04 queued 21s
created

ImportPOEM::form()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 1
b 0
f 1
1
<?php
2
3
namespace App\Admin\Forms;
4
5
use App\Models\Eloquent\ProblemModel;
6
use Encore\Admin\Widgets\Form;
7
use Illuminate\Support\MessageBag;
8
use Illuminate\Http\Request;
9
use POEM\Parser as POEMParser;
10
use Illuminate\Support\Facades\Storage;
11
use DB;
12
13
class ImportPOEM extends Form
14
{
15
    /**
16
     * The form title.
17
     *
18
     * @var string
19
     */
20
    public $title = 'Import';
21
22
    /**
23
     * Handle the form request.
24
     *
25
     * @param Request $request
26
     *
27
     * @return \Illuminate\Http\RedirectResponse
28
     */
29
    public function handle(Request $request)
30
    {
31
        $err = function ($msg) {
32
            $error = new MessageBag([
33
                'title'   => 'POEM parse failed.',
34
                'message' => $msg,
35
            ]);
36
            return back()->with(compact('error'));
37
        };
38
        $success_message = '';
39
40
        $file = $request->file('Files');
41
        if(!$file->isValid()){
42
            $err('Invalid POEM files');
43
        }
44
45
        $path      = $file->getRealPath();
46
        $poetryRaw = file_get_contents($path);
47
        $parser    = new POEMParser();
48
        $poem      = $parser->parse($poetryRaw);
0 ignored issues
show
Bug introduced by
The method parse() does not exist on POEM\Parser. Did you maybe mean parseFile()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

48
        /** @scrutinizer ignore-call */ 
49
        $poem      = $parser->parse($poetryRaw);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
49
        if(empty($poem)){
50
            $err('Malformed POEM files');
51
        }
52
53
        $success_message .= "
54
            POEM standard : {$poem['standard']} <br />
55
            generator : {$poem['generator']} <br />
56
            url : {$poem['url']} <br />
57
            description : {$poem['description']} <br />
58
            problems: <br />
59
        ";
60
61
        $memory_unit = [
62
            'kb' => 1,
63
            'mb' => 1024,
64
            'gb' => 1024*1024
65
        ];
66
        $time_unit = [
67
            'ms' => 1,
68
            's' => 1000,
69
            'm' => 60000,
70
            'h' => 3600000
71
        ];
72
73
        $prefix = 'NOJ';
74
        $p = ProblemModel::where('pcode','like',$prefix.'%')->orderBy('pcode','desc')->select('pcode')->first();
75
        if(empty($p)){
76
            $count = 1000;
77
        }else{
78
            $count = (int) str_replace($prefix,'',$p['pcode']);
79
        }
80
81
        foreach ($poem['problems'] as $problem) {
82
            //insert problem
83
            $title = $problem['title'];
84
            $pro = [
85
                'pcode'        => $prefix . (++$count),
86
                'solved_count' => 0,
87
                'difficulty'   => -1,
88
                'file'         => 0,
89
                'time_limit'   => $problem['timeLimit']['value'] * $time_unit[$problem['timeLimit']['unit']],
90
                'memory_limit' => $problem['memoryLimit']['value'] * $memory_unit[$problem['memoryLimit']['unit']],
91
                'title'        => $title,
92
                'description'  => $problem['description'],
93
                'input'        => $problem['input'],
94
                'output'       => $problem['output'],
95
                'note'         => $problem['note'],
96
                'input_type'   => 'standard input',
97
                'output_type'  => 'standard output',
98
                'OJ'           => 1,
99
                'tot_score'    => $problem['extra']['totScore'],
100
                'markdown'     => $problem['extra']['markdown'],
101
                'force_raw'    => $problem['extra']['forceRaw'],
102
                'partial'      => $problem['extra']['partial']
103
            ];
104
            $pid = ProblemModel::insertGetId($pro);
105
106
            //migrate sample
107
            $sample_count = 0;
108
            foreach($problem['sample'] as $sample){
109
                $sam = [
110
                    'pid'           => $pid,
111
                    'sample_input'  => $sample['input'],
112
                    'sample_output' => $sample['output'],
113
                ];
114
                $psid = DB::table('problem_sample')->insert($sam);
0 ignored issues
show
Unused Code introduced by
The assignment to $psid is dead and can be removed.
Loading history...
115
                $sample_count += 1;
116
            }
117
118
            //create test case file
119
            if(Storage::exists(storage_path().'/test_case/'.$pro['pcode'])){
120
                Storage::deleteDirectory(storage_path().'/test_case/'.$pro['pcode']);
121
            }
122
            Storage::makeDirectory(storage_path().'/test_case/'.$pro['pcode']);
123
            $test_case_count = 0;
124
            $test_case_info = [
125
                'spj'        => false,
126
                'test_cases' => []
127
            ];
128
            foreach($problem['testCases'] as $test_case){
129
                $test_case_count += 1;
130
                $test_case_arr = [
131
                    'input_name'  => "data{$test_case_count}.in",
132
                    'output_name' => "data{$test_case_count}.out",
133
                    'input_size'  => strlen($test_case['input']),
134
                    'output_size' => strlen($test_case['output']),
135
                    'stripped_output_md5' => md5(trim($test_case['output']))
136
                ];
137
                array_push($test_case_info['test_cases'],$test_case_arr);
138
                Storage::disk('test_case')->put('/'.$pro['pcode'].'/'.$test_case_arr['input_name'], $test_case['input']);
139
                Storage::disk('test_case')->put('/'.$pro['pcode'].'/'.$test_case_arr['output_name'], $test_case['output']);
140
            }
141
            Storage::disk('test_case')->put('/'.$pro['pcode'].'/info', json_encode($test_case_info));
142
143
            //migrate solutions
144
            $solution_count = 0;
145
            foreach($problem['solution'] as $solution) {
146
                $s = [
147
                    'uid' => 1,
148
                    'pid' => $pid,
149
                    'content' => '``` '.$solution['source'],
150
                    'audit' => 1,
151
                    'votes' => 0,
152
                    'created_at' => date('Y-m-d H:i:s')
153
                ];
154
                DB::table('problem_solution')->insert($s);
155
                $solution_count += 1;
156
            }
157
158
            $success_message .= '&nbsp;&nbsp;&nbsp;&nbsp;'.
159
                $pro['pcode'].': "
160
                '.$title.'" with
161
                '.$sample_count.' samples,
162
                '.$test_case_count.' test cases,
163
                '.$solution_count.' solutions
164
                <br />';
165
        }
166
        admin_success('Import successfully',$success_message);
167
        return back();
168
    }
169
170
    /**
171
     * Build a form here.
172
     */
173
    public function form()
174
    {
175
        $this->file('Files')->rules('required');
176
    }
177
}
178