forked from TobyMaxham/ux9-api
/
Shortener.php
156 lines (137 loc) · 2.48 KB
/
Shortener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<?php
namespace TobyMaxham\Ux9;
/**
* Class Shortener
* @package TobyMaxham\Ux9
* @author Tobias Maxham
*/
class Shortener
{
private $alias = FALSE;
private $token;
private $url = [];
private $format;
private $response;
/**
* @param null|string $url
* @param bool|string $format
*/
public function __construct($url = NULL, $format = FALSE)
{
$this->addUrl($url);
if (file_exists(__DIR__ . '/config.php')) {
$cfg = include __DIR__ . '/config.php';
if (isset($cfg['API_TOKEN']))
$this->token = $cfg['API_TOKEN'];
if (!$format && isset($cfg['FORMAT']))
$format = $cfg['FORMAT'];
else $format = 'json';
}
$this->format($format);
}
/**
* @param string $url
*/
public function addUrl($url)
{
if (is_array($url))
$this->url = array_merge($this->url, $url);
else
$this->url[] = $url;
}
/**
* @param string $format
*/
public function format($format)
{
$this->format = $format;
}
/**
* @param string $url
* @return mixed
*/
public function short($url)
{
unset($this->url);
$this->addUrl($url);
$req = $this->out('array');
$return = isset($req['link']) ? $req['link'] : NULL;
$this->url = [];
$this->response = NULL;
return $return;
}
/**
* @param null|string $format
* @return mixed
*/
public function out($format = NULL)
{
if (!is_null($format)) $this->format($format);
if (is_null($this->response)) $this->call();
return $this->parseResponse();
}
/**
* @return $this
*/
public function call()
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'http://api.ux9.de/?' . http_build_query($this->getOptions()),
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 4,
]);
$this->response = curl_exec($ch);
curl_close($ch);
return $this;
}
/**
* @return array $options
*/
private function getOptions()
{
return [
'token' => $this->getToken(),
'url' => $this->getUrl()[0],
'alias' => $this->getAlias(),
//'format' => $this->getFormat(),
];
}
/**
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
* @return array
*/
public function getUrl()
{
return $this->url;
}
/**
* @return bool|string
*/
public function getAlias()
{
return $this->alias;
}
/**
* @return mixed
*/
private function parseResponse()
{
$res = new Responder($this->response);
return $res->get($this->getFormat());
}
/**
* @return string
*/
public function getFormat()
{
return $this->format;
}
}