Passed
Push — develop ( 99647f...e3783d )
by Nikita
10:44
created

InfoService::loadVersionFromGameap()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 6
cp 0
rs 9.9666
cc 3
nc 3
nop 0
crap 12
1
<?php
2
3
namespace Gameap\Services;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\RequestException;
7
use Illuminate\Http\Response;
8
9
class InfoService
10
{
11
    private const GAMEAP_LATEST_VERSION_URI = 'http://www.gameap.ru/gameap_version.txt';
12
    private const GITHUB_LATEST_VERSION_URI = 'https://api.github.com/repos/et-nik/gameap/releases/latest';
13
    /** @var Client */
14
    private $client;
15
16
    public function __construct(Client $client)
17
    {
18
        $this->client = $client;
19
    }
20
21
    public function latestRelease(): string
22
    {
23
        $version = $this->loadVersionFromGameap();
24
25
        if ($version === '') {
26
            $version = $this->loadVersionFromGithub();
27
        }
28
29
        return $version;
30
    }
31
32
    private function loadVersionFromGameap(): string
33
    {
34
        try {
35
            $res = $this->client->get(self::GAMEAP_LATEST_VERSION_URI);
36
        } catch (RequestException $e) {
37
            return '';
38
        }
39
40
        if ($res->getStatusCode() === Response::HTTP_OK) {
41
            $lines  = explode("\n", $res->getBody()->getContents());
42
            $parts  = explode(': ', $lines[0]);
43
            return $parts[1];
44
        }
45
46
        return '';
47
    }
48
49
    private function loadVersionFromGithub(): string
50
    {
51
        try {
52
            $res = $this->client->get(self::GITHUB_LATEST_VERSION_URI);
53
        } catch (RequestException $e) {
54
            return '';
55
        }
56
57
        if ($res->getStatusCode() === Response::HTTP_OK) {
58
            $result = json_decode($res->getBody()->getContents());
59
60
            if (!empty($result->tag_name)) {
61
                return $result->tag_name;
62
            }
63
        }
64
65
        return '';
66
    }
67
}
68