|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PoLaKoSz\CoC_API\DataAccessLayer |
|
4
|
|
|
{ |
|
5
|
|
|
use PoLaKoSz\CoC_API\Exceptions\ApiException; |
|
6
|
|
|
|
|
7
|
|
|
class WebClient |
|
8
|
|
|
{ |
|
9
|
|
|
private $apiKey; |
|
10
|
|
|
private $baseURL; |
|
11
|
|
|
|
|
12
|
|
|
public function __construct(string $apiKey) |
|
13
|
|
|
{ |
|
14
|
|
|
$this->baseURL = 'https://api.clashofclans.com/v1'; |
|
15
|
|
|
$this->apiKey = $apiKey; |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Send a Request to SuperCell's Servers and Receive it |
|
20
|
|
|
* |
|
21
|
|
|
* @param string $url |
|
22
|
|
|
* @return stdClass response from API |
|
23
|
|
|
*/ |
|
24
|
|
|
public function sendRequest(string $url) |
|
25
|
|
|
{ |
|
26
|
|
|
$url = $this->baseURL . $this->encodeHashTag($url); |
|
27
|
|
|
|
|
28
|
|
|
$ch = curl_init(); |
|
29
|
|
|
|
|
30
|
|
|
curl_setopt($ch, CURLOPT_URL, $url); |
|
31
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
32
|
|
|
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); |
|
33
|
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, array( |
|
34
|
|
|
'authorization: Bearer '. $this->apiKey, |
|
35
|
|
|
)); |
|
36
|
|
|
|
|
37
|
|
|
$response = curl_exec($ch); |
|
38
|
|
|
|
|
39
|
|
|
$info = curl_getinfo($ch); |
|
40
|
|
|
|
|
41
|
|
|
if ($info['http_code'] != 200) { |
|
42
|
|
|
throw new ApiException('The request was not successfull.', $info['http_code'], $response); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
curl_close($ch); |
|
46
|
|
|
|
|
47
|
|
|
$response = $this->escapeJsonString($response); |
|
48
|
|
|
|
|
49
|
|
|
return json_decode($response); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param string $url what needs to be encoded |
|
54
|
|
|
* @var string encoded url |
|
55
|
|
|
*/ |
|
56
|
|
|
private function encodeHashTag(string $url) |
|
57
|
|
|
{ |
|
58
|
|
|
return str_replace("#", urlencode('#'), $url); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Escape all invalid character |
|
63
|
|
|
* |
|
64
|
|
|
* @param string $value string wthat needs to be escaped |
|
65
|
|
|
* @param string |
|
66
|
|
|
*/ |
|
67
|
|
|
private function escapeJsonString(string $value) |
|
68
|
|
|
{ |
|
69
|
|
|
$escapers = array("<"); |
|
70
|
|
|
$replacements = array("<"); |
|
71
|
|
|
|
|
72
|
|
|
$result = str_replace($escapers, $replacements, $value); |
|
73
|
|
|
|
|
74
|
|
|
return $result; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|