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
|
|
|
|