mekras / webapi-client
Set of classes to develop web-based API clients
This package's canonical repository appears to be gone and the package has been frozen as a result.
Installs: 3 273
Dependents: 0
Suggesters: 0
Security: 0
Stars: 9
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: ^5.6 || ^7.0
- php-http/client-implementation: ^1.0
- psr/cache: ^1.0.1
- psr/log: ^1.0
Requires (Dev)
- cache/array-adapter: ^0.4
- php-http/mock-client: ^0.3
- phpunit/phpunit: ^5.0
- satooshi/php-coveralls: dev-master
README
Set of classes to develop web-based API clients.
Goal
The goal of this library is to simplify development of web-based API clients.
Example
Sample client for phone-validator.net API:
Clinet.php:
<?php namespace Example\PhoneValidator; use Http\Client\HttpClient; use Http\Message\RequestFactory; use Mekras\WebApi\Client\ApiClient; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; class Client extends ApiClient { private $rootUrl = 'http://api.phone-validator.net/api/v2/verify'; private $apiKey; private $locale = 'en'; public function __construct(HttpClient $httpClient, RequestFactory $factory, $apiKey) { parent::__construct($httpClient, $factory); $this->apiKey = (string) $apiKey; } public function setLocale($locale) { $this->locale = (string) $locale; } public function validate($phone, $country) { $phone = trim($phone); $country = trim($country); $params = [ 'PhoneNumber' => $phone, 'CountryCode' => $country, 'Locale' => $this->locale, 'APIKey' => $this->apiKey ]; return $this->request($params); } protected function createRequest(array $params) { return $this->getRequestFactory() ->createRequest('POST', $this->rootUrl, [], http_build_query($params)); } protected function createApiResponse($response) { $json = $response->getBody()->getContents(); $this->getLogger()->debug('Server raw response: ' . $json); $array = json_decode($json, true); if (null === $array) { throw new \RuntimeException( sprintf( 'Can not decode server response: %s. Raw response: "%s"', json_last_error_msg(), $json ) ); } return new Result($array); } }
Result.php:
<?php namespace Example\PhoneValidator; use Mekras\WebApi\Client\ArrayResponse; class Result extends ArrayResponse { public function getBriefResponse() { return $this->getStatus(); } public function getInfo() { return $this->getValue('info'); } public function getStatus() { return $this->getValue('status'); } }