Completed
Push — master ( 713384...224ae7 )
by Gareth
11:07
created

Client::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace GarethEllis\Tldr;
4
5
use GarethEllis\Tldr\Console\Command\GarethEllis\Tldr\Exception\PageNotFoundException;
6
7
class Client
8
{
9
    protected $http;
10
11
    /**
12
     * @var string The base URL of the JSON index containing a list of commands
13
     */
14
    protected $baseUrl = "https://api.github.com/repos/tldr-pages/tldr/contents/pages/index.json?ref=master";
15
16
    protected $pageInfoUrlTemplate = "https://api.github.com/repos/tldr-pages/tldr/contents/pages/{os}/{command}.md?ref=master";
17
18
    /**
19
     * Client constructor.
20
     * @param \GuzzleHttp\Client $http
21
     */
22
    public function __construct($http)
23
    {
24
        $this->http = $http;
25
    }
26
27
    public function setPagesUrl(string $url)
28
    {
29
        $this->baseUrl = $url;
30
    }
31
32
    public function getPagesUrl()
33
    {
34
        return $this->baseUrl;
35
    }
36
37
    public function lookupPage(string $page)
38
    {
39
        $response = $this->http->get($this->getPagesUrl());
40
        $contents = json_decode($response->getBody()->getContents(), true);
41
        $pages = base64_decode($contents["content"]);
42
        $json = json_decode($pages, true);
43
        $pages = $json["commands"];
44
45
        $pages = array_filter($pages, function ($foundPage) use ($page) {
46
            return $foundPage["name"] === $page;
47
        });
48
49
        //working on assumption that only one page has been found!
50
        if (empty($pages)) {
51
            throw new PageNotFoundException;
52
        }
53
54
        $page = $pages["0"];
55
        $url = str_replace("{os}", $page["platform"][0], $this->pageInfoUrlTemplate);
56
        $url = str_replace("{command}", $page["name"], $url);
57
58
        $response = $this->http->get($url);
59
        $contents = json_decode($response->getBody()->getContents(), true);
60
61
        $pageContent = base64_decode($contents["content"]);
62
63
        return $pageContent;
64
    }
65
}
66