From 979b32d56479939581f2dae504d87af3f1f37a40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Thu, 6 Oct 2016 13:12:31 +0100 Subject: [PATCH 1/7] APICaller splitted into two separate classes, a Client and a Caller Client class manages endpoint and http requests Caller class manages the requests through Client and the response data Now using HTTPlug --- .gitignore | 6 +- composer.json | 58 ++-- examples/GeoPlugin.php | 55 ++++ examples/GeoPluginClient.php | 30 ++ examples/Geoplugin.php | 44 --- src/Caller.php | 228 +++++++++++++++ src/Client.php | 259 ++++++++++++++++++ src/MASNathan/APIcaller/APIcaller.php | 179 ------------ .../Exception/InvalidContentTypeException.php | 23 -- .../Exception/InvalidMethodException.php | 23 -- .../Exception/InvalidUrlException.php | 23 -- 11 files changed, 613 insertions(+), 315 deletions(-) create mode 100644 examples/GeoPlugin.php create mode 100644 examples/GeoPluginClient.php delete mode 100644 examples/Geoplugin.php create mode 100644 src/Caller.php create mode 100644 src/Client.php delete mode 100644 src/MASNathan/APIcaller/APIcaller.php delete mode 100644 src/MASNathan/APIcaller/Exception/InvalidContentTypeException.php delete mode 100644 src/MASNathan/APIcaller/Exception/InvalidMethodException.php delete mode 100644 src/MASNathan/APIcaller/Exception/InvalidUrlException.php diff --git a/.gitignore b/.gitignore index 4c7d945..697d47e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ -vendor/* -*.lock \ No newline at end of file +.idea + +vendor +*.lock diff --git a/composer.json b/composer.json index 770c053..b60c546 100644 --- a/composer.json +++ b/composer.json @@ -1,24 +1,40 @@ { - "name": "masnathan/api-caller", - "type": "library", - "description": "Calling APIs made easy.", - "keywords": ["api","webservice","request","curl"], - "homepage": "https://github.com/ReiDuKuduro/APIcaller", - "license": "MIT", - "authors": [ - { - "name": "André Filipe", - "email": "andre.r.flip@gmail.com", - "role": "Developer" - } - ], - "require": { - "php": ">=5.3.0", - "masnathan/curl": "0.0.2" - }, - "autoload": { - "psr-0": { - "MASNathan\\APIcaller\\": "src/" - } + "name": "masnathan/api-caller", + "type": "library", + "description": "Calling APIs made easy.", + "keywords": [ + "api", + "webservice", + "request" + ], + "homepage": "https://github.com/MASNathan/APICaller", + "license": "MIT", + "authors": [ + { + "name": "André Filipe", + "email": "andre.r.flip@gmail.com", + "role": "Developer" } + ], + "require": { + "php": ">=5.6", + "psr/http-message": "^1.0", + "php-http/client-implementation": "^1.0", + "php-http/httplug": "^1.0", + "php-http/message-factory": "^1.0", + "php-http/discovery": "^1.0", + "masnathan/parser": "^0.0.1" + }, + "require-dev": { + "php-http/mock-client": "^0.3.3", + "php-http/message": "^1.0", + "guzzlehttp/psr7": "^1.0", + "php-http/curl-client": "^1.6", + "symfony/var-dumper": "^3.1" + }, + "autoload": { + "psr-4": { + "MASNathan\\APICaller\\": "src/" + } + } } diff --git a/examples/GeoPlugin.php b/examples/GeoPlugin.php new file mode 100644 index 0000000..387f77c --- /dev/null +++ b/examples/GeoPlugin.php @@ -0,0 +1,55 @@ + + * @version 0.1.2 + */ +class GeoPlugin extends Caller +{ + + /** + * Fetches the IP locatio info + * + * @param string $ip + * @param string $baseCurrency i.e.: "EUR" + * @return array + */ + public function getLocation($ip = '', $baseCurrency = '', $renameArrayKeys = false) + { + $params = array( + 'ip' => !$ip ? $_SERVER['REMOTE_ADDR'] : $ip, + 'base_currency' => $baseCurrency, + ); + + $response = $this->get('json.gp', $params); + + $data = $this->handleResponseContent($response, 'json'); + + if ($renameArrayKeys) { + $tmpData = array(); + foreach ($data as $key => $value) { + $tmpData[str_replace('geoplugin_', '', $key)] = $value; + } + $data = $tmpData; + } + + return $data; + } + + public function test() + { + $response = $this->post('tests/http.php', json_encode(['foo' => 'bar'])); + + $data = $this->handleResponseContent($response, 'json'); + + dump($data); + exit; + } +} diff --git a/examples/GeoPluginClient.php b/examples/GeoPluginClient.php new file mode 100644 index 0000000..110e380 --- /dev/null +++ b/examples/GeoPluginClient.php @@ -0,0 +1,30 @@ + + * @version 0.1.2 + */ +class GeoPluginClient extends Client +{ + public function __construct() + { + parent::__construct(); + + $this->setHeaders([ + 'Accept' => 'application/json', + ]); + } + + public function getEndpoint() + { + return 'http://localhost/'; + return 'http://www.geoplugin.net/'; + } +} diff --git a/examples/Geoplugin.php b/examples/Geoplugin.php deleted file mode 100644 index 6ed06e8..0000000 --- a/examples/Geoplugin.php +++ /dev/null @@ -1,44 +0,0 @@ - - * @version 0.1.2 - */ -class Geoplugin extends APIcaller -{ - public function __construct() - { - parent::__construct('http://www.geoplugin.net/', APIcaller::METHOD_GET, 'json'); - } - - /** - * Fetches the IP locatio info - * @param string $ip - * @param string $baseCurrency i.e.: "EUR" - * @return array - */ - public function getLocation($ip = '', $baseCurrency = '', $renameArrayKeys = false) - { - $params = array( - 'ip' => !$ip ? $_SERVER['REMOTE_ADDR'] : $ip, - 'base_currency' => $baseCurrency, - ); - - $data = $this -> call('json.gp', $params); - - if ($renameArrayKeys) { - $tmpData = array(); - foreach ($data as $key => $value) { - $tmpData[str_replace('geoplugin_', '', $key)] = $value; - } - $data = $tmpData; - } - - return $data; - } -} diff --git a/src/Caller.php b/src/Caller.php new file mode 100644 index 0000000..9d8e768 --- /dev/null +++ b/src/Caller.php @@ -0,0 +1,228 @@ +client = $client; + $this->client->init(); + } + + /** + * Returns the formated URL to the requested section + * + * @param string $section API Section + * @param array $uriParams Params + * + * @return string + */ + protected function getUrl($section, array $uriParams = []) + { + $endpoint = rtrim($this->client->getEndpoint(), '/'); + $section = ltrim($section, '/'); + $params = http_build_query($uriParams); + + if ($params) { + return sprintf("%s/%s?%s", $endpoint, $section, $params); + } else { + return sprintf("%s/%s", $endpoint, $section); + } + } + + /** + * Sends a GET request. + * + * @param string $section URI section + * @param array $params Http get parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function get($section, array $params = [], $headers = []) + { + return $this->client->get($this->getUrl($section, $params), $headers); + } + + /** + * Sends a HEAD request. + * + * @param string $section URI section + * @param array $params Http head parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function head($section, array $params = [], $headers = []) + { + return $this->client->head($this->getUrl($section, $params), $headers); + } + + /** + * Sends a TRACE request. + * + * @param string $section URI section + * @param array $params Http trace parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function trace($section, array $params = [], $headers = []) + { + return $this->client->trace($this->getUrl($section, $params), $headers); + } + + /** + * Sends a POST request. + * + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http post parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function post($section, $body = null, array $headers = []) + { + if (is_array($body)) { + $body = http_build_query($body); + } + + return $this->client->post($this->getUrl($section), $headers, $body); + } + + /** + * Sends a PUT request. + * + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http put parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function put($section, $body = null, array $headers = []) + { + if (is_array($body)) { + $body = http_build_query($body); + } + + return $this->client->put($this->getUrl($section), $headers, $body); + } + + /** + * Sends a PATCH request. + * + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http patch parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function patch($section, $body = null, array $headers = []) + { + if (is_array($body)) { + $body = http_build_query($body); + } + + return $this->client->patch($this->getUrl($section), $headers, $body); + } + + /** + * Sends a DELETE request. + * + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http delete parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function delete($section, $body = null, array $headers = []) + { + if (is_array($body)) { + $body = http_build_query($body); + } + + return $this->client->delete($this->getUrl($section), $headers, $body); + } + + /** + * Sends a OPTIONS request. + * + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http options parameters + * @param array $headers Http headers + * + * @throws Exception + * + * @return ResponseInterface PSR-7 Response + */ + protected function options($section, $body = null, array $headers = []) + { + if (is_array($body)) { + $body = http_build_query($body); + } + + return $this->client->options($this->getUrl($section), $headers, $body); + } + + /** + * Handles the body content of a response + * + * @param ResponseInterface $response Response instance + * @param string|null $contentType Content Type + * + * @return array|string + */ + protected function handleResponseContent(ResponseInterface $response, $contentType = null) + { + $contents = $response->getBody()->getContents(); + + if (!$contentType) { + $contentTypeHeaderLine = $response->getHeaderLine('Content-Type'); + + if (stripos($contentTypeHeaderLine, 'application/json') !== false) { + $contentType = 'json'; + } elseif (stripos($contentTypeHeaderLine, 'application/xml') !== false) { + $contentType = 'xml'; + } + } + + if ($contentType) { + return Parser::data($contents)->from($contentType)->toArray(); + } + + return $contents; + } +} diff --git a/src/Client.php b/src/Client.php new file mode 100644 index 0000000..d033744 --- /dev/null +++ b/src/Client.php @@ -0,0 +1,259 @@ +setDefaultHeaders([ + 'User-Agent' => 'PHP APICaller SDK', + ]); + } + + /** + * Returns the API Endpoint + * + * @return string + */ + abstract public function getEndpoint(); + + /** + * @param HttpClient $httpClient HttpClient implementation + * + * @return Client + */ + public function setHttpClient(HttpClient $httpClient) + { + $this->httpClient = $httpClient; + + return $this; + } + + /** + * @param MessageFactory $messageFactory MessageFactory implementation + * + * @return Client + */ + public function setMessageFactory(MessageFactory $messageFactory) + { + $this->messageFactory = $messageFactory; + + return $this; + } + + /** + * Sets the Default Headers + * + * @param array $defaultHeaders Default Headers + * + * @return Client + */ + public function setDefaultHeaders(array $defaultHeaders) + { + $this->plugins['default_headers'] = new HeaderDefaultsPlugin($defaultHeaders); + + return $this; + } + + /** + * Sets the Mandatory Headers + * + * @param array $headers Headers + * + * @return Client + */ + public function setHeaders(array $headers) + { + $this->plugins['headers'] = new HeaderSetPlugin($headers); + + return $this; + } + + /** + * Initialises the HttpClient + * + * @return void + */ + public function init() + { + $this->pluginClient = new PluginClient( + $this->httpClient ?: HttpClientDiscovery::find(), + $this->plugins + ); + + $this->client = new HttpMethodsClient( + $this->pluginClient, + $this->messageFactory ?: MessageFactoryDiscovery::find() + ); + } + + + /** + * Sends a GET request. + * + * @param string|UriInterface $uri + * @param array $headers + * + * @throws Exception + * + * @return ResponseInterface + */ + public function get($uri, array $headers = []) + { + return $this->client->get($uri, $headers); + } + + /** + * Sends an HEAD request. + * + * @param string|UriInterface $uri + * @param array $headers + * + * @throws Exception + * + * @return ResponseInterface + */ + public function head($uri, array $headers = []) + { + return $this->client->head($uri, $headers); + } + + /** + * Sends a TRACE request. + * + * @param string|UriInterface $uri + * @param array $headers + * + * @throws Exception + * + * @return ResponseInterface + */ + public function trace($uri, array $headers = []) + { + return $this->client->trace($uri, $headers); + } + + /** + * Sends a POST request. + * + * @param string|UriInterface $uri + * @param array $headers + * @param string|StreamInterface|null $body + * + * @throws Exception + * + * @return ResponseInterface + */ + public function post($uri, array $headers = [], $body = null) + { + return $this->client->post($uri, $headers, $body); + } + + /** + * Sends a PUT request. + * + * @param string|UriInterface $uri + * @param array $headers + * @param string|StreamInterface|null $body + * + * @throws Exception + * + * @return ResponseInterface + */ + public function put($uri, array $headers = [], $body = null) + { + return $this->client->put($uri, $headers, $body); + } + + /** + * Sends a PATCH request. + * + * @param string|UriInterface $uri + * @param array $headers + * @param string|StreamInterface|null $body + * + * @throws Exception + * + * @return ResponseInterface + */ + public function patch($uri, array $headers = [], $body = null) + { + return $this->client->patch($uri, $headers, $body); + } + + /** + * Sends a DELETE request. + * + * @param string|UriInterface $uri + * @param array $headers + * @param string|StreamInterface|null $body + * + * @throws Exception + * + * @return ResponseInterface + */ + public function delete($uri, array $headers = [], $body = null) + { + return $this->client->delete($uri, $headers, $body); + } + + /** + * Sends an OPTIONS request. + * + * @param string|UriInterface $uri + * @param array $headers + * @param string|StreamInterface|null $body + * + * @throws Exception + * + * @return ResponseInterface + */ + public function options($uri, array $headers = [], $body = null) + { + return $this->client->options($uri, $headers, $body); + } +} diff --git a/src/MASNathan/APIcaller/APIcaller.php b/src/MASNathan/APIcaller/APIcaller.php deleted file mode 100644 index a817e18..0000000 --- a/src/MASNathan/APIcaller/APIcaller.php +++ /dev/null @@ -1,179 +0,0 @@ - - * @link https://github.com/ReiDuKuduro/APIcaller GitHub repo - * @license MIT - * @version 0.3.0 - */ -class APIcaller -{ - /** - * Communication standards allowed - */ - const METHOD_GET = 'GET'; - const METHOD_POST = 'POST'; - const METHOD_PUT = 'PUT'; - const METHOD_DELETE = 'DELETE'; - - /** - * Url of the API to call - * @var string - */ - private $api_url; - - /** - * Var that holds all the default params - * @var array - */ - private $default_params = array(); - - /** - * Method to use on the call - * @var string - */ - private $default_request_method; - - /** - * Data format that the api you are calling will return to be parsed - * @var string [none|json|xml] - */ - private $default_response_format; - - /** - * Holds the last call information - * @var string - */ - private $last_call = array(); - - /** - * Allows you to set the default URL, call method and the parse format if any - * @param string $url The API URL - * @param string $method The Request Standard you want to use [GET|POST|PUT|DELETE] - * @param string $format The format of the data the webservice will return [none|json|xml] - */ - public function __construct($api_url = null, $default_request_method = 'GET', $response_format = 'none') - { - $this->setApiUrl($api_url); - $this->setRequestMethod($default_request_method); - $this->setResponseFormat($response_format); - } - - /** - * Sets the URL of the API - * @param string $url - * @return APIcaller - * @throws Exception\InvalidUrlException If URL is not valid - */ - final protected function setApiUrl($url) - { - if (!filter_var($url, FILTER_VALIDATE_URL)) { - throw new Exception\InvalidUrlException; - } - - $this->api_url = $url; - return $this; - } - - /** - * Sets a default parameter - * @param string $param - * @param string|integer|double $value - * @return APIcaller - */ - protected function setDefaultParameter($param, $value) - { - $this->default_params[$param] = $value; - return $this; - } - - /** - * Sets the Method to use when calling the API - * @param string $method [ GET | POST | PUT | DELETE ] - * @return APIcaller - * @throws Exception\InvalidMethodException If method is not valid - */ - final protected function setRequestMethod($method) - { - if (!in_array($method, array(self::METHOD_GET, self::METHOD_POST, self::METHOD_PUT, self::METHOD_DELETE))) { - throw new Exception\InvalidMethodException; - } - - $this->default_request_method = $method; - return $this; - } - - /** - * Sets the Format of the retrieved data to be parsed - * @param string $format - * @return APIcaller - */ - final protected function setResponseFormat($format) - { - $this->default_response_format = $format; - return $this; - } - - /** - * Returns the last call info - * @return array - */ - public function getLastCall() - { - return $this->last_call; - } - - /** - * Calls the API and returns the data as an Array - * @param string $section Name of the file or path you need to call - * @param array|string $params Params to use on the query or the xml/json string you want to POST - * @param string $content_type Content type of the data you want to POST - * @return array|null - * @throws InvalidUrlException Throws a exception if there is no URL defined - * @throws InvalidContentTypeException Throws a exception if the content type is not supported - */ - protected function call($section, $params, $content_type = null) - { - if (!$this->api_url) { - throw new Exception\InvalidUrlException("You need to set a URL!"); - } - - if ($content_type && !in_array($content_type, array('json', 'xml'))) { - throw new Exception\InvalidContentTypeException(sprintf("Content type not supported: \"%s\".", $content_type)); - } - - if (!$content_type) { - $params = array_merge($params, $this->default_params); - } - - $this->last_call = array(); - $this->last_call['url'] = $this->api_url . $section; - $this->last_call['params'] = $params; - $this->last_call['response'] = null; - $this->last_call['data'] = null; - - try { - $args = array( - $this->api_url . $section, //URL - $params, //Parameters - ); - - $response = Curl\Ch::call($this->default_request_method, $args, $content_type); - $this->last_call['response'] = $response; - - $data = Curl\StringParser::parse($response, $this->default_response_format); - $this->last_call['data'] = $data; - - return $data; - } catch(\Exception $e) { - return null; - } - } -} diff --git a/src/MASNathan/APIcaller/Exception/InvalidContentTypeException.php b/src/MASNathan/APIcaller/Exception/InvalidContentTypeException.php deleted file mode 100644 index ad7cf6d..0000000 --- a/src/MASNathan/APIcaller/Exception/InvalidContentTypeException.php +++ /dev/null @@ -1,23 +0,0 @@ - - * @license MIT - * @version 0.2.0 - */ -class InvalidContentTypeException extends \Exception -{ - public function __construct($message = '', $code = 0, $previous = null) { - - if (!$message) { - $message = "Content type not supported"; - } - parent::__construct($message, $code, $previous); - } -} diff --git a/src/MASNathan/APIcaller/Exception/InvalidMethodException.php b/src/MASNathan/APIcaller/Exception/InvalidMethodException.php deleted file mode 100644 index 785de26..0000000 --- a/src/MASNathan/APIcaller/Exception/InvalidMethodException.php +++ /dev/null @@ -1,23 +0,0 @@ - - * @license MIT - * @version 0.2.0 - */ -class InvalidMethodException extends \Exception -{ - public function __construct($message = '', $code = 0, $previous = null) { - - if (!$message) { - $message = "Invalid communication standard."; - } - parent::__construct($message, $code, $previous); - } -} diff --git a/src/MASNathan/APIcaller/Exception/InvalidUrlException.php b/src/MASNathan/APIcaller/Exception/InvalidUrlException.php deleted file mode 100644 index eab39fc..0000000 --- a/src/MASNathan/APIcaller/Exception/InvalidUrlException.php +++ /dev/null @@ -1,23 +0,0 @@ - - * @license MIT - * @version 0.2.0 - */ -class InvalidUrlException extends \Exception -{ - public function __construct($message = '', $code = 0, $previous = null) { - - if (!$message) { - $message = "Invalid URL."; - } - parent::__construct($message, $code, $previous); - } -} From ad8291287c4171ccbe92acbce8310adae82bf158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Thu, 6 Oct 2016 13:17:48 +0100 Subject: [PATCH 2/7] Added gitattributes file --- .gitattributes | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..ad9755e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/examples export-ignore +.gitattributes export-ignore +.gitignore export-ignore From 95fbc205ada48c81e7d9c400fe271efcfeef4a86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Thu, 6 Oct 2016 14:28:13 +0100 Subject: [PATCH 3/7] Added default parameters Small logic changes --- examples/GeoPlugin.php | 2 +- examples/GeoPluginClient.php | 1 - src/Caller.php | 171 +------------------------------ src/Client.php | 191 ++++++++++++++++++++++++++--------- 4 files changed, 143 insertions(+), 222 deletions(-) diff --git a/examples/GeoPlugin.php b/examples/GeoPlugin.php index 387f77c..3aa21e6 100644 --- a/examples/GeoPlugin.php +++ b/examples/GeoPlugin.php @@ -28,7 +28,7 @@ public function getLocation($ip = '', $baseCurrency = '', $renameArrayKeys = fal 'base_currency' => $baseCurrency, ); - $response = $this->get('json.gp', $params); + $response = $this->client->get('json.gp', $params); $data = $this->handleResponseContent($response, 'json'); diff --git a/examples/GeoPluginClient.php b/examples/GeoPluginClient.php index 110e380..4cced7e 100644 --- a/examples/GeoPluginClient.php +++ b/examples/GeoPluginClient.php @@ -24,7 +24,6 @@ public function __construct() public function getEndpoint() { - return 'http://localhost/'; return 'http://www.geoplugin.net/'; } } diff --git a/src/Caller.php b/src/Caller.php index 9d8e768..e404703 100644 --- a/src/Caller.php +++ b/src/Caller.php @@ -15,7 +15,7 @@ abstract class Caller /** * @var Client */ - private $client; + protected $client; /** * Caller constructor. @@ -28,175 +28,6 @@ public function __construct(Client $client) $this->client->init(); } - /** - * Returns the formated URL to the requested section - * - * @param string $section API Section - * @param array $uriParams Params - * - * @return string - */ - protected function getUrl($section, array $uriParams = []) - { - $endpoint = rtrim($this->client->getEndpoint(), '/'); - $section = ltrim($section, '/'); - $params = http_build_query($uriParams); - - if ($params) { - return sprintf("%s/%s?%s", $endpoint, $section, $params); - } else { - return sprintf("%s/%s", $endpoint, $section); - } - } - - /** - * Sends a GET request. - * - * @param string $section URI section - * @param array $params Http get parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function get($section, array $params = [], $headers = []) - { - return $this->client->get($this->getUrl($section, $params), $headers); - } - - /** - * Sends a HEAD request. - * - * @param string $section URI section - * @param array $params Http head parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function head($section, array $params = [], $headers = []) - { - return $this->client->head($this->getUrl($section, $params), $headers); - } - - /** - * Sends a TRACE request. - * - * @param string $section URI section - * @param array $params Http trace parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function trace($section, array $params = [], $headers = []) - { - return $this->client->trace($this->getUrl($section, $params), $headers); - } - - /** - * Sends a POST request. - * - * @param string $section URI section - * @param string|array|StreamInterface|null $body Body content or Http post parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function post($section, $body = null, array $headers = []) - { - if (is_array($body)) { - $body = http_build_query($body); - } - - return $this->client->post($this->getUrl($section), $headers, $body); - } - - /** - * Sends a PUT request. - * - * @param string $section URI section - * @param string|array|StreamInterface|null $body Body content or Http put parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function put($section, $body = null, array $headers = []) - { - if (is_array($body)) { - $body = http_build_query($body); - } - - return $this->client->put($this->getUrl($section), $headers, $body); - } - - /** - * Sends a PATCH request. - * - * @param string $section URI section - * @param string|array|StreamInterface|null $body Body content or Http patch parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function patch($section, $body = null, array $headers = []) - { - if (is_array($body)) { - $body = http_build_query($body); - } - - return $this->client->patch($this->getUrl($section), $headers, $body); - } - - /** - * Sends a DELETE request. - * - * @param string $section URI section - * @param string|array|StreamInterface|null $body Body content or Http delete parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function delete($section, $body = null, array $headers = []) - { - if (is_array($body)) { - $body = http_build_query($body); - } - - return $this->client->delete($this->getUrl($section), $headers, $body); - } - - /** - * Sends a OPTIONS request. - * - * @param string $section URI section - * @param string|array|StreamInterface|null $body Body content or Http options parameters - * @param array $headers Http headers - * - * @throws Exception - * - * @return ResponseInterface PSR-7 Response - */ - protected function options($section, $body = null, array $headers = []) - { - if (is_array($body)) { - $body = http_build_query($body); - } - - return $this->client->options($this->getUrl($section), $headers, $body); - } - /** * Handles the body content of a response * diff --git a/src/Client.php b/src/Client.php index d033744..305e3f5 100644 --- a/src/Client.php +++ b/src/Client.php @@ -44,6 +44,10 @@ abstract class Client */ private $client; + protected $defaultParameters = []; + + protected $parameters = []; + /** * Client constructor. */ @@ -61,6 +65,27 @@ public function __construct() */ abstract public function getEndpoint(); + /** + * Returns the formated URL to the requested section + * + * @param string $section API Section + * @param array $uriParams Params + * + * @return string + */ + protected function getUrl($section, array $uriParams = []) + { + $endpoint = rtrim($this->client->getEndpoint(), '/'); + $section = ltrim($section, '/'); + $params = http_build_query($uriParams); + + if ($params) { + return sprintf("%s/%s?%s", $endpoint, $section, $params); + } else { + return sprintf("%s/%s", $endpoint, $section); + } + } + /** * @param HttpClient $httpClient HttpClient implementation * @@ -92,13 +117,27 @@ public function setMessageFactory(MessageFactory $messageFactory) * * @return Client */ - public function setDefaultHeaders(array $defaultHeaders) + protected function setDefaultHeaders(array $defaultHeaders) { $this->plugins['default_headers'] = new HeaderDefaultsPlugin($defaultHeaders); return $this; } + /** + * Sets the Default Parameters + * + * @param array $defaultParameters Default Parameters + * + * @return Client + */ + protected function setDefaultParameters(array $defaultParameters) + { + $this->defaultParameters = $defaultParameters; + + return $this; + } + /** * Sets the Mandatory Headers * @@ -106,13 +145,27 @@ public function setDefaultHeaders(array $defaultHeaders) * * @return Client */ - public function setHeaders(array $headers) + protected function setHeaders(array $headers) { $this->plugins['headers'] = new HeaderSetPlugin($headers); return $this; } + /** + * Sets the Mandatory Parameters + * + * @param array $parameters Parameters + * + * @return Client + */ + protected function setParameters(array $parameters) + { + $this->parameters = $parameters; + + return $this; + } + /** * Initialises the HttpClient * @@ -131,129 +184,167 @@ public function init() ); } - /** * Sends a GET request. * - * @param string|UriInterface $uri - * @param array $headers + * @param string $section URI section + * @param array $params Http get parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function get($uri, array $headers = []) + public function get($section, array $params = [], $headers = []) { - return $this->client->get($uri, $headers); + $params = array_merge($this->parameters, $params, $this->defaultParameters); + + return $this->client->get($this->getUrl($section, $params), $headers); } /** - * Sends an HEAD request. + * Sends a HEAD request. * - * @param string|UriInterface $uri - * @param array $headers + * @param string $section URI section + * @param array $params Http head parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function head($uri, array $headers = []) + public function head($section, array $params = [], $headers = []) { - return $this->client->head($uri, $headers); + $params = array_merge($this->parameters, $params, $this->defaultParameters); + + return $this->client->head($this->getUrl($section, $params), $headers); } /** * Sends a TRACE request. * - * @param string|UriInterface $uri - * @param array $headers + * @param string $section URI section + * @param array $params Http trace parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function trace($uri, array $headers = []) + public function trace($section, array $params = [], $headers = []) { - return $this->client->trace($uri, $headers); + $params = array_merge($this->parameters, $params, $this->defaultParameters); + + return $this->client->trace($this->getUrl($section, $params), $headers); } /** * Sends a POST request. * - * @param string|UriInterface $uri - * @param array $headers - * @param string|StreamInterface|null $body + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http post parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function post($uri, array $headers = [], $body = null) + public function post($section, $body = null, array $headers = []) { - return $this->client->post($uri, $headers, $body); + if (is_array($body)) { + $body = array_merge($this->parameters, $body, $this->defaultParameters); + + $body = http_build_query($body); + } + + return $this->client->post($this->getUrl($section), $headers, $body); } /** * Sends a PUT request. * - * @param string|UriInterface $uri - * @param array $headers - * @param string|StreamInterface|null $body + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http put parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function put($uri, array $headers = [], $body = null) + public function put($section, $body = null, array $headers = []) { - return $this->client->put($uri, $headers, $body); + if (is_array($body)) { + $body = array_merge($this->parameters, $body, $this->defaultParameters); + + $body = http_build_query($body); + } + + return $this->client->put($this->getUrl($section), $headers, $body); } /** * Sends a PATCH request. * - * @param string|UriInterface $uri - * @param array $headers - * @param string|StreamInterface|null $body + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http patch parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function patch($uri, array $headers = [], $body = null) + public function patch($section, $body = null, array $headers = []) { - return $this->client->patch($uri, $headers, $body); + if (is_array($body)) { + $body = array_merge($this->parameters, $body, $this->defaultParameters); + + $body = http_build_query($body); + } + + return $this->client->patch($this->getUrl($section), $headers, $body); } /** * Sends a DELETE request. * - * @param string|UriInterface $uri - * @param array $headers - * @param string|StreamInterface|null $body + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http delete parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function delete($uri, array $headers = [], $body = null) + public function delete($section, $body = null, array $headers = []) { - return $this->client->delete($uri, $headers, $body); + if (is_array($body)) { + $body = array_merge($this->parameters, $body, $this->defaultParameters); + + $body = http_build_query($body); + } + + return $this->client->delete($this->getUrl($section), $headers, $body); } /** - * Sends an OPTIONS request. + * Sends a OPTIONS request. * - * @param string|UriInterface $uri - * @param array $headers - * @param string|StreamInterface|null $body + * @param string $section URI section + * @param string|array|StreamInterface|null $body Body content or Http options parameters + * @param array $headers Http headers * * @throws Exception * - * @return ResponseInterface + * @return ResponseInterface PSR-7 Response */ - public function options($uri, array $headers = [], $body = null) + public function options($section, $body = null, array $headers = []) { - return $this->client->options($uri, $headers, $body); + if (is_array($body)) { + $body = array_merge($this->parameters, $body, $this->defaultParameters); + + $body = http_build_query($body); + } + + return $this->client->options($this->getUrl($section), $headers, $body); } } From fb92351c47a3414311de18de8bba19512a47d910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Thu, 6 Oct 2016 15:10:40 +0100 Subject: [PATCH 4/7] removed test method --- examples/GeoPlugin.php | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/examples/GeoPlugin.php b/examples/GeoPlugin.php index 3aa21e6..d5aba04 100644 --- a/examples/GeoPlugin.php +++ b/examples/GeoPlugin.php @@ -42,14 +42,4 @@ public function getLocation($ip = '', $baseCurrency = '', $renameArrayKeys = fal return $data; } - - public function test() - { - $response = $this->post('tests/http.php', json_encode(['foo' => 'bar'])); - - $data = $this->handleResponseContent($response, 'json'); - - dump($data); - exit; - } } From e99121bc5e75a8087b812cd12cc605894daef9f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Thu, 6 Oct 2016 15:40:35 +0100 Subject: [PATCH 5/7] Changed the dependencies Small fixes --- composer.json | 5 +---- src/Client.php | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index b60c546..9853c7a 100644 --- a/composer.json +++ b/composer.json @@ -18,16 +18,13 @@ ], "require": { "php": ">=5.6", - "psr/http-message": "^1.0", "php-http/client-implementation": "^1.0", - "php-http/httplug": "^1.0", - "php-http/message-factory": "^1.0", + "php-http/client-common": "^1.2", "php-http/discovery": "^1.0", "masnathan/parser": "^0.0.1" }, "require-dev": { "php-http/mock-client": "^0.3.3", - "php-http/message": "^1.0", "guzzlehttp/psr7": "^1.0", "php-http/curl-client": "^1.6", "symfony/var-dumper": "^3.1" diff --git a/src/Client.php b/src/Client.php index 305e3f5..aea1069 100644 --- a/src/Client.php +++ b/src/Client.php @@ -75,7 +75,7 @@ abstract public function getEndpoint(); */ protected function getUrl($section, array $uriParams = []) { - $endpoint = rtrim($this->client->getEndpoint(), '/'); + $endpoint = rtrim($this->getEndpoint(), '/'); $section = ltrim($section, '/'); $params = http_build_query($uriParams); From 4319bd118dcc8f5d639d9f96f24329ed9d8ec707 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Wed, 1 Feb 2017 14:09:08 +0000 Subject: [PATCH 6/7] Last operation (request and response) is now stored and can be accessed throw the Client with getLastOperation --- src/Caller.php | 8 +++++ src/Client.php | 10 +++++- src/Clients/HttpMethodsClient.php | 39 +++++++++++++++++++++++ src/Operation.php | 53 +++++++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 src/Clients/HttpMethodsClient.php create mode 100644 src/Operation.php diff --git a/src/Caller.php b/src/Caller.php index e404703..1411cfa 100644 --- a/src/Caller.php +++ b/src/Caller.php @@ -56,4 +56,12 @@ protected function handleResponseContent(ResponseInterface $response, $contentTy return $contents; } + + /** + * @return Client + */ + public function getClient() + { + return $this->client; + } } diff --git a/src/Client.php b/src/Client.php index aea1069..0e8314d 100644 --- a/src/Client.php +++ b/src/Client.php @@ -2,7 +2,7 @@ namespace MASNathan\APICaller; -use Http\Client\Common\HttpMethodsClient; +use MASNathan\APICaller\Clients\HttpMethodsClient; use Http\Client\Common\Plugin\HeaderDefaultsPlugin; use Http\Client\Common\Plugin\HeaderSetPlugin; use Http\Client\Common\PluginClient; @@ -347,4 +347,12 @@ public function options($section, $body = null, array $headers = []) return $this->client->options($this->getUrl($section), $headers, $body); } + + /** + * @return Operation + */ + public function getLastOperation() + { + return $this->client->getLastOperation(); + } } diff --git a/src/Clients/HttpMethodsClient.php b/src/Clients/HttpMethodsClient.php new file mode 100644 index 0000000..6319162 --- /dev/null +++ b/src/Clients/HttpMethodsClient.php @@ -0,0 +1,39 @@ +lastOperation = new Operation($request); + + $response = parent::sendRequest($request); + + $this->lastOperation->setResponse($response); + + return $response; + } + + /** + * @return Operation + */ + public function getLastOperation() + { + return $this->lastOperation; + } +} diff --git a/src/Operation.php b/src/Operation.php new file mode 100644 index 0000000..92584b8 --- /dev/null +++ b/src/Operation.php @@ -0,0 +1,53 @@ +request = $request; + } + + /** + * @return RequestInterface + */ + public function getRequest() + { + return $this->request; + } + + /** + * @return ResponseInterface + */ + public function getResponse() + { + return $this->response; + } + + /** + * @param ResponseInterface $response + */ + public function setResponse(ResponseInterface $response) + { + $this->response = $response; + } +} From 6a9e8d1b280a63495c52a878931c652bb4ba76f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Filipe?= Date: Fri, 21 Jul 2017 11:12:44 +0100 Subject: [PATCH 7/7] Updated dependencies and changed docs --- README.md | 128 +++++++++++++++---------- composer.json | 2 +- examples/GeoPlugin.php | 11 +-- examples/GeoPluginClient.php | 5 +- examples/Geoplugin.md | 9 +- examples/Openweathermap.md | 32 ------- examples/Openweathermap.php | 176 ----------------------------------- 7 files changed, 94 insertions(+), 269 deletions(-) delete mode 100644 examples/Openweathermap.md delete mode 100644 examples/Openweathermap.php diff --git a/README.md b/README.md index 9230836..45bb2f3 100755 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -#APIcaller +# APIcaller [![Downloads with Composer](https://poser.pugx.org/masnathan/api-caller/downloads.png)](https://packagist.org/packages/masnathan/api-caller) [![SensioLabs Insight](https://insight.sensiolabs.com/projects/a1bfb7a8-0b34-4118-a451-fc8f158ef9c7/mini.png)](https://insight.sensiolabs.com/projects/6d9231d8-9140-4b02-9522-5d3c3aa3d6f2) @@ -7,69 +7,103 @@ APIcaller is a class that helps you build API wrappers. You don't have to worry about building URLs, or even about parsing the requested data. -# How to install via Composer +## How to use -The recommended way to install is through [Composer](http://composer.org). +You will have to extend the ```Client``` class and the ```Caller``` class, the ```Client``` will handle all the +configuration to use on the requests and the ```Caller``` will be used as the interface to interact with the API. -```sh -# Install Composer -$ curl -sS https://getcomposer.org/installer | php +```php +use MASNathan\APICaller\Client; +use MASNathan\APICaller\Caller; -# Add APIcaller as a dependency -$ php composer.phar require masnathan/api-caller:dev-master -``` +class MyPackageClient extends Client +{ + /** + * Here you can set the default headers and parameters on a global scope + */ + public function __construct($ip = null) + { + $this->setDefaultHeaders([ + 'User-Agent' => 'PHP APICaller SDK', + 'Accept' => 'application/json', + 'Token' => '123456', + ]); + $this->setDefaultParameters([ + 'ip' => $ip ?: '127.0.0.1', + ]); + } + + /** + * Returns the API Endpoint + * + * @return string + */ + public function getEndpoint() + { + return 'http://api.domain.com/v1/'; + } +} -Once it's installed, you need to require Composer's autoloader: +class MyPackageCaller extends Caller +{ + public function requestSomething($foo, $bar) + { + $params = [ + 'foo' => $foo, + 'bar' => $bar, + ]; -```php -require 'vendor/autoload.php'; -``` + // this will result in this url http://api.domain.com/v1/some-method.json?ip={$ip}&foo={$foo}&bar={$bar} + $response = $this->client->get('some-method.json', $params); -#How to Extend -Here is some quick example. + $data = $this->handleResponseContent($response, 'json'); -```php -class MyClass extends APIcaller -{ - function __construct() - { - /* - * Calling the parent construct you can send the API URL, set the request method and/or the response type - * The API URL must be a valid url - * The Request Method to use [GET|POST|PUT|DELETE], we have constants APIcaller::METHOD_GET, APIcaller::METHOD_… - * The format of the data the webservice will return, can be APIcaller::CONTENT_TYPE_NONE, APIcaller::CONTENT_TYPE_JSON or APIcaller::CONTENT_TYPE_XML - */ - parent::__construct('http://www.some_api.com/', APIcaller::METHOD_GET, 'json'); - - //You can also set some default parameters to use on the calls, like api keys and such. - $this->setDefault('api_key', 'key'); - } - - /****/ + // Do something with your data + + return $data; + } } ``` Well, this is how you can start creating your class, now, lets make some calls! ```php -public function callMeBaby($some_number) -{ - //1st, you need to set the parameters you want to send - $params = array( - 'number' => $some_number, - 'other' => 'info', - ); - //2nd, you send the request - return $this->call('call_a_friend', $params); -} +$client = new MyPackageClient('8.8.8.8'); +$caller = new MyPackageCaller($client); + +$result = $caller->requestSomething(13, 37); + +var_dump($result); ``` -This function will call the following url:```http://www.some_api.com/call_a_friend?api_key=key&number=1&other=info```. +This will call the following url:```http://api.domain.com/v1/some-method.json?ip=8.8.8.8&foo=13&bar=37```. + +## Installation + +To install the SDK, you will need to be using [Composer](http://composer.org) in your project. If you don't have composer +installed check this page and follow the [installation steps](https://getcomposer.org/download/) -If you set the format/ response type to ```json``` or ```xml``` and the response has a valid format, the ```$this->call()```function will return an array with the parsed data, if not, it'll return a string of the response. +This library is not hard coupled to Guzzle or any other library that sends HTTP messages. +It uses an abstraction called [HTTPlug](http://httplug.io/). +This will give you the flexibility to choose what PSR-7 implementation and HTTP client to use. + +To get started ASAP you should run the following command: + +```sh +# Add APIcaller as a dependency +$ composer require masnathan/api-caller php-http/curl-client guzzlehttp/psr7 +``` + +## Why do I need to require all those packages? + +APICaller depends on the virtual package [php-http/client-implementation](https://packagist.org/providers/php-http/client-implementation) +which requires to you install an adapter, but we do not care which one. +That is an implementation detail in your application. +We also need a PSR-7 implementation and a message factory. + +You don't have to use the [php-http/curl-client](https://github.com/php-http/curl-client) if you don't want to. +Read more about the virtual packages, why this is a good idea and about the flexibility it brings at the [HTTPlug docs](http://docs.php-http.org/en/latest/index.html). # License This library is under the MIT License, see the complete license [here](LICENSE) - -###Is your project using `APIcaller`? [Let me know](https://github.com/ReiDuKuduro/APIcaller/issues/new?title=New%20script%20using%20APIcaller&body=Name and Description of your script.)! \ No newline at end of file diff --git a/composer.json b/composer.json index 9853c7a..f64cd08 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "masnathan/parser": "^0.0.1" }, "require-dev": { - "php-http/mock-client": "^0.3.3", + "php-http/mock-client": "^1.0.1", "guzzlehttp/psr7": "^1.0", "php-http/curl-client": "^1.6", "symfony/var-dumper": "^3.1" diff --git a/examples/GeoPlugin.php b/examples/GeoPlugin.php index d5aba04..dc99717 100644 --- a/examples/GeoPlugin.php +++ b/examples/GeoPlugin.php @@ -5,11 +5,10 @@ use MASNathan\APICaller\Caller; /** - * GeoPlugin - API Wrapper for http://www.geoplugin.com/, Simple example on How to use the APIcaller class to call an - * API + * GeoPlugin - API Wrapper for http://www.geoplugin.com/, + * Simple example on How to use the APIcaller class to call an API * * @author André Filipe - * @version 0.1.2 */ class GeoPlugin extends Caller { @@ -23,17 +22,17 @@ class GeoPlugin extends Caller */ public function getLocation($ip = '', $baseCurrency = '', $renameArrayKeys = false) { - $params = array( + $params = [ 'ip' => !$ip ? $_SERVER['REMOTE_ADDR'] : $ip, 'base_currency' => $baseCurrency, - ); + ]; $response = $this->client->get('json.gp', $params); $data = $this->handleResponseContent($response, 'json'); if ($renameArrayKeys) { - $tmpData = array(); + $tmpData = []; foreach ($data as $key => $value) { $tmpData[str_replace('geoplugin_', '', $key)] = $value; } diff --git a/examples/GeoPluginClient.php b/examples/GeoPluginClient.php index 4cced7e..5c456b5 100644 --- a/examples/GeoPluginClient.php +++ b/examples/GeoPluginClient.php @@ -5,11 +5,10 @@ use MASNathan\APICaller\Client; /** - * Geoplugin - API Wrapper for http://www.geoplugin.com/, Simple example on How to use the APIcaller class to call an - * API + * Geoplugin - API Wrapper for http://www.geoplugin.com/, + * Simple example on How to use the APIcaller class to call an API * * @author André Filipe - * @version 0.1.2 */ class GeoPluginClient extends Client { diff --git a/examples/Geoplugin.md b/examples/Geoplugin.md index ecfa976..03bcc24 100644 --- a/examples/Geoplugin.md +++ b/examples/Geoplugin.md @@ -7,13 +7,14 @@ API used: http://www.geoplugin.com/ ##How to use this class: ```php //Initializing the caller -$geo = new MASNathan\Geoplugin\Geoplugin(); +$client = new MASNathan\Geoplugin\GeoPluginClient(); +$geo = new MASNathan\Geoplugin\Geoplugin($client); //Getting IP info $geo->getLocation('173.194.41.223'); $geo->getLocation('173.194.41.223', 'EUR', true); $geo->getLocation('173.194.41.223', 'USD', true); -//Get the last call to the API -$geo->getLastCall(); -``` \ No newline at end of file +//Get the last request and response to the API +var_dump($geo->getLastOperation()); +``` diff --git a/examples/Openweathermap.md b/examples/Openweathermap.md deleted file mode 100644 index e940a89..0000000 --- a/examples/Openweathermap.md +++ /dev/null @@ -1,32 +0,0 @@ -#Openweathermap - -Simple example on How to use the APIcaller to call an API - -API used: http://openweathermap.org/ - -##How to use this class: -```php -//Initializing the caller -$weather = new MASNathan\Openweathermap\Openweathermap('my_api_key'); -//Setting the default properties -$weather - ->setLanguage('pt') - ->setUnits('metric'); - -//Getting current weather data -$weather->getCurrentWeatherByCity('London,uk'); -$weather->getCurrentWeatherByCoordinats(35, 139); -$weather->getCurrentWeatherByID(2172797); - -//Getting forecast weather data -$weather->getForecastByCity('London,uk'); -$weather->getForecastByCoordinats(35, 139); -$weather->getForecastByID(2172797, 4); - -//Searching of city -$weather->getForecastByCity('London,uk', 10, 'accurate'); -$weather->getForecastByCoordinats(57, -2.15); - -//Get the last call to the API -$weather->getLastCall(); -``` diff --git a/examples/Openweathermap.php b/examples/Openweathermap.php deleted file mode 100644 index 0b834f4..0000000 --- a/examples/Openweathermap.php +++ /dev/null @@ -1,176 +0,0 @@ - - * @version 0.1.2 - */ -class Openweathermap extends APIcaller -{ - - /** - * Openweathermap class constructor - * @param string $apiid - */ - function __construct($apiid = '') - { - parent::__construct('http://api.openweathermap.org/data/2.5/', APIcaller::METHOD_GET, 'json'); - - //Default values will be always added to the URL - if ($apiid) { - $this->setDefaultParameter('APPID', $apiid); - } - $this->setDefaultParameter('mode', 'json'); - } - - /** - * Sets the default language - * @param string $lang - * @return Openweathermap - */ - public function setLanguage($lang) - { - $this->setDefaultParameter('lang', $lang); - return $this; - } - - /** - * Sets the default units system - * @param string $lang It can be either "internal", "metric" or "imperial" - * @return Openweathermap - */ - public function setUnits($units) - { - $this->setDefaultParameter('units', $units); - return $this; - } - - /** - * Seaching current weather by city name - * @param string $cityname - * @return array - */ - public function getCurrentWeatherByCity($cityName) - { - $params = array( - 'q' => $cityName - ); - return $this->call('weather', $params); - } - - /** - * Seaching current weather by geographic coordinats - * @param double $lat - * @param double $lon - * @return array - */ - public function getCurrentWeatherByCoordinats($lat, $lon) - { - $params = array( - 'lat' => $lat, - 'lon' => $lon, - ); - return $this->call('weather', $params); - } - - /** - * Seaching current weather by city ID - * @param integer $id - * @return array - */ - public function getCurrentWeatherByID($id) - { - $params = array( - 'id' => $id - ); - return $this->call('weather', $params); - } - - /** - * Seaching forecast by city name - * @param string $cityname - * @param integer $numberOfDays - * @return array - */ - public function getForecastByCity($cityName, $numberOfDays = 1) - { - $params = array( - 'q' => $cityName, - 'cnt' => $numberOfDays - ); - return $this->call('forecast', $params); - } - - /** - * Seaching forecast by geographic coordinats - * @param double $lat - * @param double $lon - * @param integer $numberOfDays - * @return array - */ - public function getForecastByCoordinats($lat, $lon, $numberOfDays = 1) - { - $params = array( - 'lat' => $lat, - 'lon' => $lon, - 'cnt' => $numberOfDays - ); - return $this->call('forecast', $params); - } - - /** - * Seaching forecast by city ID - * @param integer $id - * @param integer $numberOfDays - * @return array - */ - public function getForecastByID($id, $numberOfDays = 1) - { - $params = array( - 'id' => $id, - 'cnt' => $numberOfDays - ); - return $this->call('forecast', $params); - } - - - /** - * Seaching forecast by city name - * @param string $cityname - * @param integer $numberOfDays - * @param string $type It can be either "like" or "accurate" - * @return array - */ - public function findByCity($cityName, $numberOfDays = 1, $type = '') - { - $params = array( - 'q' => $cityName, - 'cnt' => $numberOfDays, - 'type' => $type, - ); - return $this->call('forecast', $params); - } - - /** - * Seaching forecast by geographic coordinats - * @param double $lat - * @param double $lon - * @param integer $numberOfDays - * @param string $type It can be either "like" or "accurate" - * @return array - */ - public function findByCoordinats($lat, $lon, $numberOfDays = 1, $type = '') - { - $params = array( - 'lat' => $lat, - 'lon' => $lon, - 'cnt' => $numberOfDays, - 'type' => $type, - ); - return $this->call('forecast', $params); - } -}