Passed
Push — master ( 2cb25c...1f8869 )
by MusikAnimal
02:53
created

WikiDomainLookup::load()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App;
6
7
use GuzzleHttp\Client as GuzzleClient;
8
use Psr\Cache\CacheItemInterface;
9
use Psr\Cache\CacheItemPoolInterface;
10
11
class WikiDomainLookup
12
{
13
    /** @var GuzzleClient */
14
    private $guzzle;
15
16
    /** @var CacheItemPoolInterface */
17
    private $cache;
18
19
    private const CACHE_KEY = 'global-search-wikidomainlookup';
20
21
    /** @var string Duration of cache for lookup table, as accepted by DateInterval::createFromDateString() */
22
    private const CACHE_TIME = '10 hours';
23
24
    public function __construct(GuzzleClient $guzzle, CacheItemPoolInterface $cache)
25
    {
26
        $this->guzzle = $guzzle;
27
        $this->cache = $cache;
28
    }
29
30
    public function load(): array
31
    {
32
        $cacheItem = $this->cache->getItem(self::CACHE_KEY);
33
        $lookup = null; //$cacheItem->get();
34
        if ($lookup === null) {
0 ignored issues
show
introduced by
The condition $lookup === null is always true.
Loading history...
35
            $lookup = $this->loadUncached();
36
            $cacheItem->set($lookup)
37
                ->expiresAfter(\DateInterval::createFromDateString(self::CACHE_TIME));
38
            $this->cache->save($cacheItem);
39
        }
40
        return $lookup;
41
    }
42
43
    public function loadUncached(): array
44
    {
45
        $res = $this->guzzle->request('GET', 'https://meta.wikimedia.org/w/api.php', [
46
            'query' => [
47
                'format' => 'json',
48
                'formatversion' => 2,
49
                'action' => 'sitematrix',
50
                'smlangprop' => 'site',
51
                'smsiteprop' => 'url|dbname',
52
            ]
53
        ]);
54
        $decoded = json_decode($res->getBody()->getContents(), true)['sitematrix'];
55
        $lookup = [];
56
        foreach ($decoded as $k => $v) {
57
            if ($k === 'count') {
58
                continue;
59
            }
60
            $sites = $k === 'specials' ? $v : $v['site'];
61
            foreach ($sites as $site) {
62
                $lookup[$site['dbname']] = parse_url($site['url'], PHP_URL_HOST);
63
            }
64
        }
65
        return $lookup;
66
    }
67
}
68