|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Vinelab\UrlShortener\Base; |
|
4
|
|
|
|
|
5
|
|
|
use Vinelab\Http\Client as HttpClient; |
|
6
|
|
|
use Vinelab\UrlShortener\Contracts\ClientInterface; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class Client. |
|
10
|
|
|
* |
|
11
|
|
|
* @category Client Adapter |
|
12
|
|
|
* |
|
13
|
|
|
* @author Mahmoud Zalt <[email protected]> |
|
14
|
|
|
*/ |
|
15
|
|
|
class ClientAdapter implements ClientInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var \Vinelab\Http\Client |
|
19
|
|
|
*/ |
|
20
|
|
|
private $client; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param null $client |
|
24
|
|
|
*/ |
|
25
|
|
|
public function setClient($client = null) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->client = ((!$client) ? $this->defaultClient() : $client); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @return HttpClient |
|
32
|
|
|
*/ |
|
33
|
|
|
public function getClient() |
|
34
|
|
|
{ |
|
35
|
|
|
return $this->client; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* returns an object of the default HTTP client. |
|
40
|
|
|
* |
|
41
|
|
|
* @return \Vinelab\Http\Client |
|
42
|
|
|
*/ |
|
43
|
|
|
private function defaultClient() |
|
44
|
|
|
{ |
|
45
|
|
|
return new HttpClient(); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* build the URI from the provided data |
|
50
|
|
|
* do the actual call to the API through the Http Client |
|
51
|
|
|
* parse the data to return the shorten URL. |
|
52
|
|
|
* |
|
53
|
|
|
* @param $url the url which needs to be Shortened |
|
54
|
|
|
* @param array $parameters parameters tp be added to the URL |
|
55
|
|
|
* @param bool $json_formatted the format of the output |
|
56
|
|
|
* @param string $verb the HTTP verb function in the Client |
|
57
|
|
|
* |
|
58
|
|
|
* @return mixed |
|
59
|
|
|
*/ |
|
60
|
|
|
public function fetchUrl($url, $parameters = [], $json_formatted = true, $verb = 'get') |
|
61
|
|
|
{ |
|
62
|
|
|
$full_url = $this->buildUrl($url, $parameters); |
|
63
|
|
|
|
|
64
|
|
|
$response = $this->client->{$verb}($full_url); |
|
65
|
|
|
|
|
66
|
|
|
return ($json_formatted) ? $response->json() : $response; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* build the final URI to be called by the client. |
|
71
|
|
|
* |
|
72
|
|
|
* @param $url |
|
73
|
|
|
* @param $parameters |
|
74
|
|
|
* |
|
75
|
|
|
* @return string |
|
76
|
|
|
*/ |
|
77
|
|
|
private function buildUrl($url, $parameters) |
|
78
|
|
|
{ |
|
79
|
|
|
$prams_former = '?'; |
|
80
|
|
|
|
|
81
|
|
|
foreach ($parameters as $key => $value) { |
|
82
|
|
|
$prams_former = $prams_former.$key.'='.$value.'&'; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
return $url.substr($prams_former, 0, -1); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|