HttpClient.php 2.51 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
<?php
/**
 * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
 */
namespace Temando\Shipping\Webservice;

use Temando\Shipping\Webservice\Exception\HttpRequestException;
use Temando\Shipping\Webservice\Exception\HttpResponseException;

/**
 * Wrapper around ZF2 HTTP Client
 *
 * @package  Temando\Shipping\Webservice
 * @author   Christoph Aßmann <christoph.assmann@netresearch.de>
 * @license  http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 * @link     http://www.temando.com/
 */
class HttpClient implements HttpClientInterface
{
    /**
     * @var \Zend\Http\Client
     */
    private $client;

    /**
     * HttpClient constructor.
     * @param \Zend\Http\Client $client
     */
    public function __construct(\Zend\Http\Client $client)
    {
        $this->client = $client;
    }

    /**
     * @param string[] $headers
     * @return \Zend\Http\Client
     */
    public function setHeaders(array $headers)
    {
        return $this->client->setHeaders($headers);
    }

    /**
     * @param string $uri
     * @return \Zend\Http\Client
     */
    public function setUri($uri)
    {
        return $this->client->setUri($uri);
    }

    /**
     * @param string[] $options
     * @return \Zend\Http\Client
     */
    public function setOptions(array $options)
    {
        return $this->client->setOptions($options);
    }

    /**
     * @param string $rawBody
     * @return \Zend\Http\Client
     */
    public function setRawBody($rawBody)
    {
        return $this->client->setRawBody($rawBody);
    }

    /**
     * @param string[] $queryParams
     * @return \Zend\Http\Client
     */
    public function setParameterGet($queryParams)
    {
        return $this->client->setParameterGet($queryParams);
    }

    /**
     * @param string $method
     * @return string The response body
     * @throws HttpRequestException
     * @throws HttpResponseException
     */
    public function send($method)
    {
        $this->client->setMethod($method);

        try {
            $response = $this->client->send();
        } catch (\Zend\Http\Exception\RuntimeException $e) {
            throw new HttpRequestException($e->getMessage(), $e->getCode(), $e);
        }

        if (!$response->isSuccess()) {
            throw new HttpResponseException(
                $response->getBody(),
                $response->getStatusCode(),
                null,
                $response->getHeaders()->toString()
            );
        }

        return $response->getBody();
    }
}