Skip to content

Commit

Permalink
add curl timeout & error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
exinfinite committed Nov 6, 2020
1 parent 808eb56 commit ce2c3f8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 16 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "exinfinite/piwik-linker",
"description": "api wraper for piwik",
"version": "1.0.0",
"version": "1.0.1",
"type": "library",
"license": "LGPL-2.1",
"authors": [
Expand Down
16 changes: 14 additions & 2 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@ class Config {
private $paUrl;
private $idSite;
private $token;
public function __construct($paUrl, $idSite, $token) {
private $timeout;
/**
*
* @param string $paUrl
* @param integer $idSite
* @param string $token
* @param integer $timeout seconds, 0:no limit
*/
public function __construct($paUrl, $idSite, $token, $timeout = 30) {
$this->paUrl = $paUrl;
$this->idSite = $idSite;
$this->idSite = (int) $idSite;
$this->token = $token;
$this->timeout = (int) $timeout;
}
public function getIdSite() {
return $this->idSite;
Expand All @@ -19,4 +28,7 @@ public function getToken() {
public function getPaUrl() {
return $this->paUrl;
}
public function getTimeout() {
return $this->timeout;
}
}
36 changes: 23 additions & 13 deletions src/Modules/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,34 @@ protected function getApi($method) {
return "{$this->api}.{$method}";
}
protected function request($method, array $params = []) {
$ch = curl_init();
$query = http_build_query(
array_merge([
'method' => $this->getApi($method),
'module' => 'API',
'idSite' => $this->cfg->getIdSite(),
'format' => 'JSON',
'token_auth' => $this->cfg->getToken(),
], $params)
);
curl_setopt_array($ch, [
CURLOPT_URL => "{$this->cfg->getPaUrl()}?{$query}",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->cfg->getTimeout(),
]);
try {
$ch = curl_init();
$query = http_build_query(
array_merge([
'method' => $this->getApi($method),
'module' => 'API',
'idSite' => $this->cfg->getIdSite(),
'format' => 'JSON',
'token_auth' => $this->cfg->getToken(),
], $params)
);
curl_setopt($ch, CURLOPT_URL, "{$this->cfg->getPaUrl()}?{$query}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
return $result;
} catch (\Exception $e) {
return "[]";
curl_close($ch);
return $this->error($e->getMessage());
}
}
protected function error($msg) {
return json_encode([]);
}
}

0 comments on commit ce2c3f8

Please sign in to comment.