TopicMigration::transform()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 31
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 26
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 31
rs 9.1928
1
<?php
2
3
namespace App\Console\Commands\Migrations;
4
5
use App\Entities\Reply;
6
use App\Entities\Topic;
7
use App\Services\UserService;
8
9
class TopicMigration extends Migration
10
{
11
    public function handle($command)
12
    {
13
        $command->info('Migrating Topic...');
14
        $this->table('topic')->orderBy('tid', 'asc')->chunk(100, function ($items) {
15
            foreach ($items as $item) {
16
                $this->transform($item);
17
            }
18
        });
19
        $command->info('Migrating Topic Done');
20
    }
21
22
    private function transform($item)
23
    {
24
        $topic = new Topic();
25
        $topic->id = $item->tid;
26
        $topic->title = $item->title;
27
        $topic->contest_id = $item->cid;
28
        $topic->problem_id = $item->pid;
29
        if (! $topic->contest_id) {
30
            $topic->contest_id = 0;
31
        }
32
        $user = app(UserService::class)->findByName($item->author_id);
33
        $topic->user_id = $user->id;
34
        $topic->save();
35
36
        $replies = $this->table('reply')->where('topic_id', $item->tid)->orderBy('rid', 'asc')->get();
37
        $isFirst = true;
38
        foreach ($replies as $reply) {
39
            if ($isFirst && $item->author_id === $reply->author_id) {
40
                $topic->content = $reply->content;
41
                $topic->created_at = $reply->time;
42
                $topic->save();
43
                $isFirst = false;
44
                continue;
45
            }
46
            $newReply = new Reply();
47
            $newReply->topic_id = $topic->id;
48
            $newReply->created_at = $reply->time;
49
            $newReply->content = $reply->content;
50
            $author = app(UserService::class)->findByName($reply->author_id);
51
            $newReply->user_id = $author->id;
52
            $newReply->save();
53
        }
54
    }
55
}
56