mekras/webapi-client

Set of classes to develop web-based API clients

v3.1.1 2016-09-20 08:02 UTC

This package is auto-updated.

Last update: 2021-06-29 01:04:40 UTC


README

Set of classes to develop web-based API clients.

Latest Stable Version License Build Status Coverage Status

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');
    }
}