Skip to content

Commit

Permalink
Merge pull request #7 from Ziptastic/2.0
Browse files Browse the repository at this point in the history
2.0 [WIP]
  • Loading branch information
jdpedrie authored Feb 11, 2019
2 parents 6227a4c + 20e4e00 commit 253b5c8
Show file tree
Hide file tree
Showing 19 changed files with 379 additions and 557 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
vendor
composer.lock
.DS_Store
clover.xml
build
8 changes: 2 additions & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
language: php
php:
- '5.4'
- '5.5'
- '5.6'
- '7.0'
install:
- mkdir -p build/logs
- 7.1
- 7.2
before_script:
- composer self-update
- composer install --prefer-source --no-interaction --dev
Expand Down
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
The MIT License (MIT)
Copyright (c) 2015 John Pedrie
Copyright (c) 2018 Ziptastic

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
Expand Down
75 changes: 40 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Ziptastic PHP

[![Build Status](https://travis-ci.org/Ziptastic/ziptastic-php.svg)](https://travis-ci.org/Ziptastic/ziptastic-php) [![Code Climate](https://codeclimate.com/github/Ziptastic/ziptastic-php/badges/gpa.svg)](https://codeclimate.com/github/Ziptastic/ziptastic-php) [![Test Coverage](https://codeclimate.com/github/Ziptastic/ziptastic-php/badges/coverage.svg)](https://codeclimate.com/github/Ziptastic/ziptastic-php/coverage)
[![Latest Stable Version](https://poser.pugx.org/ziptastic/ziptastic/v/stable)](https://packagist.org/packages/ziptastic/ziptastic) [![Build Status](https://travis-ci.org/Ziptastic/ziptastic-php.svg)](https://travis-ci.org/Ziptastic/ziptastic-php) [![Test Coverage](https://codeclimate.com/github/Ziptastic/ziptastic-php/badges/coverage.svg)](https://codeclimate.com/github/Ziptastic/ziptastic-php/coverage)

This library is a simple interface for the [Ziptastic API](https://www.getziptastic.com/).

Expand All @@ -14,56 +14,61 @@ Ziptastic PHP can be installed via composer:
composer require ziptastic/ziptastic
````

## Usage

The simplest usage defaults to the provided Curl service:
Ziptastic PHP relies on [HTTPlug](http://httplug.io/) to make API requests.
HTTPlug is an abstraction which allows you to choose from any one of a large
number of HTTP clients, including the client you might already have installed.

````php
<?php
For more information on getting started with HTTPlug, please refer to the
[HTTPlug for library users](http://docs.php-http.org/en/latest/httplug/users.html)
documentation.

include "vendor/autoload.php";
To just get moving right now, install a couple common dependencies:

$z = Ziptastic\Ziptastic\Lookup::create(getenv('ZIPTASTIC_API_KEY'));

$result = $z->lookup(48038);

?>
````
```
composer require php-http/curl-client guzzlehttp/psr7 php-http/message
```

You can also use a normal instantiation technique:
## Usage

````php
```php
<?php

include "vendor/autoload.php";

$service = new Ziptastic\Ziptastic\Service\CurlService;
$z = new Ziptastic\Ziptastic\Lookup($service, getenv('ZIPTASTIC_API_KEY'));
use Ziptastic\Client;

$result = $z->lookup(48038);
$z = Client::create(getenv('ZIPTASTIC_API_KEY'));
```

?>
````
Ziptastic provides two API methods: Lookup by a postal code (forward lookup),
and lookup by latitude and longitude (reverse lookup).

Results are returned as a collection of class LookupModel:
```php
$result = $z->forward(48038);
$result = $z->reverse(42.331427, -83.0457538, 1000);
```

````php
Results are returned as a list of arrays:

```php
<?php

$lookup = current($result);
echo $lookup->county(); // Macomb
echo $lookup->city(); // Clinton Township
echo $lookup->state(); // Michigan
echo $lookup->stateShort(); // MI
echo $lookup->postalCode(); // 48038
echo $lookup->latitude(); // 42.5868882
echo $lookup->longitude(); // -82.9195514

// timezone() returns an instance of \DateTimeZone
echo $lookup->timezone()->getName(); // America/Detroit

?>
````
echo $lookup['county']; // Macomb
echo $lookup['city']; // Clinton Township
echo $lookup['state']; // Michigan
echo $lookup['state_short']; // MI
echo $lookup['postal_code']; // 48038
echo $lookup['latitude']; // 42.5868882
echo $lookup['longitude']; // -82.9195514

// Timezones are represented by an instance of \DateTimeZone
echo $lookup['timezone']->getName(); // America/Detroit
```

### PHP 5

If you require PHP 5 compatibility, please use Ziptastic-PHP version 1.

## License

Expand Down
13 changes: 9 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@
"name": "ziptastic/ziptastic",
"description": "PHP SDK for the Ziptastic Lookup API",
"require": {
"php": ">=5.4"
"php": ">=7.1",
"php-http/client-implementation": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0",
"codeclimate/php-test-reporter": "dev-master"
"phpunit/phpunit": "^6.0",
"codeclimate/php-test-reporter": "dev-master",
"php-http/mock-client": "^1.0",
"php-http/message": "^1.0",
"php-http/curl-client": "^1.7",
"guzzlehttp/psr7": "^1.4"
},
"license": "MIT",
"authors": [
Expand All @@ -17,7 +22,7 @@
],
"autoload": {
"psr-4": {
"Ziptastic\\Ziptastic\\": "src"
"Ziptastic\\": "src"
}
},
"minimum-stability": "stable"
Expand Down
7 changes: 0 additions & 7 deletions demo.php

This file was deleted.

12 changes: 9 additions & 3 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,16 @@
</testsuite>
</testsuites>

<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory>
<exclude>./vendor</exclude>
<exclude>./tests</exclude>
</whitelist>
</filter>

<logging>
<log type="coverage-html" target="build/coverage" lowUpperBound="35"
highLowerBound="70"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
<log type="coverage-clover" target="clover.xml"/>
</logging>

</phpunit>
185 changes: 185 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
<?php

declare(strict_types=1);

namespace Ziptastic;

use Http\Client\HttpClient;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Message\MessageFactory;

/**
* The Ziptastic API class.
*
* Example:
* ```
* use Ziptastic\Client;
*
* $ziptastic = Client::create($myApiKey);
* ```
*/
class Client
{
const ZIPTASTIC_LOOKUP_URL = 'https://zip.getziptastic.com/v3/%s/%s';
const ZIPTASTIC_REVERSE_URL = 'https://zip.getziptastic.com/v3/reverse/%s/%s/%s';

/**
* @var HttpClient;
*/
private $http;

/**
* @var MessageFactory
*/
private $messageFactory;

/**
* @var string
*/
private $apiKey;

/**
* @var string
*/
private $countryCode;

/**
* @param HttpClient $http An HTTP Client implementation.
* @param MessageFactory $messageFactory An HTTP message factory implementation.
* @param string $apiKey Ziptastic API Key.
* @param string|null $countryCode 2-character country code. Currently only
* supports "US".
*/
public function __construct(
HttpClient $http,
MessageFactory $messageFactory,
string $apiKey,
string $countryCode = 'US'
) {
$this->http = $http;
$this->messageFactory = $messageFactory;
$this->apiKey = $apiKey;
$this->countryCode = $countryCode;
}

/**
* Create a client instance with the default HTTP handler.
*
* Example:
* ```
* $ziptastic = Client::create($myApiKey);
* ```
*
* @param string $apiKey Ziptastic API Key.
* @param string|null $countryCode 2-character country code. Currently only
* supports "US".
* @return Client
*/
public static function create(
string $apiKey,
string $countryCode = 'US'
): self {
$http = HttpClientDiscovery::find();
$messageFactory = MessageFactoryDiscovery::find();

return new self($http, $messageFactory, $apiKey, $countryCode);
}

/**
* Lookup locale information by a postal code.
*
* Example:
* ```
* $result = $ziptastic->forward('48226');
* foreach ($result as $item) {
* echo $item->postalCode() . PHP_EOL;
* }
* ```
*
* @param string $zipCode The lookup postal code.
* @return array[] A list of arrays containing locale data.
*/
public function forward(string $postalCode): array
{
$url = sprintf(
self::ZIPTASTIC_LOOKUP_URL,
$this->countryCode,
$postalCode
);

return $this->request($url);
}

/**
* Lookup locale information by a set of coordinates.
*
* Example:
* ```
* $result = $ziptastic->reverse(42.331427, -83.0457538);
* foreach ($result as $item) {
* echo $item->postalCode() . PHP_EOL;
* }
* ```
*
* @param float $latitude The lookup centerpoint latitude.
* @param float $longitude The lookup centerpoint longitude.
* @param integer $radius The search radius, in meters. Defaults to `1000`.
* @return array[] A list of arrays containing locale data.
*/
public function reverse(float $latitude, float $longitude, int $radius = 1000): array
{
$url = sprintf(
self::ZIPTASTIC_REVERSE_URL,
$latitude,
$longitude,
$radius
);

return $this->request($url);
}

/**
* Make a request to a given URI with the ziptastic API key.
*
* @param string $url
* @return array[] A list of arrays containing locale data.
*/
private function request(string $url): array
{
try {
$res = $this->http->sendRequest(
$this->messageFactory->createRequest('GET', $url, [
'x-key' => $this->apiKey
])
);
} catch (\Exception $e) {
throw new Exception('An error occurred: '. $e->getMessage(), $e->getCode(), $e);
}

$body = json_decode($res->getBody()->getContents(), true);

if ($res->getStatusCode() !== 200) {
$message = isset($body['message'])
? $body['message']
: 'An error occurred';

throw new Exception($message, $res->getStatusCode());
}

$collection = [];
foreach ($body as $result) {
// If the timezone is not valid, keep null.
try {
$result['timezone'] = new \DateTimeZone($result['timezone']);
} catch (\Exception $e) {
$result['timezone'] = null;
}

$collection[] = $result;

}

return $collection;
}
}
11 changes: 8 additions & 3 deletions src/Exception.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
<?php namespace Ziptastic\Ziptastic;
<?php

class Exception extends \Exception
{}
namespace Ziptastic;

/**
* Represents an error case in the Ziptastic API.
*/
class Exception extends \RuntimeException
{}
Loading

0 comments on commit 253b5c8

Please sign in to comment.