t411-console/src/Api/Client.php

75 lines
1.9 KiB
PHP
Raw Normal View History

2015-02-10 01:17:29 +01:00
<?php
namespace Api;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\RequestException;
class Client
{
protected $client;
2015-02-10 02:21:03 +01:00
protected $token;
2015-02-10 01:17:29 +01:00
public function __construct()
{
2015-02-10 02:04:56 +01:00
$this->client = new GuzzleClient(array('base_url' => 'https://api.t411.me'));
2015-02-10 01:17:29 +01:00
}
public function getAuthorization($username, $password)
{
2015-02-10 02:04:56 +01:00
return $this->post(
2015-02-10 02:21:03 +01:00
false,
2015-02-10 02:04:56 +01:00
'/auth',
2015-02-10 01:17:29 +01:00
array(
2015-02-10 02:04:56 +01:00
'body' => array(
'username' => $username,
'password' => $password,
),
2015-02-10 01:17:29 +01:00
)
);
}
2015-02-10 02:21:03 +01:00
public function setAuthorization($token)
{
$this->token = $token;
}
2015-02-10 02:04:56 +01:00
public function getCategoriesTree()
{
2015-02-10 02:21:03 +01:00
return $this->get(true, '/categories/tree');
2015-02-10 02:04:56 +01:00
}
2015-02-10 02:21:03 +01:00
public function get($needAuthorization, $uri, array $options = array())
2015-02-10 01:17:29 +01:00
{
2015-02-10 02:21:03 +01:00
return $this->send($needAuthorization, 'get', $uri, $options);
2015-02-10 01:17:29 +01:00
}
2015-02-10 02:21:03 +01:00
public function post($needAuthorization, $uri, array $options = array())
2015-02-10 02:04:56 +01:00
{
2015-02-10 02:21:03 +01:00
return $this->send($needAuthorization, 'post', $uri, $options);
2015-02-10 02:04:56 +01:00
}
2015-02-10 02:21:03 +01:00
protected function send($needAuthorization, $method, $uri, $options)
2015-02-10 01:17:29 +01:00
{
2015-02-10 02:21:03 +01:00
if ($needAuthorization) {
$options = array_merge(
$options,
array(
'headers' => array(
'Authorization' => $this->token,
),
)
);
}
2015-02-10 01:17:29 +01:00
try {
2015-02-10 02:04:56 +01:00
return new ClientResponse($this->client->{$method}($uri, $options));
2015-02-10 01:17:29 +01:00
} catch (RequestException $e) {
2015-02-10 02:04:56 +01:00
throw new ApiClientException(sprintf('Request exception (%s): %s', strtoupper($method), $e->getMessage()));
2015-02-10 01:17:29 +01:00
} catch (HttpConnectException $e) {
throw new ApiClientException(sprintf('HTTP Connection exception: %s', $e->getMessage()));
}
}
}