Completed
Push — master ( 33476c...427ebd )
by Bertrand
09:14
created

ImportAllPagesFromWiki::handle()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 16
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 24
rs 9.7333
1
<?php
2
3
4
namespace App\Console\Commands;
5
6
use App\Src\UseCases\Domain\Ports\PageRepository;
7
use App\Src\UseCases\Infra\Sql\Model\PageModel;
8
use GuzzleHttp\Client;
9
use Illuminate\Console\Command;
10
11
class ImportAllPagesFromWiki extends Command
12
{
13
    protected $signature = 'pages:import-all';
14
15
    protected $description = 'Import all pages from the wiki';
16
17
18
    public function __construct()
19
    {
20
        parent::__construct();
21
    }
22
23
    public function handle()
24
    {
25
        $httpClient = new Client();
26
        $queryPages = '?action=query&generator=allpages&gaplimit=500&gapfilterredir=nonredirects&format=json';
27
28
        $pagesApiUri = config('wiki.api_uri').$queryPages;
29
        $response = $httpClient->get($pagesApiUri);
30
        $content = json_decode($response->getBody()->getContents(), true);
31
32
        $pages = $content['query']['pages'];
33
34
        $this->handlePages($pages);
35
        $continue = $content['continue']['gapcontinue'];
36
37
        while($continue !== null && $continue !== ''){
38
            $this->info($continue);
39
40
            $pagesApiUri = config('wiki.api_uri').$queryPages.'&gapcontinue='.$continue;
41
            $response = $httpClient->get($pagesApiUri);
42
            $content = json_decode($response->getBody()->getContents(), true);
43
            $pages = $content['query']['pages'];
44
            $this->handlePages($pages);
45
46
            $continue = $content['continue']['gapcontinue'] ?? null;
47
        }
48
    }
49
50
    private function handlePages($pages)
51
    {
52
        foreach ($pages as $page) {
53
            $pageModel = PageModel::where('page_id', $page['pageid'])->first();
54
            if (!isset($pageModel)) {
55
                $pageModel = new PageModel();
56
            }
57
            $pageModel->page_id = $page['pageid'];
58
            $pageModel->dry = true;
59
            $pageModel->title = $page['title'];
60
            $pageModel->save();
61
        }
62
    }
63
}
64