Skip to content

Instantly share code, notes, and snippets.

@juriansluiman
Last active August 29, 2015 14:04
Show Gist options
  • Save juriansluiman/650d29648a9fc076f6e6 to your computer and use it in GitHub Desktop.
Save juriansluiman/650d29648a9fc076f6e6 to your computer and use it in GitHub Desktop.
<?php
namespace Foo;
use Zend\Http\Client as HttpClient;
use Zend\Http\Response as HttpResponse;
use Zend\Http\Exception\ExceptionInterface as HttpException;
use Zend\Json\Json;
class Service
{
const API_HOST = 'http://api.postcodeapi.nu/';
protected $client;
public function setClient(HttpClient $client)
{
$this->client = $client;
}
public function getClient()
{
if (null === $this->client) {
$this->client = new HttpClient;
}
return $this->client;
}
public function do()
{
// $params or something
$uri = self::API_HOST . implode('/', $params);
$client = $this->getClient();
try {
$response = $client->send($uri);
} catch (HttpException $e) {
return $this->handleError(500, $e->getMessage());
}
return $this->handleResponse($response);
}
public function handleResponse(HttpResponse $response)
{
$body = $response->getBody();
if (!$response->isSuccess()) {
$code = $response->getStatusCode();
return $this->handleError($code, $body);
}
$data = Json::decode($body);
switch ($data->success) {
// etc
}
}
}
<?php
namespace FooTest;
use Foo\Service;
use PHPUnit_Framework_TestCase as TestCase;
use Zend\Http\Response as HttpResponse;
class SerivceTest extends TestCase
{
protected $service;
protected $httpAdapter;
public function setUp()
{
$this->service = new Service;
$this->httpAdapter = new Zend\Http\Client\Adapter\Test;
$this->service->getClient()->setAdapter($this->httpAdapter);
}
public function testResponseHandlesNon20xResponse()
{
$service = $this->service;
$adapter = $this->httpAdapter;
$response = new HttpResponse;
$response->setStatusCode(500);
$response->setContent('FooBarBaz');
$adapter->setResponse($response);
$result = $service->do();
$this->assertInstanceOf('Foo\Service\Error', $result);
$this->assertEquals(500, $result->getCode());
$this->assertEquals('FooBarBaz', $result->getMessage());
}
}
<?php
namespace MyNamespace;
use Zend\Http\Client as HttpClient;
class MyService
{
protected $apiKey;
protected $httpClient;
public function __construct($apiKey, HttpClient $httpClient = null)
{
$this->apiKey = $apiKey;
if (null !== $httpClient) {
$this->httpClient = $httpClient;
}
}
public function find($postcode, $houseNumber=null)
{
/ direct $postcode en $houseNumber gebruiken
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment