Completed
Push — master ( 1b316c...8fba66 )
by Albert
02:34
created

HttpsXkcdRepository::getRandom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
ccs 0
cts 11
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nastoletni\Code\Infrastructure;
6
7
use Nastoletni\Code\Domain\Xkcd;
8
use Nastoletni\Code\Domain\XkcdRepository;
9
10
class HttpsXkcdRepository implements XkcdRepository
11
{
12
    private const XKCD_URL = 'https://xkcd.com/%d/';
13
    private const XKCD_JSON_URL = 'https://xkcd.com/%d/info.0.json';
14
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function getRandom(): Xkcd
19
    {
20
        // 1851th is the last xkcd's comic available at the time of writing this.
21
        $number = random_int(1, 1851);
22
23
        $response = file_get_contents(sprintf(self::XKCD_JSON_URL, $number));
24
        $xkcd = json_decode($response, true);
25
26
        return new Xkcd(
27
            sprintf(self::XKCD_URL, $number),
28
            $xkcd['img'],
29
            $xkcd['alt']
30
        );
31
    }
32
}
33