1
0
Fork 0
mirror of https://we.phorge.it/source/phorge.git synced 2024-11-22 14:52:41 +01:00

Add Balanced Payments API

Summary: Adds the Balanced PHP API to externals/. Ref T2787.

Test Plan: Used in next diff.

Reviewers: btrahan, chad

Reviewed By: chad

CC: aran, aurelijus

Maniphest Tasks: T2787

Differential Revision: https://secure.phabricator.com/D5764
This commit is contained in:
epriestley 2013-04-25 09:47:30 -07:00
parent a8bc87578e
commit 23786784ef
95 changed files with 7994 additions and 0 deletions

14
externals/balanced-php/.gitignore vendored Normal file
View file

@ -0,0 +1,14 @@
# composer
.buildpath
composer.lock
composer.phar
vendor
*~
*#
# phar
*.phar
# eclipse-pdt
.settings
.project
*.iml

8
externals/balanced-php/.travis.yml vendored Normal file
View file

@ -0,0 +1,8 @@
language: php
before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install
script: phpunit --bootstrap vendor/autoload.php --exclude-group suite tests/
php:
- 5.3
- 5.4

22
externals/balanced-php/LICENSE vendored Normal file
View file

@ -0,0 +1,22 @@
Copyright (c) 2012 Balanced
MIT License
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 the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

156
externals/balanced-php/README.md vendored Normal file
View file

@ -0,0 +1,156 @@
# Balanced
Online Marketplace Payments
[![Build Status](https://secure.travis-ci.org/balanced/balanced-php.png)](http://travis-ci.org/balanced/balanced-php)
The design of this library was heavily influenced by [Httpful](https://github.com/nategood/httpful).
## Requirements
- [PHP](http://www.php.net) >= 5.3 **with** [cURL](http://www.php.net/manual/en/curl.installation.php)
- [RESTful](https://github.com/bninja/restful) >= 0.1
- [Httpful](https://github.com/nategood/httpful) >= 0.1
## Issues
Please use appropriately tagged github [issues](https://github.com/balanced/balanced-php/issues) to request features or report bugs.
## Installation
You can install using [composer](#composer), a [phar](#phar) package or from [source](#source). Note that Balanced is [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) compliant:
### Composer
If you don't have Composer [install](http://getcomposer.org/doc/00-intro.md#installation) it:
$ curl -s https://getcomposer.org/installer | php
Add this to your `composer.json`:
{
"require": {
"balanced/balanced": "*"
}
}
Refresh your dependencies:
$ php composer.phar update
Then make sure to `require` the autoloader and initialize all:
<?php
require(__DIR__ . '/vendor/autoload.php');
\Httpful\Bootstrap::init();
\RESTful\Bootstrap::init();
\Balanced\Bootstrap::init();
...
### Phar
Download an Httpful [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/nategood/httpful/downloads):
$ curl -s -L -o httpful.phar https://github.com/downloads/nategood/httpful/httpful.phar
Download a RESTful [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/bninja/restful/downloads):
$ curl -s -L -o restful.phar https://github.com/bninja/restful/downloads/restful.phar
Download a Balanced [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/balanced/balanced-php/downloads):
$ curl -s -L -o balanced.phar https://github.com/balanced/balanced-php/downloads/balanced-{VERSION}.phar
And then `include` all:
<?php
include(__DIR__ . '/httpful.phar');
include(__DIR__ . '/restful.phar');
include(__DIR__ . '/balanced.phar');
...
### Source
Download [Httpful](https://github.com/nategood/httpful) source:
$ curl -s -L -o httpful.zip https://github.com/nategood/httpful/zipball/master;
$ unzip httpful.zip; mv nategood-httpful* httpful; rm httpful.zip
Download [RESTful](https://github.com/bninja/restful) source:
$ curl -s -L -o restful.zip https://github.com/bninja/restful/zipball/master;
$ unzip restful.zip; mv bninja-restful* restful; rm restful.zips
Download the Balanced source:
$ curl -s -L -o balanced.zip https://github.com/balanced/balanced-php/zipball/master
$ unzip balanced.zip; mv balanced-balanced-php-* balanced; rm balanced.zip
And then `require` all bootstrap files:
<?php
require(__DIR__ . "/httpful/bootstrap.php")
require(__DIR__ . "/restful/bootstrap.php")
require(__DIR__ . "/balanced/bootstrap.php")
...
## Quickstart
curl -s http://getcomposer.org/installer | php
echo '{
"require": {
"balanced/balanced": "*"
}
}' > composer.json
php composer.phar install
curl https://raw.github.com/balanced/balanced-php/master/example/example.php > example.php
php example.php
curl https://raw.github.com/balanced/balanced-php/master/example/buyer-example.php > buyer-example.php
php -S 127.0.0.1:9321 buyer-example.php
# now open a browser and go to http://127.0.0.1:9321/ to view how to tokenize cards and add to a buyer
## Usage
See https://www.balancedpayments.com/docs/overview?language=php for tutorials and documentation.
## Testing
$ phpunit --bootstrap vendor/autoload.php tests/
Or if you'd like to skip network calls:
$ phpunit --exclude-group suite --bootstrap vendor/autoload.php tests/
## Publishing
1. Ensure that **all** [tests](#testing) pass
2. Increment minor `VERSION` in `src/Balanced/Settings` and `composer.json` (`git commit -am 'v{VERSION} release'`)
3. Tag it (`git tag -a v{VERSION} -m 'v{VERSION} release'`)
4. Push the tag (`git push --tag`)
5. [Packagist](http://packagist.org/packages/balanced/balanced) will see the new tag and take it from there
6. Build (`build-phar`) and upload a [phar](http://php.net/manual/en/book.phar.php) file
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Write your code **and [tests](#testing)**
4. Ensure all tests still pass (`phpunit --bootstrap vendor/autoload.php tests/`)
5. Commit your changes (`git commit -am 'Add some feature'`)
6. Push to the branch (`git push origin my-new-feature`)
7. Create new pull request
## Contributors
* [Jacob Rus](https://github.com/jrus)
* [Leon Smith](https://github.com/leonsmith)
* [Matt Drollette](https://github.com/MDrollette)
* [You](https://github.com/balanced/balanced-php/issues)!

4
externals/balanced-php/bootstrap.php vendored Normal file
View file

@ -0,0 +1,4 @@
<?php
require(__DIR__ . '/src/Balanced/Bootstrap.php');
\Balanced\Bootstrap::init();

36
externals/balanced-php/build-phar vendored Executable file
View file

@ -0,0 +1,36 @@
#!/usr/bin/php
<?php
include('src/Balanced/Settings.php');
function exit_unless($condition, $msg = null) {
if ($condition)
return;
echo "[FAIL] $msg";
exit(1);
}
echo "Building Phar... ";
$base_dir = dirname(__FILE__);
$source_dir = $base_dir . '/src/Balanced/';
$phar_name = 'balanced.phar';
$phar_path = $base_dir . '/' . $phar_name;
$phar = new Phar($phar_path, 0, $phar_name);
$stub = <<<HEREDOC
<?php
// Phar Stub File
Phar::mapPhar('balanced.phar');
include('phar://balanced.phar/Balanced/Bootstrap.php');
\Balanced\Bootstrap::pharInit();
__HALT_COMPILER();
HEREDOC;
$phar->setStub($stub);
exit_unless($phar, "Unable to create a phar. Make sure you have phar.readonly=0 set in your ini file.");
$phar->buildFromDirectory(dirname($source_dir));
echo "[ OK ]\n";
echo "Renaming Phar... ";
$phar_versioned_name = 'balanced-' . \Balanced\Settings::VERSION . '.phar';
$phar_versioned_path = $base_dir . '/' . $phar_versioned_name;
rename($phar_path, $phar_versioned_path);
echo "[ OK ]\n";

24
externals/balanced-php/composer.json vendored Normal file
View file

@ -0,0 +1,24 @@
{
"name": "balanced/balanced",
"description": "Client for Balanced API",
"homepage": "http://github.com/balanced/balanced-php",
"license": "MIT",
"keywords": ["payments", "api"],
"version": "0.7.1",
"authors": [
{
"name": "Balanced",
"email": "dev@balancedpayments.com",
"homepage": "http://www.balancedpayments.com"
}
],
"require": {
"nategood/httpful": "*",
"bninja/restful": "*"
},
"autoload": {
"psr-0": {
"Balanced": "src/"
}
}
}

View file

@ -0,0 +1,54 @@
<?php
//
// Learn how to authenticate a bank account so you can debit with it.
//
require(__DIR__ . '/vendor/autoload.php');
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();
// create a new marketplace
$key = new Balanced\APIKey();
$key->save();
Balanced\Settings::$api_key = $key->secret;
$marketplace = new Balanced\Marketplace();
$marketplace->save();
// create a bank account
$bank_account = $marketplace->createBankAccount("Jack Q Merchant",
"123123123",
"123123123"
);
$buyer = $marketplace->createAccount("buyer@example.org");
$buyer->addBankAccount($bank_account);
print("you can't debit from a bank account until you verify it\n");
try {
$buyer->debit(100);
} catch (Exception $e) {
printf("Debit failed, %s\n", $e->getMessage());
}
// authenticate
$verification = $bank_account->verify();
try {
$verification->confirm(1, 2);
} catch (Balanced\Errors\BankAccountVerificationFailure $e) {
printf('Authentication error , %s\n', $e->getMessage());
print("PROTIP: for TEST bank accounts the valid amount is always 1 and 1\n");
}
$verification->confirm(1, 1);
$debit = $buyer->debit(100);
printf("debited the bank account %s for %d cents\n",
$debit->source->uri,
$debit->amount
);
print("and there you have it");
?>

View file

@ -0,0 +1,157 @@
<?php
require(__DIR__ . '/vendor/autoload.php');
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();
$API_KEY_SECRET = '5f4db668a5ec11e1b908026ba7e239a9';
$page = $_SERVER['REQUEST_URI'];
Balanced\Settings::$api_key = $API_KEY_SECRET;
$marketplace = Balanced\Marketplace::mine();
if ($page == '/') {
// do nothing
} elseif ($page == '/buyer') {
if (isset($_POST['uri']) and isset($_POST['email_address'])) {
// create in balanced
$email_address = $_POST['email_address'];
$card_uri = $_POST['uri'];
try {
echo create_buyer($email_address, $card_uri)->uri;
return;
} catch (Balanced\Errors\Error $e) {
echo $e->getMessage();
return;
}
}
}
function create_buyer($email_address, $card_uri) {
$marketplace = Balanced\Marketplace::mine();
try {
# new buyer
$buyer = $marketplace->createBuyer(
$email_address,
$card_uri);
}
catch (Balanced\Errors\DuplicateAccountEmailAddress $e) {
# oops, account for $email_address already exists so just add the card
$buyer = Balanced\Account::get($e->extras->account_uri);
$buyer->addCard($card_uri);
}
return $buyer;
}
?>
<html>
<head>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" type="text/css">
<style type="text/css">
[name="marketplace_eid"] {
width: 300px;
}
[name^="expiration"] {
width: 50px;
}
[name="security_code"] {
width: 50px;
}
code { display: block; }
pre { color: green; }
</style>
</head>
<body>
<h1>Balanced Sample - Collect Credit Card Information</h1>
<div class="row">
<div class="span6">
<form id="payment">
<div>
<label>Email Address</label>
<input name="email_address" value="bob@example.com">
</div>
<div>
<label>Card Number</label>
<input name="card_number" value="4111111111111111" autocomplete="off">
</div>
<div>
<label>Expiration</label>
<input name="expiration_month" value="1"> / <input name="expiration_year" value="2020">
</div>
<div>
<label>Security Code</label>
<input name="security_code" value="123" autocomplete="off">
</div>
<button>Submit Payment Data</button>
</form>
</div>
</div>
<div id="result"></div>
<script type="text/javascript" src="https://js.balancedpayments.com/v1/balanced.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var marketplaceUri = '<?php echo $marketplace->uri; ?>';
var debug = function (tag, content) {
$('<' + tag + '>' + content + '</' + tag + '>').appendTo('#result');
};
try {
balanced.init(marketplaceUri);
} catch (e) {
debug('code', 'You need to set the marketplaceUri variable');
}
function accountCreated(response) {
debug('code', 'account create result: ' + response);
}
function balancedCallback(response) {
var tag = (response.status < 300) ? 'pre' : 'code';
debug(tag, JSON.stringify(response));
switch (response.status) {
case 201:
// response.data.uri == uri of the card resource, submit to your server
$.post('/buyer', {
uri: response.data.uri,
email_address: $('[name="email_address"]').val()
}, accountCreated);
case 400:
case 403:
// missing/malformed data - check response.error for details
break;
case 402:
// we couldn't authorize the buyer's credit card - check response.error for details
break;
case 404:
// your marketplace URI is incorrect
break;
default:
// we did something unexpected - check response.error for details
break;
}
}
var tokenizeCard = function(e) {
e.preventDefault();
var $form = $('form#payment');
var cardData = {
card_number: $form.find('[name="card_number"]').val(),
expiration_month: $form.find('[name="expiration_month"]').val(),
expiration_year: $form.find('[name="expiration_year"]').val(),
security_code: $form.find('[name="security_code"]').val()
};
balanced.card.create(cardData, balancedCallback);
};
$('#payment').submit(tokenizeCard);
if (window.location.protocol === 'file:') {
alert("balanced.js does not work when included in pages served over file:// URLs. Try serving this page over a webserver. Contact support@balancedpayments.com if you need assistance.");
}
</script>
</body>
</html>

View file

@ -0,0 +1,5 @@
{
"require": {
"balanced/balanced": "*"
}
}

View file

@ -0,0 +1,42 @@
<?php
require('vendor/autoload.php');
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();
$API_KEY_SECRET = '5f4db668a5ec11e1b908026ba7e239a9';
Balanced\Settings::$api_key = $API_KEY_SECRET;
$marketplace = Balanced\Marketplace::mine();
print "create a card\n";
$card = $marketplace->cards->create(array(
"card_number" => "5105105105105100",
"expiration_month" => "12",
"expiration_year" => "2015"
));
print "our card: " . $card->uri . "\n";
print "create a **buyer** account with that card\n";
$buyer = $marketplace->createBuyer(null, $card->uri);
print "our buyer account: " . $buyer->uri . "\n";
print "debit our buyer, let's say $15\n";
try {
$debit = $buyer->debit(1500);
print "our buyer debit: " . $debit->uri . "\n";
}
catch (Balanced\Errors\Declined $e) {
print "oh no, the processor declined the debit!\n";
}
catch (Balanced\Errors\NoFundingSource $e) {
print "oh no, the buyer has not active funding sources!\n";
}
catch (Balanced\Errors\CannotDebit $e) {
print "oh no, the buyer has no debitable funding sources!\n";
}
print "and there you have it 8)\n";
?>

View file

@ -0,0 +1,59 @@
<?php
/*
* Welcome weary traveller. Sick of polling for state changes? Well today have
* I got good news for you. Run this example below to see how to get yourself
* some callback goodness and to understand how events work.
*/
require(__DIR__ . "/vendor/autoload.php");
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();
// create a new marketplace
$key = new Balanced\APIKey();
$key->save();
Balanced\Settings::$api_key = $key->secret;
$marketplace = new Balanced\Marketplace();
$marketplace->save();
// let"s create a requestb.in
$ch = curl_init("http://requestb.in/api/v1/bins");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . 0)
);
$result = json_decode(curl_exec($ch));
$bin_name = $result->name;
$callback_url = "http://requestb.in/" . $bin_name;
$requests_url = "http://requestb.in/api/v1/bins/" . $bin_name . "/requests";
printf("let's create a callback\n");
$marketplace->createCallback($callback_url);
printf("let's create a card and associate it with a new account\n");
$card = $marketplace->cards->create(array(
"card_number" => "5105105105105100",
"expiration_month" => "12",
"expiration_year" => "2015"
));
$buyer = $marketplace->createBuyer("buyer@example.org", $card->uri);
printf("generate a debit (which implicitly creates and captures a hold)\n");
$buyer->debit(100);
foreach ($marketplace->events as $event) {
printf("this was a %s event, it occurred at %s\n",
$event->type,
$event->occurred_at
);
}
printf("ok, let's check with requestb.in to see if our callbacks fired at %s\n", $callback_url);
printf("we received callbacks, you can view them at http://requestb.in/%s?inspect\n",
$bin_name
);
?>

View file

@ -0,0 +1,120 @@
<?php
require('vendor/autoload.php');
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();
print "create our new api key\n";
$key = new Balanced\APIKey();
$key->save();
print "Our secret is " . $key->secret . "\n";
print "configure with our secret " . $key->secret . "\n";
Balanced\Settings::$api_key = $key->secret;
print "create our marketplace";
$marketplace = new Balanced\Marketplace();
$marketplace->save();
if (Balanced\Merchant::me() == null) {
throw new Exception("Balanced\Merchant::me() should not be null");
}
print "What's my merchant? Easy: Balanced\Merchant::me(): " . Balanced\Merchant::me()->uri . "\n";
if (Balanced\Marketplace::mine() == null) {
throw new Exception("Balanced\Marketplace::mine() should never be null");
}
print "What's my marketplace? Easy: Balanced\Marketplace::mine(): " .Balanced\Marketplace::mine()->uri . "\n";
print "My marketplace's name is " . $marketplace->name . "\n";
print "Changing it to TestFooey\n";
$marketplace->name = "TestFooey";
$marketplace->save();
print "My marketplace name is now " . $marketplace->name . "\n";
if ($marketplace->name != "TestFooey") {
throw new Exception("Marketplace name is NOT TestFooey");
}
print "Cool, let's create a card\n";
$card = $marketplace->cards->create(array(
"card_number" => "5105105105105100",
"expiration_month" => "12",
"expiration_year" => "2015"
));
print "Our card: " . $card->uri . "\n";
print "Create out **buyer** account\n";
$buyer = $marketplace->createBuyer("buyer@example.org", $card->uri);
print "our buyer account: " . $buyer->uri . "\n";
print "hold some amount of funds on the buyer, let's say $15\n";
$the_hold = $buyer->hold(1500);
print "ok, no more holds! let's capture it (for the full amount)\n";
$debit = $the_hold->capture();
print "hmm, ho much money do i have in escrow? it should equal the debit amount\n";
$marketplace = Balanced\Marketplace::mine();
if ($marketplace->in_escrow != 1500) {
throw new Exception("1500 is not in escrow! This is wrong");
}
print "I have " . $marketplace->in_escrow . " in escrow!\n";
print "Cool. now let me refund the full amount";
$refund = $debit->refund();
print "ok, we have a merchant that's signing up, let's create an account for them first, let's create their bank account\n";
$bank_account = $marketplace->createBankAccount("Jack Q Merchant",
"123123123", /* account_number */
"123123123" /* bank_code (routing number is USA)*/
);
$identity = array(
"type" => "person",
"name" => "Billy Jones",
"street_address" => "801 High St",
"postal_code" => "94301",
"country" => "USA",
"dob" => "1979-02",
"phone_number" => "+16505551234"
);
$merchant = $marketplace->createMerchant('merchant@example.org',
$identity,
$bank_account->uri
);
print "our buyer is interested in buying something for $130\n";
$another_debit = $buyer->debit(13000, "MARKETPLACE.COM");
print "let's credit our merchant $110\n";
$credit = $merchant->credit(11000, "Buyer purchase something on Marketplace.com");
print "let's assume the marketplace charges 15%, so it earned $20\n";
$mp_credit = $marketplace->owner_account->credit(2000,
"Commission from MARKETPLACE.COM");
print "ok, let's invalidate the card used so it cannot be used again\n";
$card->is_valid = false;
$card->save();
print "how do we look up an existing object from the URI?\n";
$the_buyer = Balanced\Account::get($buyer->uri);
print "we got the buyer " . $the_buyer->email_address . "\n";
$the_debit = Balanced\Debit::get($debit->uri);
print "we got the debit: " . $the_debit->uri . "\n";
$the_credit = Balanced\Credit::get($credit->uri);
print "we got the credit: " . $the_credit->uri . "\n";
print "and there you have it :)\n";
?>

View file

@ -0,0 +1,71 @@
<?
require('vendor/autoload.php');
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
Balanced\Bootstrap::init();
$key = new Balanced\APIKey();
$key->save();
Balanced\Settings::$api_key = $key->secret;
$marketplace = new Balanced\Marketplace();
$marketplace->save();
$card = $marketplace->cards->create(array(
"card_number" => "5105105105105100",
"expiration_month" => "12",
"expiration_year" => "2015"
));
$buyer = $marketplace->createBuyer("buyer@example.com", $card->uri);
$debit = $buyer->debit(1500);
$debit->refund(100);
$debit->refund(100);
$debit->refund(100);
echo $debit->refunds->total() . " refunds" . "\n";
$total = 0;
foreach ($debit->refunds as $r) {
$total += $r->amount;
print "refund = " . $r->amount . "\n";
}
print $total . "\n";
# bigger pagination example
print "Create 60 **buyer** with cards accounts\n";
for ($i = 0; $i < 60; $i++) {
$card = $marketplace->cards->create(array(
"card_number" => "5105105105105100",
"expiration_month" => "12",
"expiration_year" => "2015"
));
$buyer = $marketplace->createBuyer("buyer" . $i . "@example.org", $card->uri);
print '.';
}
print "\n";
$cards = $marketplace->cards;
print $cards->total() . " cards in Marketplace\n";
foreach ($cards as $c) {
print "card " . $c->uri . "\n";
}
# let's iterate through cards for just a single account
foreach ($buyer->cards as $c) {
print "buyer's card " . $c->uri . "\n";
}
print "and there you have it :)\n";
?>

View file

@ -0,0 +1,14 @@
<?php
// run this file to test your composer install of Balanced
require(__DIR__ . '/vendor/autoload.php');
\Httpful\Bootstrap::init();
\RESTful\Bootstrap::init();
\Balanced\Bootstrap::init();
echo "[ OK ]\n";
echo "balanced version -- " . \Balanced\Settings::VERSION . " \n";
echo "restful version -- " . \RESTful\Settings::VERSION . " \n";
echo "httpful version -- " . \Httpful\Httpful::VERSION . " \n";

View file

@ -0,0 +1,12 @@
<?php
// run this file to test your phar install of Balanced
include(__DIR__ . '/httpful.phar');
include(__DIR__ . '/restful.phar');
include(__DIR__ . '/balanced.phar');
echo "[ OK ]\n";
echo "balanced version -- " . \Balanced\Settings::VERSION . " \n";
echo "restful version -- " . \RESTful\Settings::VERSION . " \n";
echo "httpful version -- " . \Httpful\Httpful::VERSION . " \n";

View file

@ -0,0 +1,12 @@
<?php
// run this file to test your source install of Balanced
require(__DIR__ . "/httpful/bootstrap.php");
require(__DIR__ . "/restful/bootstrap.php");
require(__DIR__ . "/balanced/bootstrap.php");
echo "[ OK ]\n";
echo "balanced version -- " . \Balanced\Settings::VERSION . " \n";
echo "restful version -- " . \RESTful\Settings::VERSION . " \n";
echo "httpful version -- " . \Httpful\Httpful::VERSION . " \n";

View file

@ -0,0 +1,55 @@
<?php
namespace Balanced;
use Balanced\Resource;
use Balanced\Settings;
use \RESTful\URISpec;
/**
* Represents an api key. These are used to authenticate you with the api.
*
* Typically you create an initial api key:
*
* <code>
* print \Balanced\Settings::$api_key == null;
* $api_key = new \Balanced\APIKey();
* $api_key = api_key->save();
* $secret = $api_key->secret;
* print $secret;
* </code>
*
* Then save the returned secret (we don't store it) and configure the client
* to use it:
*
* <code>
* \Balanced\Settings::$api_key = 'my-api-key-secret';
* </code>
*
* You can later add another api key if you'd like to rotate or expire old
* ones:
*
* <code>
* $api_key = new \Balanced\APIKey();
* $api_key = api_key->save();
* $new_secret = $api_key->secret;
* print $new_secret;
*
* \Balanced\Settings::$api_key = $new_secret;
*
* \Balanced\APIKey::query()
* ->sort(\Balanced\APIKey::f->created_at->desc())
* ->first()
* ->delete();
* </code>
*/
class APIKey extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('api_keys', 'id', '/v1');
self::$_registry->add(get_called_class());
}
}

View file

@ -0,0 +1,217 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represent a buyer or merchant account on a marketplace.
*
* You create these using Balanced\Marketplace->createBuyer or
* Balanced\Marketplace->createMerchant.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $card = $marketplace->cards->create(array(
* 'street_address' => $street_address,
* 'city' => 'Jollywood',
* 'region' => 'CA',
* 'postal_code' => '90210',
* 'name' => 'Captain Chunk',
* 'card_number' => '4111111111111111',
* 'expiration_month' => 7,
* 'expiration_year' => 2015
* ));
*
* $buyer = $marketplace->createBuyer(
* 'buyer@example.com',
* $card->uri,
* array(
* 'my_id' => '1212121',
* )
* );
* </code>
*
* @see Balanced\Marketplace->createBuyer
* @see Balanced\Marketplace->createMerchant
*/
class Account extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('accounts', 'id');
self::$_registry->add(get_called_class());
}
/**
* Credit the account.
*
* @param int amount Amount to credit the account in USD pennies.
* @param string description Optional description of the credit.
* @param array[string]string meta Optional metadata to associate with the credit.
* @param mixed destination Optional URI of a funding destination (i.e. \Balanced\BankAccount) associated with this account to credit. If not specified the funding destination most recently added to the account is used.
* @param string appears_on_statement_as Optional description of the credit as it will appears on the customer's billing statement.
*
* @return \Balanced\Credit
*/
public function credit(
$amount,
$description = null,
$meta = null,
$destination = null,
$appears_on_statement_as = null)
{
if ($destination == null)
$destination_uri = null;
else
$destination_uri = is_string($destination) ? $destination : $destination->uri;
return $this->credits->create(array(
'amount' => $amount,
'description' => $description,
'meta' => $meta,
'destination_uri' => $destination_uri,
'appears_on_statement_as' => $appears_on_statement_as
));
}
/**
* Debit the account.
*
* @param int amount Amount to debit the account in USD pennies.
* @param string appears_on_statement_as Optional description of the debit as it will appears on the customer's billing statement.
* @param string description Optional description of the debit.
* @param array[string]string meta Optional metadata to associate with the debit.
* @param mixed Optional funding source (i.e. \Balanced\Card) or URI of a funding source associated with this account to debit. If not specified the funding source most recently added to the account is used.
*
* @return \Balanced\Debit
*/
public function debit(
$amount,
$appears_on_statement_as = null,
$description = null,
$meta = null,
$source = null,
$on_behalf_of = null)
{
if ($source == null) {
$source_uri = null;
} else if (is_string($source)) {
$source_uri = $source;
} else {
$source_uri = $source->uri;
}
if ($on_behalf_of == null) {
$on_behalf_of_uri = null;
} else if (is_string($on_behalf_of)) {
$on_behalf_of_uri = $on_behalf_of;
} else {
$on_behalf_of_uri = $on_behalf_of->uri;
}
if (isset($this->uri) && $on_behalf_of_uri == $this->uri)
throw new \InvalidArgumentException(
'The on_behalf_of parameter MAY NOT be the same account as the account you are debiting!'
);
return $this->debits->create(array(
'amount' => $amount,
'description' => $description,
'meta' => $meta,
'source_uri' => $source_uri,
'on_behalf_of_uri' => $on_behalf_of_uri,
'appears_on_statement_as' => $appears_on_statement_as
));
}
/**
* Create a hold (i.e. a guaranteed pending debit) for account funds. You
* can later capture or void. A hold is associated with a account funding
* source (i.e. \Balanced\Card). If you don't specify the source then the
* current primary funding source for the account is used.
*
* @param int amount Amount of the hold in USD pennies.
* @param string Optional description Description of the hold.
* @param string Optional URI referencing the card to use for the hold.
* @param array[string]string meta Optional metadata to associate with the hold.
*
* @return \Balanced\Hold
*/
public function hold(
$amount,
$description = null,
$source_uri = null,
$meta = null)
{
return $this->holds->create(array(
'amount' => $amount,
'description' => $description,
'source_uri' => $source_uri,
'meta' => $meta
));
}
/**
* Creates or associates a created card with the account. The default
* funding source for the account will be this card.
*
* @see \Balanced\Marketplace->createCard
*
* @param mixed card \Balanced\Card or URI referencing a card to associate with the account. Alternatively it can be an associative array describing a card to create and associate with the account.
*
* @return \Balanced\Account
*/
public function addCard($card)
{
if (is_string($card))
$this->card_uri = $card;
else if (is_array($card))
$this->card = $card;
else
$this->card_uri = $card->uri;
return $this->save();
}
/**
* Creates or associates a created bank account with the account. The
* new default funding destination for the account will be this bank account.
*
* @see \Balanced\Marketplace->createBankAccount
*
* @param mixed bank_account \Balanced\BankAccount or URI for a bank account to associate with the account. Alternatively it can be an associative array describing a bank account to create and associate with the account.
*
* @return \Balanced\Account
*/
public function addBankAccount($bank_account)
{
if (is_string($bank_account))
$this->bank_account_uri = $bank_account;
else if (is_array($bank_account))
$this->bank_account = $bank_account;
else
$this->bank_account_uri = $bank_account->uri;
return $this->save();
}
/**
* Promotes a role-less or buyer account to a merchant.
*
* @see Balanced\Marketplace::createMerchant
*
* @param mixed merchant Associative array describing the merchants identity or a URI referencing a created merchant.
*
* @return \Balanced\Account
*/
public function promoteToMerchant($merchant)
{
if (is_string($merchant))
$this->merchant_uri = $merchant;
else
$this->merchant = $merchant;
return $this->save();
}
}

View file

@ -0,0 +1,127 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents an account bank account.
*
* You can create these via Balanced\Marketplace::bank_accounts::create or
* Balanced\Marketplace::createBankAccount. Associate them with a buyer or
* merchant one creation via Balanced\Marketplace::createBuyer or
* Balanced\Marketplace::createMerchant and with an existing buyer or merchant
* use Balanced\Account::addBankAccount.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $bank_account = $marketplace->bank_accounts->create(array(
* 'name' => 'name',
* 'account_number' => '11223344',
* 'bank_code' => '1313123',
* ));
*
* $account = $marketplace
* ->accounts
* ->query()
* ->filter(Account::f->email_address->eq('merchant@example.com'))
* ->one();
* $account->addBankAccount($bank_account->uri);
* </code>
*/
class BankAccount extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('bank_accounts', 'id', '/v1');
self::$_registry->add(get_called_class());
}
/**
* Credit a bank account.
*
* @param int amount Amount to credit in USD pennies.
* @param string description Optional description of the credit.
* @param string appears_on_statement_as Optional description of the credit as it will appears on the customer's billing statement.
*
* @return \Balanced\Credit
*
* <code>
* $bank_account = new \Balanced\BankAccount(array(
* 'account_number' => '12341234',
* 'name' => 'Fit Finlay',
* 'bank_code' => '325182797',
* 'type' => 'checking',
* ));
*
* $credit = $bank_account->credit(123, 'something descriptive');
* </code>
*/
public function credit(
$amount,
$description = null,
$meta = null,
$appears_on_statement_as = null)
{
if (!property_exists($this, 'account') || $this->account == null) {
$credit = $this->credits->create(array(
'amount' => $amount,
'description' => $description,
));
} else {
$credit = $this->account->credit(
$amount,
$description,
$meta,
$this->uri,
$appears_on_statement_as
);
}
return $credit;
}
public function verify()
{
$response = self::getClient()->post(
$this->verifications_uri, null
);
$verification = new BankAccountVerification();
$verification->_objectify($response->body);
return $verification;
}
}
/**
* Represents an verification for a bank account which is a pre-requisite if
* you want to create debits using the associated bank account. The side-effect
* of creating a verification is that 2 random amounts will be deposited into
* the account which must then be confirmed via the confirm method to ensure
* that you have access to the bank account in question.
*
* You can create these via Balanced\Marketplace::bank_accounts::verify.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $bank_account = $marketplace->bank_accounts->create(array(
* 'name' => 'name',
* 'account_number' => '11223344',
* 'bank_code' => '1313123',
* ));
*
* $verification = $bank_account->verify();
* </code>
*/
class BankAccountVerification extends Resource {
public function confirm($amount1, $amount2) {
$this->amount_1 = $amount1;
$this->amount_2 = $amount2;
$this->save();
return $this;
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Balanced;
/**
* Bootstrapper for Balanced does autoloading and resource initialization.
*/
class Bootstrap
{
const DIR_SEPARATOR = DIRECTORY_SEPARATOR;
const NAMESPACE_SEPARATOR = '\\';
public static $initialized = false;
public static function init()
{
spl_autoload_register(array('\Balanced\Bootstrap', 'autoload'));
self::initializeResources();
}
public static function autoload($classname)
{
self::_autoload(dirname(dirname(__FILE__)), $classname);
}
public static function pharInit()
{
spl_autoload_register(array('\Balanced\Bootstrap', 'pharAutoload'));
self::initializeResources();
}
public static function pharAutoload($classname)
{
self::_autoload('phar://balanced.phar', $classname);
}
private static function _autoload($base, $classname)
{
if (!strncmp($classname, 'Balanced\Errors\\', strlen('Balanced\Errors\\')))
$classname = 'Balanced\Errors';
$parts = explode(self::NAMESPACE_SEPARATOR, $classname);
$path = $base . self::DIR_SEPARATOR. implode(self::DIR_SEPARATOR, $parts) . '.php';
if (file_exists($path)) {
require_once($path);
}
}
/**
* Initializes resources (i.e. registers them with Resource::_registry). Note
* that if you add a Resource then you must initialize it here.
*
* @internal
*/
private static function initializeResources()
{
if (self::$initialized)
return;
\Balanced\Errors\Error::init();
\Balanced\Resource::init();
\Balanced\APIKey::init();
\Balanced\Marketplace::init();
\Balanced\Account::init();
\Balanced\Credit::init();
\Balanced\Debit::init();
\Balanced\Refund::init();
\Balanced\Card::init();
\Balanced\BankAccount::init();
\Balanced\Hold::init();
\Balanced\Merchant::init();
\Balanced\Callback::init();
\Balanced\Event::init();
self::$initialized = true;
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/*
* A Callback is a publicly accessible location that can receive POSTed JSON
* data whenever an Event is generated.
*
* You create these using Balanced\Marketplace->createCallback.
*
*/
class Callback extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('callbacks', 'id');
self::$_registry->add(get_called_class());
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents an account card.
*
* You can create these via Balanced\Marketplace::cards::create or
* Balanced\Marketplace::createCard. Associate them with a buyer or merchant
* one creation via Marketplace::createBuyer or
* Balanced\Marketplace::createMerchant and with an existing buyer or merchant
* use Balanced\Account::addCard.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $card = $marketplace->cards->create(array(
* 'name' => 'name',
* 'account_number' => '11223344',
* 'bank_code' => '1313123'
* ));
*
* $account = $marketplace
* ->accounts
* ->query()
* ->filter(Account::f->email_address->eq('buyer@example.com'))
* ->one();
* $account->addCard($card->uri);
* </code>
*/
class Card extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('cards', 'id', '/v1');
self::$_registry->add(get_called_class());
}
public function debit(
$amount,
$appears_on_statement_as = null,
$description = null,
$meta = null,
$source = null)
{
if ($this->account == null) {
throw new \UnexpectedValueException('Card is not associated with an account.');
}
return $this->account->debit(
$amount,
$appears_on_statement_as,
$description,
$meta,
$this->uri);
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents an account credit transaction.
*
* You create these using Balanced\Account::credit.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $account = $marketplace
* ->accounts
* ->query()
* ->filter(Account::f->email_address->eq('merchant@example.com'))
* ->one();
*
* $credit = $account->credit(
* 100,
* 'how it '
* array(
* 'my_id': '112233'
* )
* );
* </code>
*/
class Credit extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('credits', 'id', '/v1');
self::$_registry->add(get_called_class());
}
/**
* Credit an unstored bank account.
*
* @param int amount Amount to credit in USD pennies.
* @param string description Optional description of the credit.
* @param mixed bank_account Associative array describing a bank account to credit. The bank account will *not* be stored.
*
* @return \Balanced\Credit
*
* <code>
* $credit = \Balanced\Credit::bankAccount(
* 123,
* array(
* 'account_number' => '12341234',
* 'name' => 'Fit Finlay',
* 'bank_code' => '325182797',
* 'type' => 'checking',
* ),
* 'something descriptive');
* </code>
*/
public static function bankAccount(
$amount,
$bank_account,
$description = null)
{
$credit = new Credit(array(
'amount' => $amount,
'bank_account' => $bank_account,
'description' => $description
));
$credit->save();
return $credit;
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents an account debit transaction.
*
* You create these using Balanced\Account::debit.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $account = $marketplace
* ->accounts
* ->query()
* ->filter(Account::f->email_address->eq('buyer@example.com'))
* ->one();
*
* $debit = $account->debit(
* 100,
* 'how it appears on the statement',
* 'a description',
* array(
* 'my_id': '443322'
* )
* );
* </code>
*/
class Debit extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('debits', 'id');
self::$_registry->add(get_called_class());
}
/**
* Create a refund for this debit. You can create multiple refunds for a
* debit but the total amount of the refunds must be less than the debit
* amount.
*
* @param int amount Optional amount of the refund in USD pennies. If unspecified then the full debit amount is used.
* @param string description Optional description of the refund.
* @param array[string]string meta Optional metadata to associate with the refund.
*
* @return \Balanced\Refund
*/
public function refund(
$amount = null,
$description = null,
$meta = null)
{
return $this->refunds->create(array(
'amount' => $amount,
'description' => $description,
'meta' => $meta
));
}
}

View file

@ -0,0 +1,135 @@
<?php
namespace Balanced\Errors;
use RESTful\Exceptions\HTTPError;
class Error extends HTTPError
{
public static $codes = array();
public static function init()
{
foreach (get_declared_classes() as $class) {
$parent_class = get_parent_class($class);
if ($parent_class != 'Balanced\Errors\Error')
continue;
foreach ($class::$codes as $type)
self::$codes[$type] = $class;
}
}
}
class DuplicateAccountEmailAddress extends Error
{
public static $codes = array('duplicate-email-address');
}
class InvalidAmount extends Error
{
public static $codes = array('invalid-amount');
}
class InvalidRoutingNumber extends Error
{
public static $codes = array('invalid-routing-number');
}
class InvalidBankAccountNumber extends Error
{
public static $codes = array('invalid-bank-account-number');
}
class Declined extends Error
{
public static $codes = array('funding-destination-declined', 'authorization-failed');
}
class CannotAssociateMerchantWithAccount extends Error
{
public static $codes = array('cannot-associate-merchant-with-account');
}
class AccountIsAlreadyAMerchant extends Error
{
public static $codes = array('account-already-merchant');
}
class NoFundingSource extends Error
{
public static $codes = array('no-funding-source');
}
class NoFundingDestination extends Error
{
public static $codes = array('no-funding-destination');
}
class CardAlreadyAssociated extends Error
{
public static $codes = array('card-already-funding-src');
}
class CannotAssociateCard extends Error
{
public static $codes = array('cannot-associate-card');
}
class BankAccountAlreadyAssociated extends Error
{
public static $codes = array('bank-account-already-associated');
}
class AddressVerificationFailed extends Error
{
public static $codes = array('address-verification-failed');
}
class HoldExpired extends Error
{
public static $codes = array('authorization-expired');
}
class MarketplaceAlreadyCreated extends Error
{
public static $codes = array('marketplace-already-created');
}
class IdentityVerificationFailed extends Error
{
public static $codes = array('identity-verification-error', 'business-principal-kyc', 'business-kyc', 'person-kyc');
}
class InsufficientFunds extends Error
{
public static $codes = array('insufficient-funds');
}
class CannotHold extends Error
{
public static $codes = array('funding-source-not-hold');
}
class CannotCredit extends Error
{
public static $codes = array('funding-destination-not-creditable');
}
class CannotDebit extends Error
{
public static $codes = array('funding-source-not-debitable');
}
class CannotRefund extends Error
{
public static $codes = array('funding-source-not-refundable');
}
class BankAccountVerificationFailure extends Error
{
public static $codes = array(
'bank-account-authentication-not-pending',
'bank-account-authentication-failed',
'bank-account-authentication-already-exists'
);
}

View file

@ -0,0 +1,23 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/*
* An Event is a snapshot of another resource at a point in time when
* something significant occurred. Events are created when resources are
* created, updated, deleted or otherwise change state such as a Credit
* being marked as failed.
*/
class Event extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('events', 'id', '/v1');
self::$_registry->add(get_called_class());
}
}

View file

@ -0,0 +1,77 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents pending debit of funds for an account. The funds for that debit
* are held by the processor. You can later capture the hold, which results in
* debit, or void it, which releases the held funds.
*
* Note that a hold can expire so you should always check
* Balanced\Hold::expires_at.
*
* You create these using \Balanced\Account::hold.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $account = $marketplace
* ->accounts
* ->query()
* ->filter(Account::f->email_address->eq('buyer@example.com'))
* ->one();
*
* $hold = $account->hold(
* 100,
* 'a description',
* null,
* array(
* 'my_id': '1293712837'
* )
* );
*
* $debit = $hold->capture();
* </code>
*/
class Hold extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('holds', 'id');
self::$_registry->add(get_called_class());
}
/**
** Voids a pending hold. This releases the held funds. Once voided a hold
* is not longer pending can cannot be re-captured or re-voided.
*
* @return \Balanced\Hold
*/
public function void()
{
$this->is_void = true;
return $this->save();
}
/**
* Captures a pending hold. This results in a debit. Once captured a hold
* is not longer pending can cannot be re-captured or re-voided.
*
* @param int amount Optional Portion of the pending hold to capture. If not specified the full amount associated with the hold is captured.
*
* @return \Balanced\Debit
*/
public function capture($amount = null)
{
$this->debit = $this->account->debits->create(array(
'hold_uri' => $this->uri,
'amount' => $amount,
));
return $this->debit;
}
}

View file

@ -0,0 +1,325 @@
<?php
namespace Balanced;
use Balanced\Resource;
use Balanced\Errors;
use Balanced\Account;
use \RESTful\URISpec;
/**
* Represents a marketplace.
*
* To get started you create an api key and then create a marketplace:
*
* <code>
* $api_key = new \Balanced\APIKey();
* $api_key->save();
* $secret = $api_key->secret // better save this somewhere
* print $secret;
* \Balanced\Settings::$api_key = $secret;
*
* $marketplace = new \Balanced\Marketplace();
* $marketplace->save();
* var_dump($marketplace);
* </code>
*
* Each api key is uniquely associated with an api key so once you've created a
* marketplace:
*
* <code>
* \Balanced\Settings::$api_key = $secret;
* $marketplace = \Balanced\Marketplace::mine(); // this is the marketplace associated with $secret
* </code>
*/
class Marketplace extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('marketplaces', 'id', '/v1');
self::$_registry->add(get_called_class());
}
/**
* Get the marketplace associated with the currently configured
* \Balanced\Settings::$api_key.
*
* @throws \RESTful\Exceptions\NoResultFound
* @return \Balanced\Marketplace
*/
public static function mine()
{
return self::query()->one();
}
/**
* Create a card. These can later be associated with an account using
* \Balanced\Account->addCard or \Balanced\Marketplace->createBuyer.
*
* @param string street_address Street address. Use null if there is no address for the card.
* @param string city City. Use null if there is no address for the card.
* @param string postal_code Postal code. Use null if there is no address for the card.
* @param string name Name as it appears on the card.
* @param string card_number Card number.
* @param string security_code Card security code. Use null if it is no available.
* @param int expiration_month Expiration month.
* @param int expiration_year Expiration year.
*
* @return \Balanced\Card
*/
public function createCard(
$street_address,
$city,
$region,
$postal_code,
$name,
$card_number,
$security_code,
$expiration_month,
$expiration_year)
{
if ($region != null && strlen($region) > 0) {
trigger_error("The region parameter will be deprecated in the next minor version of balanced-php", E_USER_NOTICE);
}
return $this->cards->create(array(
'street_address' => $street_address,
'city' => $city,
'region' => $region,
'postal_code' => $postal_code,
'name' => $name,
'card_number' => $card_number,
'security_code' => $security_code,
'expiration_month' => $expiration_month,
'expiration_year' => $expiration_year
));
}
/**
* Create a bank account. These can later be associated with an account
* using \Balanced\Account->addBankAccount.
*
* @param string name Name of the account holder.
* @param string account_number Account number.
* @param string routing_number Bank code or routing number.
* @param string type checking or savings
* @param array meta Single level mapping from string keys to string values.
*
* @return \Balanced\BankAccount
*/
public function createBankAccount(
$name,
$account_number,
$routing_number,
$type,
$meta = null
)
{
return $this->bank_accounts->create(array(
'name' => $name,
'account_number' => $account_number,
'routing_number' => $routing_number,
'type' => $type,
'meta' => $meta
));
}
/**
* Create a role-less account. You can later turn this into a buyer by
* adding a funding source (e.g a card) or a merchant using
* \Balanced\Account->promoteToMerchant.
*
* @param string email_address Optional email address. There can only be one account with this email address.
* @param array[string]string meta Optional metadata to associate with the account.
*
* @return \Balanced\Account
*/
public function createAccount($email_address = null, $meta = null)
{
return $this->accounts->create(array(
'email_address' => $email_address,
'meta' => $meta,
));
}
/**
* Find or create a role-less account by email address. You can later turn
* this into a buyer by adding a funding source (e.g a card) or a merchant
* using \Balanced\Account->promoteToMerchant.
*
* @param string email_address Email address. There can only be one account with this email address.
*
* @return \Balanced\Account
*/
function findOrCreateAccountByEmailAddress($email_address)
{
$marketplace = Marketplace::mine();
try {
$account = $this->accounts->create(array(
'email_address' => $email_address
));
}
catch (Errors\DuplicateAccountEmailAddress $e) {
$account = Account::get($e->extras->account_uri);
}
return $account;
}
/**
* Create a buyer account.
*
* @param string email_address Optional email address. There can only be one account with this email address.
* @param string card_uri URI referencing a card to associate with the account.
* @param array[string]string meta Optional metadata to associate with the account.
* @param string name Optional name of the account.
*
* @return \Balanced\Account
*/
public function createBuyer($email_address, $card_uri, $meta = null, $name = null)
{
return $this->accounts->create(array(
'email_address' => $email_address,
'card_uri' => $card_uri,
'meta' => $meta,
'name' => $name
));
}
/**
* Create a merchant account.
*
* Unlike buyers the identity of a merchant must be established before
* the account can function as a merchant (i.e. be credited). A merchant
* can be either a person or a business. Either way that information is
* represented as an associative array and passed as the merchant parameter
* when creating the merchant account.
*
* For a person the array looks like this:
*
* <code>
* array(
* 'type' => 'person',
* 'name' => 'William James',
* 'tax_id' => '393-48-3992',
* 'street_address' => '167 West 74th Street',
* 'postal_code' => '10023',
* 'dob' => '1842-01-01',
* 'phone_number' => '+16505551234',
* 'country_code' => 'USA'
* )
* </code>
*
* For a business the array looks like this:
*
* <code>
* array(
* 'type' => 'business',
* 'name' => 'Levain Bakery',
* 'tax_id' => '253912384',
* 'street_address' => '167 West 74th Street',
* 'postal_code' => '10023',
* 'phone_number' => '+16505551234',
* 'country_code' => 'USA',
* 'person' => array(
* 'name' => 'William James',
* 'tax_id' => '393483992',
* 'street_address' => '167 West 74th Street',
* 'postal_code' => '10023',
* 'dob' => '1842-01-01',
* 'phone_number' => '+16505551234',
* 'country_code' => 'USA',
* )
* )
* </code>
*
* In some cases the identity of the merchant, person or business, cannot
* be verified in which case a \Balanced\Exceptions\HTTPError is thrown:
*
* <code>
* $identity = array(
* 'type' => 'business',
* 'name' => 'Levain Bakery',
* 'tax_id' => '253912384',
* 'street_address' => '167 West 74th Street',
* 'postal_code' => '10023',
* 'phone_number' => '+16505551234',
* 'country_code' => 'USA',
* 'person' => array(
* 'name' => 'William James',
* 'tax_id' => '393483992',
* 'street_address' => '167 West 74th Street',
* 'postal_code' => '10023',
* 'dob' => '1842-01-01',
* 'phone_number' => '+16505551234',
* 'country_code' => 'USA',
* ),
* );
*
* try {
* $merchant = \Balanced\Marketplace::mine()->createMerchant(
* 'merchant@example.com',
* $identity,
* );
* catch (\Balanced\Exceptions\HTTPError $e) {
* if ($e->code != 300) {
* throw $e;
* }
* print e->response->header['Location'] // this is where merchant must signup
* }
* </code>
*
* Once the merchant has completed signup you can use the resulting URI to
* create an account for them on your marketplace:
*
* <code>
* $merchant = self::$marketplace->createMerchant(
* 'merchant@example.com',
* null,
* null,
* $merchant_uri
* );
* </coe>
*
* @param string email_address Optional email address. There can only be one account with this email address.
* @param array[string]mixed merchant Associative array describing the merchants identity.
* @param string $bank_account_uri Optional URI referencing a bank account to associate with this account.
* @param string $merchant_uri URI of a merchant created via the redirection sign-up flow.
* @param string $name Optional name of the merchant.
* @param array[string]string meta Optional metadata to associate with the account.
*
* @return \Balanced\Account
*/
public function createMerchant(
$email_address = null,
$merchant = null,
$bank_account_uri = null,
$merchant_uri = null,
$name = null,
$meta = null)
{
return $this->accounts->create(array(
'email_address' => $email_address,
'merchant' => $merchant,
'merchant_uri' => $merchant_uri,
'bank_account_uri' => $bank_account_uri,
'name' => $name,
'meta' => $meta,
));
}
/*
* Create a callback.
*
* @param string url URL of callback.
*/
public function createCallback(
$url
)
{
return $this->callbacks->create(array(
'url' => $url
));
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents a merchant identity.
*
* These are optionally created and associated with an account via
* \Balanced\Marketplace::createMerchant which establishes a merchant account
* on a marketplace.
*
* In some cases a merchant may need to be redirected to create a identity (e.g. the
* information provided cannot be verified, more information is needed, etc). That
* redirected signup results in a merchant_uri which is then associated with an
* account on the marketplace via \Balanced\Marketplace::createMerchant.
*
* @see \Balanced\Marketplace
*/
class Merchant extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('merchants', 'id', '/v1');
self::$_registry->add(get_called_class());
}
/**
* Return the merchant identity associated with the current
* Balanced\Settings::$api_key. If you are not authenticated (i.e.
* ) then Balanced\Exceptions\NoResult
* will be thrown.
*
* <code>
* $merchant = \Balanced\Merchant::me();
* $owner_account = \Balanced\Marketplace::mine()->owner_account;
* assert($merchant->id == $owner_account->merchant->id);
* </code>
*
* @throws \RESTful\Exceptions\NoResultFound
* @return \Balanced\Merchant
*/
public static function me()
{
return self::query()->one();
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Balanced;
use Balanced\Resource;
use \RESTful\URISpec;
/**
* Represents a refund of an account debit transaction.
*
* You create these via Balanced\Debit::refund.
*
* <code>
* $marketplace = \Balanced\Marketplace::mine();
*
* $account = $marketplace
* ->accounts
* ->query()
* ->filter(Account::f->email_address->eq('buyer@example.com'))
* ->one();
*
* $debit = $account->debit(
* 100,
* 'how it appears on the statement',
* 'a description',
* array(
* 'my_id': '443322'
* )
* );
*
* $debit->refund(
* 99,
* 'some description',
* array(
* 'my_id': '123123'
* )
* );
* </code>
*/
class Refund extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('refunds', 'id');
self::$_registry->add(get_called_class());
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Balanced;
use Balanced\Errors\Error;
use RESTful\Exceptions\HTTPError;
class Resource extends \RESTful\Resource
{
public static $fields, $f;
protected static $_client, $_registry, $_uri_spec;
public static function init()
{
self::$_client = new \RESTful\Client('\Balanced\Settings', null, __NAMESPACE__ .'\Resource::convertError');
self::$_registry = new \RESTful\Registry();
self::$f = self::$fields = new \RESTful\Fields();
}
public static function convertError($response)
{
if (property_exists($response->body, 'category_code') &&
array_key_exists($response->body->category_code, Error::$codes))
$error = new Error::$codes[$response->body->category_code]($response);
else
$error = new HTTPError($response);
return $error;
}
public static function getClient()
{
$class = get_called_class();
return $class::$_client;
}
public static function getRegistry()
{
$class = get_called_class();
return $class::$_registry;
}
public static function getURISpec()
{
$class = get_called_class();
return $class::$_uri_spec;
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Balanced;
/**
* Configurable settings.
*
* You can either set these settings individually:
*
* <code>
* \Balanced\Settngs::api_key = 'my-api-key-secret';
* </code>
*
* or all at once:
*
* <code>
* \Balanced\Settngs::configure(
* 'https://api.balancedpayments.com',
* 'my-api-key-secret'
* );
* </code>
*/
class Settings
{
const VERSION = '0.7.1';
public static $url_root = 'https://api.balancedpayments.com',
$api_key = null,
$agent = 'balanced-php',
$version = Settings::VERSION;
/**
* Configure all settings.
*
* @param string url_root The root (schema://hostname[:port]) to use when constructing api URLs.
* @param string api_key The api key secret to use for authenticating when talking to the api. If null then api usage is limited to uauthenticated endpoints.
*/
public static function configure($url_root, $api_key)
{
self::$url_root= $url_root;
self::$api_key = $api_key;
}
}

View file

@ -0,0 +1,614 @@
<?php
namespace Balanced\Test;
\Balanced\Bootstrap::init();
\RESTful\Bootstrap::init();
\Httpful\Bootstrap::init();
use Balanced\Resource;
use Balanced\Settings;
use Balanced\APIKey;
use Balanced\Marketplace;
use Balanced\Credit;
use Balanced\Debit;
use Balanced\Refund;
use Balanced\Account;
use Balanced\Merchant;
use Balanced\BankAccount;
use Balanced\Card;
use Balanced\Hold;
use \RESTful\Collection;
class APIKeyTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$this->expectOutputString('');
$result = Resource::getRegistry()->match('/v1/api_keys');
return;
$expected = array(
'collection' => true,
'class' => 'Balanced\APIKey',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/api_keys/1234');
$expected = array(
'collection' => false,
'class' => 'Balanced\APIKey',
'ids' => array('id' => '1234'),
);
$this->assertEquals($expected, $result);
}
}
class MarketplaceTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/marketplaces');
$expected = array(
'collection' => true,
'class' => 'Balanced\Marketplace',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/marketplaces/1122');
$expected = array(
'collection' => false,
'class' => 'Balanced\Marketplace',
'ids' => array('id' => '1122'),
);
$this->assertEquals($expected, $result);
}
function testCreateCard()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Card', 'some/uri', null)
);
$collection->expects($this->once())
->method('create')
->with(array(
'street_address' => '123 Fake Street',
'city' => 'Jollywood',
'region' => '',
'postal_code' => '90210',
'name' => 'khalkhalash',
'card_number' => '4112344112344113',
'security_code' => '123',
'expiration_month' => 12,
'expiration_year' => 2013,
));
$marketplace = new Marketplace(array('cards' => $collection));
$marketplace->createCard(
'123 Fake Street',
'Jollywood',
'',
'90210',
'khalkhalash',
'4112344112344113',
'123',
12,
2013);
}
function testCreateBankAccount()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\BankAccount', 'some/uri', null)
);
$collection->expects($this->once())
->method('create')
->with(array(
'name' => 'Homer Jay',
'account_number' => '112233a',
'routing_number' => '121042882',
'type' => 'savings',
'meta' => null
));
$marketplace = new Marketplace(array('bank_accounts' => $collection));
$marketplace->createBankAccount(
'Homer Jay',
'112233a',
'121042882',
'savings');
}
function testCreateAccount()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Account', 'some/uri', null)
);
$collection->expects($this->once())
->method('create')
->with(array(
'email_address' => 'role-less@example.com',
'meta' => array('test#' => 'test_d')
));
$marketplace = new Marketplace(array('accounts' => $collection));
$marketplace->createAccount(
'role-less@example.com',
array('test#' => 'test_d')
);
}
function testCreateBuyer()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Account', 'some/uri', null)
);
$collection->expects($this->once())
->method('create')
->with(array(
'email_address' => 'buyer@example.com',
'card_uri' => '/some/card/uri',
'meta' => array('test#' => 'test_d'),
'name' => 'Buy Er'
));
$marketplace = new Marketplace(array('accounts' => $collection));
$marketplace->createBuyer(
'buyer@example.com',
'/some/card/uri',
array('test#' => 'test_d'),
'Buy Er'
);
}
}
class AccountTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/accounts');
$expected = array(
'collection' => true,
'class' => 'Balanced\Account',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/accounts/0099');
$expected = array(
'collection' => false,
'class' => 'Balanced\Account',
'ids' => array('id' => '0099'),
);
$this->assertEquals($expected, $result);
}
function testCredit()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Credit', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 101,
'description' => 'something sweet',
'meta' => null,
'destination_uri' => null,
'appears_on_statement_as' => null
));
$account = new Account(array('credits' => $collection));
$account->credit(101, 'something sweet');
}
function testDebit()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Debit', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 9911,
'description' => 'something tangy',
'appears_on_statement_as' => 'BAL*TANG',
'meta' => null,
'source_uri' => null,
'on_behalf_of_uri' => null,
));
$account = new Account(array('debits' => $collection));
$account->debit(9911, 'BAL*TANG', 'something tangy');
}
function testHold()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Hold', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 1243,
'description' => 'something crispy',
'source_uri' => '/some/card/uri',
'meta' => array('test#' => 'test_d')
));
$account = new Account(array('holds' => $collection));
$account->hold(
1243,
'something crispy',
'/some/card/uri',
array('test#' => 'test_d')
);
}
function testAddCard()
{
$account = $this->getMock(
'\Balanced\Account',
array('save')
);
$account
->expects($this->once())
->method('save')
->with();
$account->addCard('/my/new/card/121212');
$this->assertEquals($account->card_uri, '/my/new/card/121212');
}
function testAddBankAccount()
{
$account = $this->getMock(
'\Balanced\Account',
array('save')
);
$account
->expects($this->once())
->method('save')
->with();
$account->addBankAccount('/my/new/bank_account/121212');
$this->assertEquals($account->bank_account_uri, '/my/new/bank_account/121212');
}
function testPromotToMerchant()
{
$account = $this->getMock(
'\Balanced\Account',
array('save')
);
$account
->expects($this->once())
->method('save')
->with();
$merchant = array(
'type' => 'person',
'name' => 'William James',
'tax_id' => '393-48-3992',
'street_address' => '167 West 74th Street',
'postal_code' => '10023',
'dob' => '1842-01-01',
'phone_number' => '+16505551234',
'country_code' => 'USA'
);
$account->promoteToMerchant($merchant);
$this->assertEquals($account->merchant, $merchant);
}
}
class HoldTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/holds');
$expected = array(
'collection' => true,
'class' => 'Balanced\Hold',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/holds/112233');
$expected = array(
'collection' => false,
'class' => 'Balanced\Hold',
'ids' => array('id' => '112233'),
);
$this->assertEquals($expected, $result);
}
function testVoid()
{
$hold = $this->getMock(
'\Balanced\Hold',
array('save')
);
$hold
->expects($this->once())
->method('save')
->with();
$hold->void();
$this->assertTrue($hold->is_void);
}
function testCapture()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Debit', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'hold_uri' => 'some/hold/uri',
'amount' => 2211,
));
$account = new Account(array('debits' => $collection));
$hold = new Hold(array('uri' => 'some/hold/uri', 'account' => $account));
$hold->capture(2211);
}
}
class CreditTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/credits');
$expected = array(
'collection' => true,
'class' => 'Balanced\Credit',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/credits/9988');
$expected = array(
'collection' => false,
'class' => 'Balanced\Credit',
'ids' => array('id' => '9988'),
);
$this->assertEquals($expected, $result);
}
}
class DebitTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/debits');
$expected = array(
'collection' => true,
'class' => 'Balanced\Debit',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/debits/4545');
$expected = array(
'collection' => false,
'class' => 'Balanced\Debit',
'ids' => array('id' => '4545'),
);
$this->assertEquals($expected, $result);
}
function testRefund()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Refund', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 5645,
'description' => null,
'meta' => array('test#' => 'test_d')
));
$debit = new Debit(array('refunds' => $collection));
$debit->refund(5645, null, array('test#' => 'test_d'));
}
}
class RefundTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/refunds');
$expected = array(
'collection' => true,
'class' => 'Balanced\Refund',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/refunds/1287');
$expected = array(
'collection' => false,
'class' => 'Balanced\Refund',
'ids' => array('id' => '1287'),
);
$this->assertEquals($expected, $result);
}
}
class BankAccountTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/bank_accounts');
$expected = array(
'collection' => true,
'class' => 'Balanced\BankAccount',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/bank_accounts/887766');
$expected = array(
'collection' => false,
'class' => 'Balanced\BankAccount',
'ids' => array('id' => '887766'),
);
$this->assertEquals($expected, $result);
}
function testCreditAccount()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Credit', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 101,
'description' => 'something super sweet',
'meta' => null,
'destination_uri' => '/some/other/uri',
'appears_on_statement_as' => null
));
$account = new Account(array('credits' => $collection));
$bank_account = new BankAccount(array('uri' => '/some/other/uri', 'account' => $account));
$bank_account->credit(101, 'something super sweet');
}
function testCreditAccountless()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Credit', 'some/uri', null)
);
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 101,
'description' => 'something super sweet',
));
$bank_account = new BankAccount(array(
'uri' => '/some/other/uri',
'account' => null,
'credits' => $collection,
));
$bank_account->credit(101, 'something super sweet');
}
}
class CardTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/cards');
$expected = array(
'collection' => true,
'class' => 'Balanced\Card',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/cards/136asd6713');
$expected = array(
'collection' => false,
'class' => 'Balanced\Card',
'ids' => array('id' => '136asd6713'),
);
$this->assertEquals($expected, $result);
}
function testDebit()
{
$collection = $this->getMock(
'\RESTful\Collection',
array('create'),
array('\Balanced\Debit', 'some/uri', null)
);
$account = new Account(array('debits' => $collection));
$card = new Card(array('uri' => '/some/uri', 'account' => $account ));
$collection
->expects($this->once())
->method('create')
->with(array(
'amount' => 9911,
'description' => 'something tangy',
'appears_on_statement_as' => 'BAL*TANG',
'meta' => null,
'source_uri' => '/some/uri',
'on_behalf_of_uri' => null,
));
$card->debit(9911, 'BAL*TANG', 'something tangy');
}
/**
* @expectedException \UnexpectedValueException
*/
function testNotAssociatedDebit()
{
$card = new Card(array('uri' => '/some/uri', 'account' => null ));
$card->debit(9911, 'BAL*TANG', 'something tangy');
}
}
class MerchantTest extends \PHPUnit_Framework_TestCase
{
function testRegistry()
{
$result = Resource::getRegistry()->match('/v1/merchants');
$expected = array(
'collection' => true,
'class' => 'Balanced\Merchant',
);
$this->assertEquals($expected, $result);
$result = Resource::getRegistry()->match('/v1/merchants/136asd6713');
$expected = array(
'collection' => false,
'class' => 'Balanced\Merchant',
'ids' => array('id' => '136asd6713'),
);
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,800 @@
<?php
namespace Balanced\Test;
\Balanced\Bootstrap::init();
\RESTful\Bootstrap::init();
\Httpful\Bootstrap::init();
use Balanced\Settings;
use Balanced\APIKey;
use Balanced\Marketplace;
use Balanced\Credit;
use Balanced\Debit;
use Balanced\Refund;
use Balanced\Account;
use Balanced\Merchant;
use Balanced\BankAccount;
use Balanced\Card;
/**
* Suite test cases. These talk to an API server and so make network calls.
*
* Environment variables can be used to control client settings:
*
* <ul>
* <li>$BALANCED_URL_ROOT If set applies to \Balanced\Settings::$url_root.
* <li>$BALANCED_API_KEY If set applies to \Balanced\Settings::$api_key.
* </ul>
*
* @group suite
*/
class SuiteTest extends \PHPUnit_Framework_TestCase
{
static $key,
$marketplace,
$email_counter = 0;
static function _createBuyer($email_address = null, $card = null)
{
if ($email_address == null)
$email_address = sprintf('m+%d@poundpay.com', self::$email_counter++);
if ($card == null)
$card = self::_createCard();
return self::$marketplace->createBuyer(
$email_address,
$card->uri,
array('test#' => 'test_d'),
'Hobo Joe'
);
}
static function _createCard($account = null)
{
$card = self::$marketplace->createCard(
'123 Fake Street',
'Jollywood',
null,
'90210',
'khalkhalash',
'4112344112344113',
null,
12,
2013);
if ($account != null) {
$account->addCard($card);
$card = Card::get($card->uri);
}
return $card;
}
static function _createBankAccount($account = null)
{
$bank_account = self::$marketplace->createBankAccount(
'Homer Jay',
'112233a',
'121042882',
'checking'
);
if ($account != null) {
$account->addBankAccount($bank_account);
$bank_account = $account->bank_accounts[0];
}
return $bank_account;
}
public static function _createPersonMerchant($email_address = null, $bank_account = null)
{
if ($email_address == null)
$email_address = sprintf('m+%d@poundpay.com', self::$email_counter++);
if ($bank_account == null)
$bank_account = self::_createBankAccount();
$merchant = array(
'type' => 'person',
'name' => 'William James',
'tax_id' => '393-48-3992',
'street_address' => '167 West 74th Street',
'postal_code' => '10023',
'dob' => '1842-01-01',
'phone_number' => '+16505551234',
'country_code' => 'USA'
);
return self::$marketplace->createMerchant(
$email_address,
$merchant,
$bank_account->uri
);
}
public static function _createBusinessMerchant($email_address = null, $bank_account = null)
{
if ($email_address == null)
$email_address = sprintf('m+%d@poundpay.com', self::$email_counter++);
if ($bank_account == null)
$bank_account = self::_createBankAccount();
$merchant = array(
'type' => 'business',
'name' => 'Levain Bakery',
'tax_id' => '253912384',
'street_address' => '167 West 74th Street',
'postal_code' => '10023',
'phone_number' => '+16505551234',
'country_code' => 'USA',
'person' => array(
'name' => 'William James',
'tax_id' => '393483992',
'street_address' => '167 West 74th Street',
'postal_code' => '10023',
'dob' => '1842-01-01',
'phone_number' => '+16505551234',
'country_code' => 'USA',
),
);
return self::$marketplace->createMerchant(
$email_address,
$merchant,
$bank_account->uri
);
}
public static function setUpBeforeClass()
{
// url root
$url_root = getenv('BALANCED_URL_ROOT');
if ($url_root != '') {
Settings::$url_root = $url_root;
}
else
Settings::$url_root = 'https://api.balancedpayments.com';
// api key
$api_key = getenv('BALANCED_API_KEY');
if ($api_key != '') {
Settings::$api_key = $api_key;
}
else {
self::$key = new APIKey();
self::$key->save();
Settings::$api_key = self::$key->secret;
}
// marketplace
try {
self::$marketplace = Marketplace::mine();
}
catch(\RESTful\Exceptions\NoResultFound $e) {
self::$marketplace = new Marketplace();
self::$marketplace->save();
}
}
function testMarketplaceMine()
{
$marketplace = Marketplace::mine();
$this->assertEquals($this::$marketplace->id, $marketplace->id);
}
/**
* @expectedException \RESTful\Exceptions\HTTPError
*/
function testAnotherMarketplace()
{
$marketplace = new Marketplace();
$marketplace->save();
}
/**
* @expectedException \RESTful\Exceptions\HTTPError
*/
function testDuplicateEmailAddress()
{
self::_createBuyer('dupe@poundpay.com');
self::_createBuyer('dupe@poundpay.com');
}
function testIndexMarketplace()
{
$marketplaces = Marketplace::query()->all();
$this->assertEquals(count($marketplaces), 1);
}
function testCreateBuyer()
{
self::_createBuyer();
}
function testCreateAccountWithoutEmailAddress()
{
self::$marketplace->createAccount();
}
function testFindOrCreateAccountByEmailAddress()
{
$account1 = self::$marketplace->createAccount('foc@example.com');
$account2 = self::$marketplace->findOrCreateAccountByEmailAddress('foc@example.com');
$this->assertEquals($account2->id, $account2->id);
$account3 = self::$marketplace->findOrCreateAccountByEmailAddress('foc2@example.com');
$this->assertNotEquals($account3->id, $account1->id);
}
function testGetBuyer()
{
$buyer1 = self::_createBuyer();
$buyer2 = Account::get($buyer1->uri);
$this->assertEquals($buyer1->id, $buyer2->id);
}
function testMe()
{
$marketplace = Marketplace::mine();
$merchant = Merchant::me();
$this->assertEquals($marketplace->id, $merchant->marketplace->id);
}
function testDebitAndRefundBuyer()
{
$buyer = self::_createBuyer();
$debit = $buyer->debit(
1000,
'Softie',
'something i bought',
array('hi' => 'bye')
);
$refund = $debit->refund(100);
}
/**
* @expectedException \RESTful\Exceptions\HTTPError
*/
function testDebitZero()
{
$buyer = self::_createBuyer();
$debit = $buyer->debit(
0,
'Softie',
'something i bought'
);
}
function testMultipleRefunds()
{
$buyer = self::_createBuyer();
$debit = $buyer->debit(
1500,
'Softie',
'something tart',
array('hi' => 'bye'));
$refunds = array(
$debit->refund(100),
$debit->refund(100),
$debit->refund(100),
$debit->refund(100));
$expected_refund_ids = array_map(
function($x) {
return $x->id;
}, $refunds);
sort($expected_refund_ids);
$this->assertEquals($debit->refunds->total(), 4);
// itemization
$total = 0;
$refund_ids = array();
foreach ($debit->refunds as $refund) {
$total += $refund->amount;
array_push($refund_ids, $refund->id);
}
sort($refund_ids);
$this->assertEquals($total, 400);
$this->assertEquals($expected_refund_ids, $refund_ids);
// pagination
$total = 0;
$refund_ids = array();
foreach ($debit->refunds->paginate() as $page) {
foreach ($page->items as $refund) {
$total += $refund->amount;
array_push($refund_ids, $refund->id);
}
}
sort($refund_ids);
$this->assertEquals($total, 400);
$this->assertEquals($expected_refund_ids, $refund_ids);
}
function testDebitSource()
{
$buyer = self::_createBuyer();
$card1 = self::_createCard($buyer);
$card2 = self::_createCard($buyer);
$credit = $buyer->debit(
1000,
'Softie',
'something i bought'
);
$this->assertEquals($credit->source->id, $card2->id);
$credit = $buyer->debit(
1000,
'Softie',
'something i bought',
null,
$card1
);
$this->assertEquals($credit->source->id, $card1->id);
}
function testDebitOnBehalfOf()
{
$buyer = self::_createBuyer();
$merchant = self::$marketplace->createAccount(null);
$card1 = self::_createCard($buyer);
$debit = $buyer->debit(1000, null, null, null, null, $merchant);
$this->assertEquals($debit->amount, 1000);
// for now just test the debit succeeds.
// TODO: once the on_behalf_of actually shows up on the response, test it.
}
/**
* @expectedException \InvalidArgumentException
*/
function testDebitOnBehalfOfFailsForBuyer()
{
$buyer = self::_createBuyer();
$card1 = self::_createCard($buyer);
$debit = $buyer->debit(1000, null, null, null, null, $buyer);
}
function testCreateAndVoidHold()
{
$buyer = self::_createBuyer();
$hold = $buyer->hold(1000);
$this->assertEquals($hold->is_void, false);
$hold->void();
$this->assertEquals($hold->is_void, true);
}
function testCreateAndCaptureHold()
{
$buyer = self::_createBuyer();
$hold = $buyer->hold(1000);
$debit = $hold->capture(909);
$this->assertEquals($debit->account->id, $buyer->id);
$this->assertEquals($debit->hold->id, $hold->id);
$this->assertEquals($hold->debit->id, $debit->id);
}
function testCreatePersonMerchant()
{
$merchant = self::_createPersonMerchant();
}
function testCreateBusinessMerchant()
{
$merchant = self::_createBusinessMerchant();
}
/**
* @expectedException \RESTful\Exceptions\HTTPError
*/
function testCreditRequiresNonZeroAmount()
{
$buyer = self::_createBuyer();
$buyer->debit(
1000,
'Softie',
'something i bought'
);
$merchant = self::_createBusinessMerchant();
$merchant->credit(0);
}
/**
* @expectedException \RESTful\Exceptions\HTTPError
*/
function testCreditMoreThanEscrowBalanceFails()
{
$buyer = self::_createBuyer();
$buyer->credit(
1000,
'something i bought',
null,
null,
'Softie'
);
$merchant = self::_createBusinessMerchant();
$merchant->credit(self::$marketplace->in_escrow + 1);
}
function testCreditDestiation()
{
$buyer = self::_createBuyer();
$buyer->debit(3000); # NOTE: build up escrow balance to credit
$merchant = self::_createPersonMerchant();
$bank_account1 = self::_createBankAccount($merchant);
$bank_account2 = self::_createBankAccount($merchant);
$credit = $merchant->credit(
1000,
'something i sold',
null,
null,
'Softie'
);
$this->assertEquals($credit->destination->id, $bank_account2->id);
$credit = $merchant->credit(
1000,
'something i sold',
null,
$bank_account1,
'Softie'
);
$this->assertEquals($credit->destination->id, $bank_account1->id);
}
function testAssociateCard()
{
$merchant = self::_createPersonMerchant();
$card = self::_createCard();
$merchant->addCard($card->uri);
}
function testAssociateBankAccount()
{
$merchant = self::_createPersonMerchant();
$bank_account = self::_createBankAccount();
$merchant->addBankAccount($bank_account->uri);
}
function testCardMasking()
{
$card = self::$marketplace->createCard(
'123 Fake Street',
'Jollywood',
null,
'90210',
'khalkhalash',
'4112344112344113',
'123',
12,
2013);
$this->assertEquals($card->last_four, '4113');
$this->assertFalse(property_exists($card, 'number'));
}
function testBankAccountMasking()
{
$bank_account = self::$marketplace->createBankAccount(
'Homer Jay',
'112233a',
'121042882',
'checking'
);
$this->assertEquals($bank_account->last_four, '233a');
$this->assertEquals($bank_account->account_number, 'xxx233a');
}
function testFilteringAndSorting()
{
$buyer = self::_createBuyer();
$debit1 = $buyer->debit(1122, null, null, array('tag' => '1'));
$debit2 = $buyer->debit(3322, null, null, array('tag' => '1'));
$debit3 = $buyer->debit(2211, null, null, array('tag' => '2'));
$getId = function($o) {
return $o->id;
};
$debits = (
self::$marketplace->debits->query()
->filter(Debit::$f->meta->tag->eq('1'))
->sort(Debit::$f->created_at->asc())
->all());
$debit_ids = array_map($getId, $debits);
$this->assertEquals($debit_ids, array($debit1->id, $debit2->id));
$debits = (
self::$marketplace->debits->query()
->filter(Debit::$f->meta->tag->eq('2'))
->all());
$debit_ids = array_map($getId, $debits);
$this->assertEquals($debit_ids, array($debit3->id));
$debits = (
self::$marketplace->debits->query()
->filter(Debit::$f->meta->contains('tag'))
->sort(Debit::$f->created_at->asc())
->all());
$debit_ids = array_map($getId, $debits);
$this->assertEquals($debit_ids, array($debit1->id, $debit2->id, $debit3->id));
$debits = (
self::$marketplace->debits->query()
->filter(Debit::$f->meta->contains('tag'))
->sort(Debit::$f->amount->desc())
->all());
$debit_ids = array_map($getId, $debits);
$this->assertEquals($debit_ids, array($debit2->id, $debit3->id, $debit1->id));
}
function testMerchantIdentityFailure()
{
// NOTE: postal_code == '99999' && region == 'EX' triggers identity failure
$identity = array(
'type' => 'business',
'name' => 'Levain Bakery',
'tax_id' => '253912384',
'street_address' => '167 West 74th Street',
'postal_code' => '99999',
'region' => 'EX',
'phone_number' => '+16505551234',
'country_code' => 'USA',
'person' => array(
'name' => 'William James',
'tax_id' => '393483992',
'street_address' => '167 West 74th Street',
'postal_code' => '99999',
'region' => 'EX',
'dob' => '1842-01-01',
'phone_number' => '+16505551234',
'country_code' => 'USA',
),
);
try {
self::$marketplace->createMerchant(
sprintf('m+%d@poundpay.com', self::$email_counter++),
$identity);
}
catch(\RESTful\Exceptions\HTTPError $e) {
$this->assertEquals($e->response->code, 300);
$expected = sprintf('https://www.balancedpayments.com/marketplaces/%s/kyc', self::$marketplace->id);
$this->assertEquals($e->redirect_uri, $expected);
$this->assertEquals($e->response->headers['Location'], $expected);
return;
}
$this->fail('Expected exception HTTPError not raised.');
}
function testInternationalCard()
{
$payload = array(
'card_number' => '4111111111111111',
'city' => '\xe9\x83\xbd\xe7\x95\x99\xe5\xb8\x82',
'country_code' => 'JPN',
'expiration_month' => 12,
'expiration_year' => 2014,
'name' => 'Johnny Fresh',
'postal_code' => '4020054',
'street_address' => '\xe7\x94\xb0\xe5\x8e\x9f\xef\xbc\x93\xe3\x83\xbc\xef\xbc\x98\xe3\x83\xbc\xef\xbc\x91'
);
$card = self::$marketplace->cards->create($payload);
$this->assertEquals($card->street_address, $payload['street_address']);
}
/**
* @expectedException \RESTful\Exceptions\NoResultFound
*/
function testAccountWithEmailAddressNotFound()
{
self::$marketplace->accounts->query()
->filter(Account::$f->email_address->eq('unlikely@address.com'))
->one();
}
function testDebitACard()
{
$buyer = self::_createBuyer();
$card = self::_createCard($buyer);
$debit = $card->debit(
1000,
'Softie',
'something i bought',
array('hi' => 'bye'));
$this->assertEquals($debit->source->uri, $card->uri);
}
/**
* @expectedException \UnexpectedValueException
*/
function testDebitAnUnassociatedCard()
{
$card = self::_createCard();
$card->debit(1000, 'Softie');
}
function testCreditABankAccount()
{
$buyer = self::_createBuyer();
$buyer->debit(101); # NOTE: build up escrow balance to credit
$merchant = self::_createPersonMerchant();
$bank_account = self::_createBankAccount($merchant);
$credit = $bank_account->credit(55, 'something sour');
$this->assertEquals($credit->destination->uri, $bank_account->uri);
}
function testQuery()
{
$buyer = self::_createBuyer();
$tag = '123123123123';
$debit1 = $buyer->debit(1122, null, null, array('tag' => $tag));
$debit2 = $buyer->debit(3322, null, null, array('tag' => $tag));
$debit3 = $buyer->debit(2211, null, null, array('tag' => $tag));
$expected_debit_ids = array($debit1->id, $debit2->id, $debit3->id);
$query = (
self::$marketplace->debits->query()
->filter(Debit::$f->meta->tag->eq($tag))
->sort(Debit::$f->created_at->asc())
->limit(1));
$this->assertEquals($query->total(), 3);
$debit_ids = array();
foreach ($query as $debits) {
array_push($debit_ids, $debits->id);
}
$this->assertEquals($debit_ids, $expected_debit_ids);
$debit_ids = array($query[0]->id, $query[1]->id, $query[2]->id);
$this->assertEquals($debit_ids, $expected_debit_ids);
}
function testBuyerPromoteToMerchant()
{
$merchant = array(
'type' => 'person',
'name' => 'William James',
'tax_id' => '393-48-3992',
'street_address' => '167 West 74th Street',
'postal_code' => '10023',
'dob' => '1842-01-01',
'phone_number' => '+16505551234',
'country_code' => 'USA'
);
$buyer = self::_createBuyer();
$buyer->promoteToMerchant($merchant);
}
function testCreditAccountlessBankAccount()
{
$buyer = self::_createBuyer();
$buyer->debit(101); # NOTE: build up escrow balance to credit
$bank_account = self::_createBankAccount();
$credit = $bank_account->credit(55, 'something sour');
$this->assertEquals($credit->bank_account->id, $bank_account->id);
$bank_account = $bank_account->get($bank_account->id);
$this->assertEquals($bank_account->credits->total(), 1);
}
function testCreditUnstoredBankAccount()
{
$buyer = self::_createBuyer();
$buyer->debit(101); # NOTE: build up escrow balance to credit
$credit = Credit::bankAccount(
55,
array(
'name' => 'Homer Jay',
'account_number' => '112233a',
'routing_number' => '121042882',
'type' => 'checking',
),
'something sour');
$this->assertFalse(property_exists($credit->bank_account, 'uri'));
$this->assertFalse(property_exists($credit->bank_account, 'id'));
$this->assertEquals($credit->bank_account->name, 'Homer Jay');
$this->assertEquals($credit->bank_account->account_number, 'xxx233a');
$this->assertEquals($credit->bank_account->type, 'checking');
}
function testDeleteBankAccount()
{
$buyer = self::_createBuyer();
$buyer->debit(101); # NOTE: build up escrow balance to credit
$bank_account = self::_createBankAccount();
$credit = $bank_account->credit(55, 'something sour');
$this->assertTrue(property_exists($credit->bank_account, 'uri'));
$this->assertTrue(property_exists($credit->bank_account, 'id'));
$bank_account = BankAccount::get($bank_account->id);
$bank_account->delete();
$credit = Credit::get($credit->uri);
$this->assertFalse(property_exists($credit->bank_account, 'uri'));
$this->assertFalse(property_exists($credit->bank_account, 'id'));
}
function testGetBankAccounById()
{
$bank_account = self::_createBankAccount();
$bank_account_2 = BankAccount::get($bank_account->id);
$this->assertEquals($bank_account_2->id, $bank_account->id);
}
/**
* @expectedException \Balanced\Errors\InsufficientFunds
*/
function testInsufficientFunds()
{
$marketplace = Marketplace::get(self::$marketplace->uri);
$amount = $marketplace->in_escrow + 100;
$credit = Credit::bankAccount(
$amount,
array(
'name' => 'Homer Jay',
'account_number' => '112233a',
'routing_number' => '121042882',
'type' => 'checking',
),
'something sour');
}
function testCreateCallback() {
$callback = self::$marketplace->createCallback(
'http://example.com/php'
);
$this->assertEquals($callback->url, 'http://example.com/php');
}
/**
* @expectedException \Balanced\Errors\BankAccountVerificationFailure
*/
function testBankAccountVerificationFailure() {
$bank_account = self::_createBankAccount();
$buyer = self::_createBuyer();
$buyer->addBankAccount($bank_account);
$verification = $bank_account->verify();
$verification->confirm(1, 2);
}
/**
* @expectedException \Balanced\Errors\BankAccountVerificationFailure
*/
function testBankAccountVerificationDuplicate() {
$bank_account = self::_createBankAccount();
$buyer = self::_createBuyer();
$buyer->addBankAccount($bank_account);
$bank_account->verify();
$bank_account->verify();
}
function testBankAccountVerificationSuccess() {
$bank_account = self::_createBankAccount();
$buyer = self::_createBuyer();
$buyer->addBankAccount($bank_account);
$verification = $bank_account->verify();
$verification->confirm(1, 1);
// this will fail if the bank account is not verified
$debit = $buyer->debit(
1000,
'Softie',
'something i bought',
array('hi' => 'bye'),
$bank_account
);
$this->assertTrue(strpos($debit->source->uri, 'bank_account') > 0);
}
function testEvents() {
$prev_num_events = Marketplace::mine()->events->total();
$account = self::_createBuyer();
$account->debit(123);
$cur_num_events = Marketplace::mine()->events->total();
$count = 0;
while ($cur_num_events == $prev_num_events && $count < 10) {
printf("waiting for events - %d, %d == %d\n", $count + 1, $cur_num_events, $prev_num_events);
sleep(2); // 2 seconds
$cur_num_events = Marketplace::mine()->events->total();
$count += 1;
}
$this->assertTrue($cur_num_events > $prev_num_events);
}
}

View file

@ -0,0 +1,8 @@
<phpunit>
<testsuite name="Balanced">
<directory>.</directory>
</testsuite>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
</logging>
</phpunit>

4
externals/httpful/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
.DS_Store
composer.lock
vendor
downloads

5
externals/httpful/.travis.yml vendored Normal file
View file

@ -0,0 +1,5 @@
language: php
before_script: cd tests
php:
- 5.3
- 5.4

7
externals/httpful/LICENSE.txt vendored Normal file
View file

@ -0,0 +1,7 @@
Copyright (c) 2012 Nate Good <me@nategood.com>
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 the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

137
externals/httpful/README.md vendored Normal file
View file

@ -0,0 +1,137 @@
# Httpful
[![Build Status](https://secure.travis-ci.org/nategood/httpful.png?branch=master)](http://travis-ci.org/nategood/httpful)
[Httpful](http://phphttpclient.com) is a simple Http Client library for PHP 5.3+. There is an emphasis of readability, simplicity, and flexibility basically provide the features and flexibility to get the job done and make those features really easy to use.
Features
- Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS)
- Custom Headers
- Automatic "Smart" Parsing
- Automatic Payload Serialization
- Basic Auth
- Client Side Certificate Auth
- Request "Templates"
# Sneak Peak
Here's something to whet your appetite. Search the twitter API for tweets containing "#PHP". Include a trivial header for the heck of it. Notice that the library automatically interprets the response as JSON (can override this if desired) and parses it as an array of objects.
$url = "http://search.twitter.com/search.json?q=" . urlencode('#PHP');
$response = Request::get($url)
->withXTrivialHeader('Just as a demo')
->send();
foreach ($response->body->results as $tweet) {
echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n";
}
# Installation
## Phar
A [PHP Archive](http://php.net/manual/en/book.phar.php) (or .phar) file is available for [downloading](https://github.com/nategood/httpful/downloads). Simply [download](https://github.com/nategood/httpful/downloads) the .phar, drop it into your project, and include it like you would any other php file. _This method is ideal smaller projects, one off scripts, and quick API hacking_.
<?php
include('httpful.phar');
$r = \Httpful\Request::get($uri)->sendIt();
...
## Composer
Httpful is PSR-0 compliant and can be installed using [composer](http://getcomposer.org/). Simply add `nategood/httpful` to your composer.json file. _Composer is the sane alternative to PEAR. It is excellent for managing dependancies in larger projects_.
{
"require": {
"nategood/httpful": "*"
}
}
## Install from Source
Because Httpful is PSR-0 compliant, you can also just clone the Httpful repository and use a PSR-0 compatible autoloader to load the library, like [Symfony's](http://symfony.com/doc/current/components/class_loader.html). Alternatively you can use the PSR-0 compliant autoloader included with the Httpful (simply `require("bootstrap.php")`).
# Show Me More!
You can checkout the [Httpful Landing Page](http://phphttpclient.com) for more info including many examples and [documentation](http:://phphttpclient.com/docs).
# Contributing
Httpful highly encourages sending in pull requests. When submitting a pull request please:
- All pull requests should target the `dev` branch (not `master`)
- Make sure your code follows the [coding conventions](http://pear.php.net/manual/en/standards.php)
- Please use soft tabs (four spaces) instead of hard tabs
- Make sure you add appropriate test coverage for your changes
- Run all unit tests in the test directory via `phpunit ./tests`
- Include commenting where appropriate and add a descriptive pull request message
# Changelog
## 0.2.3
- FIX Overriding default Mime Handlers
- FIX [PR #73](https://github.com/nategood/httpful/pull/73) Parsing http status codes
## 0.2.2
- FEATURE Add support for parsing JSON responses as associative arrays instead of objects
- FEATURE Better support for setting constructor arguments on Mime Handlers
## 0.2.1
- FEATURE [PR #72](https://github.com/nategood/httpful/pull/72) Allow support for custom Accept header
## 0.2.0
- REFACTOR [PR #49](https://github.com/nategood/httpful/pull/49) Broke headers out into their own class
- REFACTOR [PR #54](https://github.com/nategood/httpful/pull/54) Added more specific Exceptions
- FIX [PR #58](https://github.com/nategood/httpful/pull/58) Fixes throwing an error on an empty xml response
- FEATURE [PR #57](https://github.com/nategood/httpful/pull/57) Adds support for digest authentication
## 0.1.6
- Ability to set the number of max redirects via overloading `followRedirects(int max_redirects)`
- Standards Compliant fix to `Accepts` header
- Bug fix for bootstrap process when installed via Composer
## 0.1.5
- Use `DIRECTORY_SEPARATOR` constant [PR #33](https://github.com/nategood/httpful/pull/32)
- [PR #35](https://github.com/nategood/httpful/pull/35)
- Added the raw\_headers property reference to response.
- Compose request header and added raw\_header to Request object.
- Fixed response has errors and added more comments for clarity.
- Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616.
- Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details.
- Added default User-Agent header
- `User-Agent: Httpful/0.1.5` + curl version + server software + PHP version
- To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks.
- Completed test units for additions.
- Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier.
## 0.1.4
- Add support for CSV Handling [PR #32](https://github.com/nategood/httpful/pull/32)
## 0.1.3
- Handle empty responses in JsonParser and XmlParser
## 0.1.2
- Added support for setting XMLHandler configuration options
- Added examples for overriding XmlHandler and registering a custom parser
- Removed the httpful.php download (deprecated in favor of httpful.phar)
## 0.1.1
- Bug fix serialization default case and phpunit tests
## 0.1.0
- Added Support for Registering Mime Handlers
- Created AbstractMimeHandler type that all Mime Handlers must extend
- Pulled out the parsing/serializing logic from the Request/Response classes into their own MimeHandler classes
- Added ability to register new mime handlers for mime types

4
externals/httpful/bootstrap.php vendored Normal file
View file

@ -0,0 +1,4 @@
<?php
require(__DIR__ . '/src/Httpful/Bootstrap.php');
\Httpful\Bootstrap::init();

51
externals/httpful/build vendored Executable file
View file

@ -0,0 +1,51 @@
#!/usr/bin/php
<?php
/**
* Build the whole library into a single file
* as an easy drop in solution as opposed to
* relying on autoloader. Sometimes we just
* want to hack with an API as a one off thing.
* Httpful should make this easy.
*/
function exit_unless($condition, $msg = null) {
if ($condition)
return;
echo "[FAIL]\n$msg\n";
exit(1);
}
// Create the Httpful Phar
echo "Building Phar... ";
$base_dir = dirname(__FILE__);
$source_dir = $base_dir . '/src/Httpful/';
$phar_path = $base_dir . '/downloads/httpful.phar';
$phar = new Phar($phar_path, 0, 'httpful.phar');
$stub = <<<HEREDOC
<?php
// Phar Stub File
Phar::mapPhar('httpful.phar');
include('phar://httpful.phar/Httpful/Bootstrap.php');
\Httpful\Bootstrap::pharInit();
__HALT_COMPILER();
HEREDOC;
try {
$phar->setStub($stub);
} catch(Exception $e) {
$phar = false;
}
exit_unless($phar, "Unable to create a phar. Make certain you have phar.readonly=0 set in your ini file.");
$phar->buildFromDirectory(dirname($source_dir));
echo "[ OK ]\n";
// Add it to git!
echo "Adding httpful.phar to the repo... ";
$return_code = 0;
passthru("git add $phar_path", $return_code);
exit_unless($return_code === 0, "Unable to add download files to git.");
echo "[ OK ]\n";
echo "\nBuild completed sucessfully.\n\n";

24
externals/httpful/composer.json vendored Normal file
View file

@ -0,0 +1,24 @@
{
"name": "nategood/httpful",
"description": "A Readable, Chainable, REST friendly, PHP HTTP Client",
"homepage": "http://github.com/nategood/httpful",
"license": "MIT",
"keywords": ["http", "curl", "rest", "restful", "api", "requests"],
"version": "0.2.3",
"authors": [
{
"name": "Nate Good",
"email": "me@nategood.com",
"homepage": "http://nategood.com"
}
],
"require": {
"php": ">=5.3",
"ext-curl": "*"
},
"autoload": {
"psr-0": {
"Httpful": "src/"
}
}
}

12
externals/httpful/examples/freebase.php vendored Normal file
View file

@ -0,0 +1,12 @@
<?php
/**
* Grab some The Dead Weather albums from Freebase
*/
require(__DIR__ . '/../bootstrap.php');
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)
->expectsJson()
->sendIt();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";

9
externals/httpful/examples/github.php vendored Normal file
View file

@ -0,0 +1,9 @@
<?php
// XML Example from GitHub
require(__DIR__ . '/../bootstrap.php');
use \Httpful\Request;
$uri = 'https://github.com/api/v2/xml/user/show/nategood';
$request = Request::get($uri)->send();
echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n";

44
externals/httpful/examples/override.php vendored Normal file
View file

@ -0,0 +1,44 @@
<?php
require(__DIR__ . '/../bootstrap.php');
// We can override the default parser configuration options be registering
// a parser with different configuration options for a particular mime type
// Example setting a namespace for the XMLHandler parser
$conf = array('namespace' => 'http://example.com');
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
// We can also add the parsers with our own...
class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
{
/**
* Takes a response body, and turns it into
* a two dimensional array.
*
* @param string $body
* @return mixed
*/
public function parse($body)
{
return str_getcsv($body);
}
/**
* Takes a two dimensional array and turns it
* into a serialized string to include as the
* body of a request
*
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
$serialized = '';
foreach ($payload as $line) {
$serialized .= '"' . implode('","', $line) . '"' . "\n";
}
return $serialized;
}
}
\Httpful\Httpful::register('text/csv', new SimpleCsvHandler());

24
externals/httpful/examples/showclix.php vendored Normal file
View file

@ -0,0 +1,24 @@
<?php
require(__DIR__ . '/../bootstrap.php');
use \Httpful\Request;
// Get event details for a public event
$uri = "http://api.showclix.com/Event/8175";
$response = Request::get($uri)
->expectsType('json')
->sendIt();
// Print out the event details
echo "The event {$response->body->event} will take place on {$response->body->event_start}\n";
// Example overriding the default JSON handler with one that encodes the response as an array
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));
$response = Request::get($uri)
->expectsType('json')
->sendIt();
// Print out the event details
echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n";

13
externals/httpful/examples/twitter.php vendored Normal file
View file

@ -0,0 +1,13 @@
<?php
require(__DIR__ . '/../bootstrap.php');
$query = urlencode('#PHP');
$response = \Httpful\Request::get("http://search.twitter.com/search.json?q=$query")->send();
if (!$response->hasErrors()) {
foreach ($response->body->results as $tweet) {
echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n";
}
} else {
echo "Uh oh. Twitter gave us the old {$response->code} status.\n";
}

View file

@ -0,0 +1,97 @@
<?php
namespace Httpful;
/**
* Bootstrap class that facilitates autoloading. A naive
* PSR-0 autoloader.
*
* @author Nate Good <me@nategood.com>
*/
class Bootstrap
{
const DIR_GLUE = DIRECTORY_SEPARATOR;
const NS_GLUE = '\\';
public static $registered = false;
/**
* Register the autoloader and any other setup needed
*/
public static function init()
{
spl_autoload_register(array('\Httpful\Bootstrap', 'autoload'));
self::registerHandlers();
}
/**
* The autoload magic (PSR-0 style)
*
* @param string $classname
*/
public static function autoload($classname)
{
self::_autoload(dirname(dirname(__FILE__)), $classname);
}
/**
* Register the autoloader and any other setup needed
*/
public static function pharInit()
{
spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload'));
self::registerHandlers();
}
/**
* Phar specific autoloader
*
* @param string $classname
*/
public static function pharAutoload($classname)
{
self::_autoload('phar://httpful.phar', $classname);
}
/**
* @param string base
* @param string classname
*/
private static function _autoload($base, $classname)
{
$parts = explode(self::NS_GLUE, $classname);
$path = $base . self::DIR_GLUE . implode(self::DIR_GLUE, $parts) . '.php';
if (file_exists($path)) {
require_once($path);
}
}
/**
* Register default mime handlers. Is idempotent.
*/
public static function registerHandlers()
{
if (self::$registered === true) {
return;
}
// @todo check a conf file to load from that instead of
// hardcoding into the library?
$handlers = array(
\Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(),
\Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(),
\Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(),
\Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(),
);
foreach ($handlers as $mime => $handler) {
// Don't overwrite if the handler has already been registered
if (Httpful::hasParserRegistered($mime))
continue;
Httpful::register($mime, $handler);
}
self::$registered = true;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace Httpful\Exception;
class ConnectionErrorException extends \Exception
{
}

View file

@ -0,0 +1,50 @@
<?php
/**
* Mime Type: text/csv
* @author Raja Kapur <rajak@twistedthrottle.com>
*/
namespace Httpful\Handlers;
class CsvHandler extends MimeHandlerAdapter
{
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
if (empty($body))
return null;
$parsed = array();
$fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r');
while (($r = fgetcsv($fp)) !== FALSE) {
$parsed[] = $r;
}
if (empty($parsed))
throw new \Exception("Unable to parse response as CSV");
return $parsed;
}
/**
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
$fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+');
$i = 0;
foreach ($payload as $fields) {
if($i++ == 0) {
fputcsv($fp, array_keys($fields));
}
fputcsv($fp, $fields);
}
rewind($fp);
$data = stream_get_contents($fp);
fclose($fp);
return $data;
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* Mime Type: application/x-www-urlencoded
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class FormHandler extends MimeHandlerAdapter
{
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
$parsed = array();
parse_str($body, $parsed);
return $parsed;
}
/**
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
return http_build_query($payload, null, '&');
}
}

View file

@ -0,0 +1,40 @@
<?php
/**
* Mime Type: application/json
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class JsonHandler extends MimeHandlerAdapter
{
private $decode_as_array = false;
public function init(array $args)
{
$this->decode_as_array = !!(array_key_exists('decode_as_array', $args) ? $args['decode_as_array'] : false);
}
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
if (empty($body))
return null;
$parsed = json_decode($body, $this->decode_as_array);
if (is_null($parsed))
throw new \Exception("Unable to parse response as JSON");
return $parsed;
}
/**
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
return json_encode($payload);
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* Handlers are used to parse and serialize payloads for specific
* mime types. You can register a custom handler via the register
* method. You can also override a default parser in this way.
*/
namespace Httpful\Handlers;
class MimeHandlerAdapter
{
public function __construct(array $args = array())
{
$this->init($args);
}
/**
* Initial setup of
* @param array $args
*/
public function init(array $args)
{
}
/**
* @param string $body
* @return mixed
*/
public function parse($body)
{
return $body;
}
/**
* @param mixed $payload
* @return string
*/
function serialize($payload)
{
return (string) $payload;
}
}

View file

@ -0,0 +1,44 @@
# Handlers
Handlers are simple classes that are used to parse response bodies and serialize request payloads. All Handlers must extend the `MimeHandlerAdapter` class and implement two methods: `serialize($payload)` and `parse($response)`. Let's build a very basic Handler to register for the `text/csv` mime type.
<?php
class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
{
/**
* Takes a response body, and turns it into
* a two dimensional array.
*
* @param string $body
* @return mixed
*/
public function parse($body)
{
return str_getcsv($body);
}
/**
* Takes a two dimensional array and turns it
* into a serialized string to include as the
* body of a request
*
* @param mixed $payload
* @return string
*/
public function serialize($payload)
{
$serialized = '';
foreach ($payload as $line) {
$serialized .= '"' . implode('","', $line) . '"' . "\n";
}
return $serialized;
}
}
Finally, you must register this handler for a particular mime type.
Httpful::register('text/csv', new SimpleCsvHandler());
After this registering the handler in your source code, by default, any responses with a mime type of text/csv should be parsed by this handler.

View file

@ -0,0 +1,15 @@
<?php
/**
* Mime Type: text/html
* Mime Type: application/html+xml
*
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class XHtmlHandler extends MimeHandlerAdapter
{
// @todo add html specific parsing
// see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php
}

View file

@ -0,0 +1,120 @@
<?php
/**
* Mime Type: application/xml
*
* @author Zack Douglas <zack@zackerydouglas.info>
* @author Nathan Good <me@nategood.com>
*/
namespace Httpful\Handlers;
class XmlHandler extends MimeHandlerAdapter
{
/**
* @var string $namespace xml namespace to use with simple_load_string
*/
private $namespace;
/**
* @var int $libxml_opts see http://www.php.net/manual/en/libxml.constants.php
*/
private $libxml_opts;
/**
* @param array $conf sets configuration options
*/
public function __construct(array $conf = array())
{
$this->namespace = isset($conf['namespace']) ? $conf['namespace'] : '';
$this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0;
}
/**
* @param string $body
* @return mixed
* @throws Exception if unable to parse
*/
public function parse($body)
{
if (empty($body))
return null;
$parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace);
if ($parsed === false)
throw new \Exception("Unable to parse response as XML");
return $parsed;
}
/**
* @param mixed $payload
* @return string
* @throws Exception if unable to serialize
*/
public function serialize($payload)
{
list($_, $dom) = $this->_future_serializeAsXml($payload);
return $dom->saveXml();
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
*/
private function _future_serializeAsXml($value, $node = null, $dom = null)
{
if (!$dom) {
$dom = new \DOMDocument;
}
if (!$node) {
if (!is_object($value)) {
$node = $dom->createElement('response');
$dom->appendChild($node);
} else {
$node = $dom;
}
}
if (is_object($value)) {
$objNode = $dom->createElement(get_class($value));
$node->appendChild($objNode);
$this->_future_serializeObjectAsXml($value, $objNode, $dom);
} else if (is_array($value)) {
$arrNode = $dom->createElement('array');
$node->appendChild($arrNode);
$this->_future_serializeArrayAsXml($value, $arrNode, $dom);
} else if (is_bool($value)) {
$node->appendChild($dom->createTextNode($value?'TRUE':'FALSE'));
} else {
$node->appendChild($dom->createTextNode($value));
}
return array($node, $dom);
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
*/
private function _future_serializeArrayAsXml($value, &$parent, &$dom)
{
foreach ($value as $k => &$v) {
$n = $k;
if (is_numeric($k)) {
$n = "child-{$n}";
}
$el = $dom->createElement($n);
$parent->appendChild($el);
$this->_future_serializeAsXml($v, $el, $dom);
}
return array($parent, $dom);
}
/**
* @author Zack Douglas <zack@zackerydouglas.info>
*/
private function _future_serializeObjectAsXml($value, &$parent, &$dom)
{
$refl = new \ReflectionObject($value);
foreach ($refl->getProperties() as $pr) {
if (!$pr->isPrivate()) {
$el = $dom->createElement($pr->getName());
$parent->appendChild($el);
$this->_future_serializeAsXml($pr->getValue($value), $el, $dom);
}
}
return array($parent, $dom);
}
}

86
externals/httpful/src/Httpful/Http.php vendored Normal file
View file

@ -0,0 +1,86 @@
<?php
namespace Httpful;
/**
* @author Nate Good <me@nategood.com>
*/
class Http
{
const HEAD = 'HEAD';
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const DELETE = 'DELETE';
const PATCH = 'PATCH';
const OPTIONS = 'OPTIONS';
const TRACE = 'TRACE';
/**
* @return array of HTTP method strings
*/
public static function safeMethods()
{
return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE);
}
/**
* @return bool
* @param string HTTP method
*/
public static function isSafeMethod($method)
{
return in_array($method, self::safeMethods());
}
/**
* @return bool
* @param string HTTP method
*/
public static function isUnsafeMethod($method)
{
return !in_array($method, self::safeMethods());
}
/**
* @return array list of (always) idempotent HTTP methods
*/
public static function idempotentMethods()
{
// Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than
// not, it is not.
return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH);
}
/**
* @return bool
* @param string HTTP method
*/
public static function isIdempotent($method)
{
return in_array($method, self::safeidempotentMethodsMethods());
}
/**
* @return bool
* @param string HTTP method
*/
public static function isNotIdempotent($method)
{
return !in_array($method, self::idempotentMethods());
}
/**
* @deprecated Technically anything *can* have a body,
* they just don't have semantic meaning. So say's Roy
* http://tech.groups.yahoo.com/group/rest-discuss/message/9962
*
* @return array of HTTP method strings
*/
public static function canHaveBody()
{
return array(self::POST, self::PUT, self::PATCH, self::OPTIONS);
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Httpful;
class Httpful {
const VERSION = '0.1.7';
private static $mimeRegistrar = array();
private static $default = null;
/**
* @param string $mime_type
* @param MimeHandlerAdapter $handler
*/
public static function register($mimeType, \Httpful\Handlers\MimeHandlerAdapter $handler)
{
self::$mimeRegistrar[$mimeType] = $handler;
}
/**
* @param string $mime_type defaults to MimeHandlerAdapter
* @return MimeHandlerAdapter
*/
public static function get($mimeType = null)
{
if (isset(self::$mimeRegistrar[$mimeType])) {
return self::$mimeRegistrar[$mimeType];
}
if (empty(self::$default)) {
self::$default = new \Httpful\Handlers\MimeHandlerAdapter();
}
return self::$default;
}
/**
* Does this particular Mime Type have a parser registered
* for it?
* @return bool
*/
public static function hasParserRegistered($mimeType)
{
return isset(self::$mimeRegistrar[$mimeType]);
}
}

58
externals/httpful/src/Httpful/Mime.php vendored Normal file
View file

@ -0,0 +1,58 @@
<?php
namespace Httpful;
/**
* Class to organize the Mime stuff a bit more
* @author Nate Good <me@nategood.com>
*/
class Mime
{
const JSON = 'application/json';
const XML = 'application/xml';
const XHTML = 'application/html+xml';
const FORM = 'application/x-www-form-urlencoded';
const PLAIN = 'text/plain';
const JS = 'text/javascript';
const HTML = 'text/html';
const YAML = 'application/x-yaml';
const CSV = 'text/csv';
/**
* Map short name for a mime type
* to a full proper mime type
*/
public static $mimes = array(
'json' => self::JSON,
'xml' => self::XML,
'form' => self::FORM,
'plain' => self::PLAIN,
'text' => self::PLAIN,
'html' => self::HTML,
'xhtml' => self::XHTML,
'js' => self::JS,
'javascript'=> self::JS,
'yaml' => self::YAML,
'csv' => self::CSV,
);
/**
* Get the full Mime Type name from a "short name".
* Returns the short if no mapping was found.
* @return string full mime type (e.g. application/json)
* @param string common name for mime type (e.g. json)
*/
public static function getFullMime($short_name)
{
return array_key_exists($short_name, self::$mimes) ? self::$mimes[$short_name] : $short_name;
}
/**
* @return bool
* @param string $short_name
*/
public static function supportsMimeType($short_name)
{
return array_key_exists($short_name, self::$mimes);
}
}

View file

@ -0,0 +1,984 @@
<?php
namespace Httpful;
use Httpful\Exception\ConnectionErrorException;
/**
* Clean, simple class for sending HTTP requests
* in PHP.
*
* There is an emphasis of readability without loosing concise
* syntax. As such, you will notice that the library lends
* itself very nicely to "chaining". You will see several "alias"
* methods: more readable method definitions that wrap
* their more concise counterparts. You will also notice
* no public constructor. This two adds to the readability
* and "chainabilty" of the library.
*
* @author Nate Good <me@nategood.com>
*/
class Request
{
// Option constants
const SERIALIZE_PAYLOAD_NEVER = 0;
const SERIALIZE_PAYLOAD_ALWAYS = 1;
const SERIALIZE_PAYLOAD_SMART = 2;
const MAX_REDIRECTS_DEFAULT = 25;
public $uri,
$method = Http::GET,
$headers = array(),
$raw_headers = '',
$strict_ssl = false,
$content_type,
$expected_type,
$additional_curl_opts = array(),
$auto_parse = true,
$serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART,
$username,
$password,
$serialized_payload,
$payload,
$parse_callback,
$error_callback,
$follow_redirects = false,
$max_redirects = self::MAX_REDIRECTS_DEFAULT,
$payload_serializers = array();
// Options
// private $_options = array(
// 'serialize_payload_method' => self::SERIALIZE_PAYLOAD_SMART
// 'auto_parse' => true
// );
// Curl Handle
public $_ch,
$_debug;
// Template Request object
private static $_template;
/**
* We made the constructor private to force the factory style. This was
* done to keep the syntax cleaner and better the support the idea of
* "default templates". Very basic and flexible as it is only intended
* for internal use.
* @param array $attrs hash of initial attribute values
*/
private function __construct($attrs = null)
{
if (!is_array($attrs)) return;
foreach ($attrs as $attr => $value) {
$this->$attr = $value;
}
}
// Defaults Management
/**
* Let's you configure default settings for this
* class from a template Request object. Simply construct a
* Request object as much as you want to and then pass it to
* this method. It will then lock in those settings from
* that template object.
* The most common of which may be default mime
* settings or strict ssl settings.
* Again some slight memory overhead incurred here but in the grand
* scheme of things as it typically only occurs once
* @param Request $template
*/
public static function ini(Request $template)
{
self::$_template = clone $template;
}
/**
* Reset the default template back to the
* library defaults.
*/
public static function resetIni()
{
self::_initializeDefaults();
}
/**
* Get default for a value based on the template object
* @return mixed default value
* @param string|null $attr Name of attribute (e.g. mime, headers)
* if null just return the whole template object;
*/
public static function d($attr)
{
return isset($attr) ? self::$_template->$attr : self::$_template;
}
// Accessors
/**
* @return bool does the request have a timeout?
*/
public function hasTimeout()
{
return isset($this->timeout);
}
/**
* @return bool has the internal curl request been initialized?
*/
public function hasBeenInitialized()
{
return isset($this->_ch);
}
/**
* @return bool Is this request setup for basic auth?
*/
public function hasBasicAuth()
{
return isset($this->password) && isset($this->username);
}
/**
* @return bool Is this request setup for digest auth?
*/
public function hasDigestAuth()
{
return isset($this->password) && isset($this->username) && $this->additional_curl_opts['CURLOPT_HTTPAUTH'] = CURLAUTH_DIGEST;
}
/**
* Specify a HTTP timeout
* @return Request $this
* @param |int $timeout seconds to timeout the HTTP call
*/
public function timeout($timeout)
{
$this->timeout = $timeout;
return $this;
}
/**
* If the response is a 301 or 302 redirect, automatically
* send off another request to that location
* @return Request $this
* @param bool|int $follow follow or not to follow or maximal number of redirects
*/
public function followRedirects($follow = true)
{
$this->max_redirects = $follow === true ? self::MAX_REDIRECTS_DEFAULT : max(0, $follow);
$this->follow_redirects = (bool) $follow;
return $this;
}
/**
* @return Request $this
* @see Request::followRedirects()
*/
public function doNotFollowRedirects()
{
return $this->followRedirects(false);
}
/**
* Actually send off the request, and parse the response
* @return string|associative array of parsed results
* @throws ConnectionErrorException when unable to parse or communicate w server
*/
public function send()
{
if (!$this->hasBeenInitialized())
$this->_curlPrep();
$result = curl_exec($this->_ch);
if ($result === false) {
$this->_error(curl_error($this->_ch));
throw new ConnectionErrorException('Unable to connect.');
}
$info = curl_getinfo($this->_ch);
$response = explode("\r\n\r\n", $result, 2 + $info['redirect_count']);
$body = array_pop($response);
$headers = array_pop($response);
return new Response($body, $headers, $this);
}
public function sendIt()
{
return $this->send();
}
// Setters
/**
* @return Request this
* @param string $uri
*/
public function uri($uri)
{
$this->uri = $uri;
return $this;
}
/**
* User Basic Auth.
* Only use when over SSL/TSL/HTTPS.
* @return Request this
* @param string $username
* @param string $password
*/
public function basicAuth($username, $password)
{
$this->username = $username;
$this->password = $password;
return $this;
}
// @alias of basicAuth
public function authenticateWith($username, $password)
{
return $this->basicAuth($username, $password);
}
// @alias of basicAuth
public function authenticateWithBasic($username, $password)
{
return $this->basicAuth($username, $password);
}
/**
* User Digest Auth.
* @return Request this
* @param string $username
* @param string $password
*/
public function digestAuth($username, $password)
{
$this->addOnCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
return $this->basicAuth($username, $password);
}
// @alias of digestAuth
public function authenticateWithDigest($username, $password)
{
return $this->digestAuth($username, $password);
}
/**
* @return is this request setup for client side cert?
*/
public function hasClientSideCert() {
return isset($this->client_cert) && isset($this->client_key);
}
/**
* Use Client Side Cert Authentication
* @return Response $this
* @param string $key file path to client key
* @param string $cert file path to client cert
* @param string $passphrase for client key
* @param string $encoding default PEM
*/
public function clientSideCert($cert, $key, $passphrase = null, $encoding = 'PEM')
{
$this->client_cert = $cert;
$this->client_key = $key;
$this->client_passphrase = $passphrase;
$this->client_encoding = $encoding;
return $this;
}
// @alias of basicAuth
public function authenticateWithCert($cert, $key, $passphrase = null, $encoding = 'PEM')
{
return $this->clientSideCert($cert, $key, $passphrase, $encoding);
}
/**
* Set the body of the request
* @return Request this
* @param mixed $payload
* @param string $mimeType
*/
public function body($payload, $mimeType = null)
{
$this->mime($mimeType);
$this->payload = $payload;
// Iserntentially don't call _serializePayload yet. Wait until
// we actually send off the request to convert payload to string.
// At that time, the `serialized_payload` is set accordingly.
return $this;
}
/**
* Helper function to set the Content type and Expected as same in
* one swoop
* @return Request this
* @param string $mime mime type to use for content type and expected return type
*/
public function mime($mime)
{
if (empty($mime)) return $this;
$this->content_type = $this->expected_type = Mime::getFullMime($mime);
return $this;
}
// @alias of mime
public function sendsAndExpectsType($mime)
{
return $this->mime($mime);
}
// @alias of mime
public function sendsAndExpects($mime)
{
return $this->mime($mime);
}
/**
* Set the method. Shouldn't be called often as the preferred syntax
* for instantiation is the method specific factory methods.
* @return Request this
* @param string $method
*/
public function method($method)
{
if (empty($method)) return $this;
$this->method = $method;
return $this;
}
/**
* @return Request this
* @param string $mime
*/
public function expects($mime)
{
if (empty($mime)) return $this;
$this->expected_type = Mime::getFullMime($mime);
return $this;
}
// @alias of expects
public function expectsType($mime)
{
return $this->expects($mime);
}
/**
* @return Request this
* @param string $mime
*/
public function contentType($mime)
{
if (empty($mime)) return $this;
$this->content_type = Mime::getFullMime($mime);
return $this;
}
// @alias of contentType
public function sends($mime)
{
return $this->contentType($mime);
}
// @alias of contentType
public function sendsType($mime)
{
return $this->contentType($mime);
}
/**
* Do we strictly enforce SSL verification?
* @return Request this
* @param bool $strict
*/
public function strictSSL($strict)
{
$this->strict_ssl = $strict;
return $this;
}
public function withoutStrictSSL()
{
return $this->strictSSL(false);
}
public function withStrictSSL()
{
return $this->strictSSL(true);
}
/**
* Determine how/if we use the built in serialization by
* setting the serialize_payload_method
* The default (SERIALIZE_PAYLOAD_SMART) is...
* - if payload is not a scalar (object/array)
* use the appropriate serialize method according to
* the Content-Type of this request.
* - if the payload IS a scalar (int, float, string, bool)
* than just return it as is.
* When this option is set SERIALIZE_PAYLOAD_ALWAYS,
* it will always use the appropriate
* serialize option regardless of whether payload is scalar or not
* When this option is set SERIALIZE_PAYLOAD_NEVER,
* it will never use any of the serialization methods.
* Really the only use for this is if you want the serialize methods
* to handle strings or not (e.g. Blah is not valid JSON, but "Blah"
* is). Forcing the serialization helps prevent that kind of error from
* happening.
* @return Request $this
* @param int $mode
*/
public function serializePayload($mode)
{
$this->serialize_payload_method = $mode;
return $this;
}
/**
* @see Request::serializePayload()
* @return Request
*/
public function neverSerializePayload()
{
return $this->serializePayload(self::SERIALIZE_PAYLOAD_NEVER);
}
/**
* This method is the default behavior
* @see Request::serializePayload()
* @return Request
*/
public function smartSerializePayload()
{
return $this->serializePayload(self::SERIALIZE_PAYLOAD_SMART);
}
/**
* @see Request::serializePayload()
* @return Request
*/
public function alwaysSerializePayload()
{
return $this->serializePayload(self::SERIALIZE_PAYLOAD_ALWAYS);
}
/**
* Add an additional header to the request
* Can also use the cleaner syntax of
* $Request->withMyHeaderName($my_value);
* @see Request::__call()
*
* @return Request this
* @param string $header_name
* @param string $value
*/
public function addHeader($header_name, $value)
{
$this->headers[$header_name] = $value;
return $this;
}
/**
* Add group of headers all at once. Note: This is
* here just as a convenience in very specific cases.
* The preferred "readable" way would be to leverage
* the support for custom header methods.
* @return Response $this
* @param array $headers
*/
public function addHeaders(array $headers)
{
foreach ($headers as $header => $value) {
$this->addHeader($header, $value);
}
return $this;
}
/**
* @return Request
* @param bool $auto_parse perform automatic "smart"
* parsing based on Content-Type or "expectedType"
* If not auto parsing, Response->body returns the body
* as a string.
*/
public function autoParse($auto_parse = true)
{
$this->auto_parse = $auto_parse;
return $this;
}
/**
* @see Request::autoParse()
* @return Request
*/
public function withoutAutoParsing()
{
return $this->autoParse(false);
}
/**
* @see Request::autoParse()
* @return Request
*/
public function withAutoParsing()
{
return $this->autoParse(true);
}
/**
* Use a custom function to parse the response.
* @return Request this
* @param \Closure $callback Takes the raw body of
* the http response and returns a mixed
*/
public function parseWith(\Closure $callback)
{
$this->parse_callback = $callback;
return $this;
}
/**
* @see Request::parseResponsesWith()
* @return Request $this
* @param \Closure $callback
*/
public function parseResponsesWith(\Closure $callback)
{
return $this->parseWith($callback);
}
/**
* Register a callback that will be used to serialize the payload
* for a particular mime type. When using "*" for the mime
* type, it will use that parser for all responses regardless of the mime
* type. If a custom '*' and 'application/json' exist, the custom
* 'application/json' would take precedence over the '*' callback.
*
* @return Request $this
* @param string $mime mime type we're registering
* @param Closure $callback takes one argument, $payload,
* which is the payload that we'll be
*/
public function registerPayloadSerializer($mime, \Closure $callback)
{
$this->payload_serializers[Mime::getFullMime($mime)] = $callback;
return $this;
}
/**
* @see Request::registerPayloadSerializer()
* @return Request $this
* @param Closure $callback
*/
public function serializePayloadWith(\Closure $callback)
{
return $this->regregisterPayloadSerializer('*', $callback);
}
/**
* Magic method allows for neatly setting other headers in a
* similar syntax as the other setters. This method also allows
* for the sends* syntax.
* @return Request this
* @param string $method "missing" method name called
* the method name called should be the name of the header that you
* are trying to set in camel case without dashes e.g. to set a
* header for Content-Type you would use contentType() or more commonly
* to add a custom header like X-My-Header, you would use xMyHeader().
* To promote readability, you can optionally prefix these methods with
* "with" (e.g. withXMyHeader("blah") instead of xMyHeader("blah")).
* @param array $args in this case, there should only ever be 1 argument provided
* and that argument should be a string value of the header we're setting
*/
public function __call($method, $args)
{
// This method supports the sends* methods
// like sendsJSON, sendsForm
//!method_exists($this, $method) &&
if (substr($method, 0, 5) === 'sends') {
$mime = strtolower(substr($method, 5));
if (Mime::supportsMimeType($mime)) {
$this->sends(Mime::getFullMime($mime));
return $this;
}
// else {
// throw new \Exception("Unsupported Content-Type $mime");
// }
}
if (substr($method, 0, 7) === 'expects') {
$mime = strtolower(substr($method, 7));
if (Mime::supportsMimeType($mime)) {
$this->expects(Mime::getFullMime($mime));
return $this;
}
// else {
// throw new \Exception("Unsupported Content-Type $mime");
// }
}
// This method also adds the custom header support as described in the
// method comments
if (count($args) === 0)
return;
// Strip the sugar. If it leads with "with", strip.
// This is okay because: No defined HTTP headers begin with with,
// and if you are defining a custom header, the standard is to prefix it
// with an "X-", so that should take care of any collisions.
if (substr($method, 0, 4) === 'with')
$method = substr($method, 4);
// Precede upper case letters with dashes, uppercase the first letter of method
$header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)));
$this->addHeader($header, $args[0]);
return $this;
}
// Internal Functions
/**
* This is the default template to use if no
* template has been provided. The template
* tells the class which default values to use.
* While there is a slight overhead for object
* creation once per execution (not once per
* Request instantiation), it promotes readability
* and flexibility within the class.
*/
private static function _initializeDefaults()
{
// This is the only place you will
// see this constructor syntax. It
// is only done here to prevent infinite
// recusion. Do not use this syntax elsewhere.
// It goes against the whole readability
// and transparency idea.
self::$_template = new Request(array('method' => Http::GET));
// This is more like it...
self::$_template
->withoutStrictSSL();
}
/**
* Set the defaults on a newly instantiated object
* Doesn't copy variables prefixed with _
* @return Request this
*/
private function _setDefaults()
{
if (!isset(self::$_template))
self::_initializeDefaults();
foreach (self::$_template as $k=>$v) {
if ($k[0] != '_')
$this->$k = $v;
}
return $this;
}
private function _error($error)
{
// Default actions write to error log
// TODO add in support for various Loggers
error_log($error);
}
/**
* Factory style constructor works nicer for chaining. This
* should also really only be used internally. The Request::get,
* Request::post syntax is preferred as it is more readable.
* @return Request
* @param string $method Http Method
* @param string $mime Mime Type to Use
*/
public static function init($method = null, $mime = null)
{
// Setup our handlers, can call it here as it's idempotent
Bootstrap::init();
// Setup the default template if need be
if (!isset(self::$_template))
self::_initializeDefaults();
$request = new Request();
return $request
->_setDefaults()
->method($method)
->sendsType($mime)
->expectsType($mime);
}
/**
* Does the heavy lifting. Uses de facto HTTP
* library cURL to set up the HTTP request.
* Note: It does NOT actually send the request
* @return Request $this;
*/
public function _curlPrep()
{
// Check for required stuff
if (!isset($this->uri))
throw new \Exception('Attempting to send a request before defining a URI endpoint.');
$ch = curl_init($this->uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);
if ($this->hasBasicAuth()) {
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
}
if ($this->hasClientSideCert()) {
if (!file_exists($this->client_key))
throw new \Exception('Could not read Client Key');
if (!file_exists($this->client_cert))
throw new \Exception('Could not read Client Certificate');
curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding);
curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert);
curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key);
curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase);
// curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->client_cert_passphrase);
}
if ($this->hasTimeout()) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
}
if ($this->follow_redirects) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->max_redirects);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->strict_ssl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
// https://github.com/nategood/httpful/issues/37
// Except header removes any HTTP 1.1 Continue from response headers
$headers[] = 'Expect:';
if (!isset($this->headers['User-Agent'])) {
$headers[] = $this->buildUserAgent();
}
$headers[] = "Content-Type: {$this->content_type}";
// allow custom Accept header if set
if (!isset($this->headers['Accept'])) {
// http://pretty-rfc.herokuapp.com/RFC2616#header.accept
$accept = 'Accept: */*; q=0.5, text/plain; q=0.8, text/html;level=3;';
if (!empty($this->expected_type)) {
$accept .= "q=0.9, {$this->expected_type}";
}
$headers[] = $accept;
}
foreach ($this->headers as $header => $value) {
$headers[] = "$header: $value";
}
$url = \parse_url($this->uri);
$path = (isset($url['path']) ? $url['path'] : '/').(isset($url['query']) ? '?'.$url['query'] : '');
$this->raw_headers = "{$this->method} $path HTTP/1.1\r\n";
$host = (isset($url['host']) ? $url['host'] : 'localhost').(isset($url['port']) ? ':'.$url['port'] : '');
$this->raw_headers .= "Host: $host\r\n";
$this->raw_headers .= \implode("\r\n", $headers);
$this->raw_headers .= "\r\n";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if (isset($this->payload)) {
$this->serialized_payload = $this->_serializePayload($this->payload);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->serialized_payload);
}
if ($this->_debug) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
}
curl_setopt($ch, CURLOPT_HEADER, 1);
// If there are some additional curl opts that the user wants
// to set, we can tack them in here
foreach ($this->additional_curl_opts as $curlopt => $curlval) {
curl_setopt($ch, $curlopt, $curlval);
}
$this->_ch = $ch;
return $this;
}
public function buildUserAgent() {
$user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/';
$curl = \curl_version();
if (isset($curl['version'])) {
$user_agent .= $curl['version'];
} else {
$user_agent .= '?.?.?';
}
$user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')';
if (isset($_SERVER['SERVER_SOFTWARE'])) {
$user_agent .= ' ' . \preg_replace('~PHP/[\d\.]+~U', '',
$_SERVER['SERVER_SOFTWARE']);
} else {
if (isset($_SERVER['TERM_PROGRAM'])) {
$user_agent .= " {$_SERVER['TERM_PROGRAM']}";
}
if (isset($_SERVER['TERM_PROGRAM_VERSION'])) {
$user_agent .= "/{$_SERVER['TERM_PROGRAM_VERSION']}";
}
}
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$user_agent .= " {$_SERVER['HTTP_USER_AGENT']}";
}
$user_agent .= ')';
return $user_agent;
}
/**
* Semi-reluctantly added this as a way to add in curl opts
* that are not otherwise accessible from the rest of the API.
* @return Request $this
* @param string $curlopt
* @param mixed $curloptval
*/
public function addOnCurlOption($curlopt, $curloptval)
{
$this->additional_curl_opts[$curlopt] = $curloptval;
return $this;
}
/**
* Turn payload from structured data into
* a string based on the current Mime type.
* This uses the auto_serialize option to determine
* it's course of action. See serialize method for more.
* Renamed from _detectPayload to _serializePayload as of
* 2012-02-15.
*
* Added in support for custom payload serializers.
* The serialize_payload_method stuff still holds true though.
* @see Request::registerPayloadSerializer()
*
* @return string
* @param mixed $payload
*/
private function _serializePayload($payload)
{
if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER)
return $payload;
// When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized
if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload))
return $payload;
// Use a custom serializer if one is registered for this mime type
if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) {
$key = isset($this->payload_serializers[$this->content_type]) ? $this->content_type : '*';
return call_user_func($this->payload_serializers[$key], $payload);
}
return Httpful::get($this->content_type)->serialize($payload);
}
/**
* HTTP Method Get
* @return Request
* @param string $uri optional uri to use
* @param string $mime expected
*/
public static function get($uri, $mime = null)
{
return self::init(Http::GET)->uri($uri)->mime($mime);
}
/**
* Like Request:::get, except that it sends off the request as well
* returning a response
* @return Response
* @param string $uri optional uri to use
* @param string $mime expected
*/
public static function getQuick($uri, $mime = null)
{
return self::get($uri, $mime)->send();
}
/**
* HTTP Method Post
* @return Request
* @param string $uri optional uri to use
* @param string $payload data to send in body of request
* @param string $mime MIME to use for Content-Type
*/
public static function post($uri, $payload = null, $mime = null)
{
return self::init(Http::POST)->uri($uri)->body($payload, $mime);
}
/**
* HTTP Method Put
* @return Request
* @param string $uri optional uri to use
* @param string $payload data to send in body of request
* @param string $mime MIME to use for Content-Type
*/
public static function put($uri, $payload = null, $mime = null)
{
return self::init(Http::PUT)->uri($uri)->body($payload, $mime);
}
/**
* HTTP Method Patch
* @return Request
* @param string $uri optional uri to use
* @param string $payload data to send in body of request
* @param string $mime MIME to use for Content-Type
*/
public static function patch($uri, $payload = null, $mime = null)
{
return self::init(Http::PATCH)->uri($uri)->body($payload, $mime);
}
/**
* HTTP Method Delete
* @return Request
* @param string $uri optional uri to use
*/
public static function delete($uri, $mime = null)
{
return self::init(Http::DELETE)->uri($uri)->mime($mime);
}
/**
* HTTP Method Head
* @return Request
* @param string $uri optional uri to use
*/
public static function head($uri)
{
return self::init(Http::HEAD)->uri($uri);
}
/**
* HTTP Method Options
* @return Request
* @param string $uri optional uri to use
*/
public static function options($uri)
{
return self::init(Http::OPTIONS)->uri($uri);
}
}

View file

@ -0,0 +1,189 @@
<?php
namespace Httpful;
/**
* Models an HTTP response
*
* @author Nate Good <me@nategood.com>
*/
class Response
{
public $body,
$raw_body,
$headers,
$raw_headers,
$request,
$code = 0,
$content_type,
$parent_type,
$charset,
$is_mime_vendor_specific = false,
$is_mime_personal = false;
private $parsers;
/**
* @param string $body
* @param string $headers
* @param Request $request
*/
public function __construct($body, $headers, Request $request)
{
$this->request = $request;
$this->raw_headers = $headers;
$this->raw_body = $body;
$this->code = $this->_parseCode($headers);
$this->headers = Response\Headers::fromString($headers);
$this->_interpretHeaders();
$this->body = $this->_parse($body);
}
/**
* Status Code Definitions
*
* Informational 1xx
* Successful 2xx
* Redirection 3xx
* Client Error 4xx
* Server Error 5xx
*
* http://pretty-rfc.herokuapp.com/RFC2616#status.codes
*
* @return bool Did we receive a 4xx or 5xx?
*/
public function hasErrors()
{
return $this->code >= 400;
}
/**
* @return return bool
*/
public function hasBody()
{
return !empty($this->body);
}
/**
* Parse the response into a clean data structure
* (most often an associative array) based on the expected
* Mime type.
* @return array|string|object the response parse accordingly
* @param string Http response body
*/
public function _parse($body)
{
// If the user decided to forgo the automatic
// smart parsing, short circuit.
if (!$this->request->auto_parse) {
return $body;
}
// If provided, use custom parsing callback
if (isset($this->request->parse_callback)) {
return call_user_func($this->request->parse_callback, $body);
}
// Decide how to parse the body of the response in the following order
// 1. If provided, use the mime type specifically set as part of the `Request`
// 2. If a MimeHandler is registered for the content type, use it
// 3. If provided, use the "parent type" of the mime type from the response
// 4. Default to the content-type provided in the response
$parse_with = $this->request->expected_type;
if (empty($this->request->expected_type)) {
$parse_with = Httpful::hasParserRegistered($this->content_type)
? $this->content_type
: $this->parent_type;
}
return Httpful::get($parse_with)->parse($body);
}
/**
* Parse text headers from response into
* array of key value pairs
* @return array parse headers
* @param string $headers raw headers
*/
public function _parseHeaders($headers)
{
$headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY);
$parse_headers = array();
for ($i = 1; $i < count($headers); $i++) {
list($key, $raw_value) = explode(':', $headers[$i], 2);
$key = trim($key);
$value = trim($raw_value);
if (array_key_exists($key, $parse_headers)) {
// See HTTP RFC Sec 4.2 Paragraph 5
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
// If a header appears more than once, it must also be able to
// be represented as a single header with a comma-separated
// list of values. We transform accordingly.
$parse_headers[$key] .= ',' . $value;
} else {
$parse_headers[$key] = $value;
}
}
return $parse_headers;
}
public function _parseCode($headers)
{
$parts = explode(' ', substr($headers, 0, strpos($headers, "\r\n")));
if (count($parts) < 2 || !is_numeric($parts[1])) {
throw new \Exception("Unable to parse response code from HTTP response due to malformed response");
}
return intval($parts[1]);
}
/**
* After we've parse the headers, let's clean things
* up a bit and treat some headers specially
*/
public function _interpretHeaders()
{
// Parse the Content-Type and charset
$content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : '';
$content_type = explode(';', $content_type);
$this->content_type = $content_type[0];
if (count($content_type) == 2 && strpos($content_type[1], '=') !== false) {
list($nill, $this->charset) = explode('=', $content_type[1]);
}
// RFC 2616 states "text/*" Content-Types should have a default
// charset of ISO-8859-1. "application/*" and other Content-Types
// are assumed to have UTF-8 unless otherwise specified.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1
// http://www.w3.org/International/O-HTTP-charset.en.php
if (!isset($this->charset)) {
$this->charset = substr($this->content_type, 5) === 'text/' ? 'iso-8859-1' : 'utf-8';
}
// Is vendor type? Is personal type?
if (strpos($this->content_type, '/') !== false) {
list($type, $sub_type) = explode('/', $this->content_type);
$this->is_mime_vendor_specific = substr($sub_type, 0, 4) === 'vnd.';
$this->is_mime_personal = substr($sub_type, 0, 4) === 'prs.';
}
// Parent type (e.g. xml for application/vnd.github.message+xml)
$this->parent_type = $this->content_type;
if (strpos($this->content_type, '+') !== false) {
list($vendor, $this->parent_type) = explode('+', $this->content_type, 2);
$this->parent_type = Mime::getFullMime($this->parent_type);
}
}
/**
* @return string
*/
public function __toString()
{
return $this->raw_body;
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Httpful\Response;
final class Headers implements \ArrayAccess, \Countable {
private $headers;
private function __construct($headers)
{
$this->headers = $headers;
}
public static function fromString($string)
{
$lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY);
array_shift($lines); // HTTP HEADER
$headers = array();
foreach ($lines as $line) {
list($name, $value) = explode(':', $line, 2);
$headers[strtolower(trim($name))] = trim($value);
}
return new self($headers);
}
public function offsetExists($offset)
{
return isset($this->headers[strtolower($offset)]);
}
public function offsetGet($offset)
{
if (isset($this->headers[$name = strtolower($offset)])) {
return $this->headers[$name];
}
}
public function offsetSet($offset, $value)
{
throw new \Exception("Headers are read-only.");
}
public function offsetUnset($offset)
{
throw new \Exception("Headers are read-only.");
}
public function count()
{
return count($this->headers);
}
public function toArray()
{
return $this->headers;
}
}

View file

@ -0,0 +1,458 @@
<?php
/**
* Port over the original tests into a more traditional PHPUnit
* format. Still need to hook into a lightweight HTTP server to
* better test some things (e.g. obscure cURL settings). I've moved
* the old tests and node.js server to the tests/.legacy directory.
*
* @author Nate Good <me@nategood.com>
*/
namespace Httpful\Test;
require(dirname(dirname(dirname(__FILE__))) . '/bootstrap.php');
\Httpful\Bootstrap::init();
use Httpful\Httpful;
use Httpful\Request;
use Httpful\Mime;
use Httpful\Http;
use Httpful\Response;
class HttpfulTest extends \PHPUnit_Framework_TestCase
{
const TEST_SERVER = '127.0.0.1:8008';
const TEST_URL = 'http://127.0.0.1:8008';
const TEST_URL_400 = 'http://127.0.0.1:8008/400';
const SAMPLE_JSON_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/json
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_JSON_RESPONSE = '{"key":"value","object":{"key":"value"},"array":[1,2,3,4]}';
const SAMPLE_CSV_HEADER =
"HTTP/1.1 200 OK
Content-Type: text/csv
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_CSV_RESPONSE =
"Key1,Key2
Value1,Value2
\"40.0\",\"Forty\"";
const SAMPLE_XML_RESPONSE = '<stdClass><arrayProp><array><k1><myClass><intProp>2</intProp></myClass></k1></array></arrayProp><stringProp>a string</stringProp><boolProp>TRUE</boolProp></stdClass>';
const SAMPLE_XML_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/xml
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_VENDOR_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/vnd.nategood.message+xml
Connection: keep-alive
Transfer-Encoding: chunked\r\n";
const SAMPLE_VENDOR_TYPE = "application/vnd.nategood.message+xml";
const SAMPLE_MULTI_HEADER =
"HTTP/1.1 200 OK
Content-Type: application/json
Connection: keep-alive
Transfer-Encoding: chunked
X-My-Header:Value1
X-My-Header:Value2\r\n";
function testInit()
{
$r = Request::init();
// Did we get a 'Request' object?
$this->assertEquals('Httpful\Request', get_class($r));
}
function testMethods()
{
$valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head');
$url = 'http://example.com/';
foreach ($valid_methods as $method) {
$r = call_user_func(array('Httpful\Request', $method), $url);
$this->assertEquals('Httpful\Request', get_class($r));
$this->assertEquals(strtoupper($method), $r->method);
}
}
function testDefaults()
{
// Our current defaults are as follows
$r = Request::init();
$this->assertEquals(Http::GET, $r->method);
$this->assertFalse($r->strict_ssl);
}
function testShortMime()
{
// Valid short ones
$this->assertEquals(Mime::JSON, Mime::getFullMime('json'));
$this->assertEquals(Mime::XML, Mime::getFullMime('xml'));
$this->assertEquals(Mime::HTML, Mime::getFullMime('html'));
$this->assertEquals(Mime::CSV, Mime::getFullMime('csv'));
// Valid long ones
$this->assertEquals(Mime::JSON, Mime::getFullMime(Mime::JSON));
$this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML));
$this->assertEquals(Mime::HTML, Mime::getFullMime(Mime::HTML));
$this->assertEquals(Mime::CSV, Mime::getFullMime(Mime::CSV));
// No false positives
$this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML));
$this->assertNotEquals(Mime::JSON, Mime::getFullMime(Mime::XML));
$this->assertNotEquals(Mime::HTML, Mime::getFullMime(Mime::JSON));
$this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::CSV));
}
function testSettingStrictSsl()
{
$r = Request::init()
->withStrictSsl();
$this->assertTrue($r->strict_ssl);
$r = Request::init()
->withoutStrictSsl();
$this->assertFalse($r->strict_ssl);
}
function testSendsAndExpectsType()
{
$r = Request::init()
->sendsAndExpectsType(Mime::JSON);
$this->assertEquals(Mime::JSON, $r->expected_type);
$this->assertEquals(Mime::JSON, $r->content_type);
$r = Request::init()
->sendsAndExpectsType('html');
$this->assertEquals(Mime::HTML, $r->expected_type);
$this->assertEquals(Mime::HTML, $r->content_type);
$r = Request::init()
->sendsAndExpectsType('form');
$this->assertEquals(Mime::FORM, $r->expected_type);
$this->assertEquals(Mime::FORM, $r->content_type);
$r = Request::init()
->sendsAndExpectsType('application/x-www-form-urlencoded');
$this->assertEquals(Mime::FORM, $r->expected_type);
$this->assertEquals(Mime::FORM, $r->content_type);
$r = Request::init()
->sendsAndExpectsType(Mime::CSV);
$this->assertEquals(Mime::CSV, $r->expected_type);
$this->assertEquals(Mime::CSV, $r->content_type);
}
function testIni()
{
// Test setting defaults/templates
// Create the template
$template = Request::init()
->method(Http::POST)
->withStrictSsl()
->expectsType(Mime::HTML)
->sendsType(Mime::FORM);
Request::ini($template);
$r = Request::init();
$this->assertTrue($r->strict_ssl);
$this->assertEquals(Http::POST, $r->method);
$this->assertEquals(Mime::HTML, $r->expected_type);
$this->assertEquals(Mime::FORM, $r->content_type);
// Test the default accessor as well
$this->assertTrue(Request::d('strict_ssl'));
$this->assertEquals(Http::POST, Request::d('method'));
$this->assertEquals(Mime::HTML, Request::d('expected_type'));
$this->assertEquals(Mime::FORM, Request::d('content_type'));
Request::resetIni();
}
function testAccept()
{
$r = Request::get('http://example.com/')
->expectsType(Mime::JSON);
$this->assertEquals(Mime::JSON, $r->expected_type);
$r->_curlPrep();
$this->assertContains('application/json', $r->raw_headers);
}
function testCustomAccept()
{
$accept = 'application/api-1.0+json';
$r = Request::get('http://example.com/')
->addHeader('Accept', $accept);
$r->_curlPrep();
$this->assertContains($accept, $r->raw_headers);
$this->assertEquals($accept, $r->headers['Accept']);
}
function testUserAgent()
{
$r = Request::get('http://example.com/')
->withUserAgent('ACME/1.2.3');
$this->assertArrayHasKey('User-Agent', $r->headers);
$r->_curlPrep();
$this->assertContains('User-Agent: ACME/1.2.3', $r->raw_headers);
$this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers);
$r = Request::get('http://example.com/')
->withUserAgent('');
$this->assertArrayHasKey('User-Agent', $r->headers);
$r->_curlPrep();
$this->assertContains('User-Agent:', $r->raw_headers);
$this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers);
}
function testAuthSetup()
{
$username = 'nathan';
$password = 'opensesame';
$r = Request::get('http://example.com/')
->authenticateWith($username, $password);
$this->assertEquals($username, $r->username);
$this->assertEquals($password, $r->password);
$this->assertTrue($r->hasBasicAuth());
}
function testDigestAuthSetup()
{
$username = 'nathan';
$password = 'opensesame';
$r = Request::get('http://example.com/')
->authenticateWithDigest($username, $password);
$this->assertEquals($username, $r->username);
$this->assertEquals($password, $r->password);
$this->assertTrue($r->hasDigestAuth());
}
function testJsonResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals("value", $response->body->key);
$this->assertEquals("value", $response->body->object->key);
$this->assertInternalType('array', $response->body->array);
$this->assertEquals(1, $response->body->array[0]);
}
function testXMLResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response(self::SAMPLE_XML_RESPONSE, self::SAMPLE_XML_HEADER, $req);
$sxe = $response->body;
$this->assertEquals("object", gettype($sxe));
$this->assertEquals("SimpleXMLElement", get_class($sxe));
$bools = $sxe->xpath('/stdClass/boolProp');
list( , $bool ) = each($bools);
$this->assertEquals("TRUE", (string) $bool);
$ints = $sxe->xpath('/stdClass/arrayProp/array/k1/myClass/intProp');
list( , $int ) = each($ints);
$this->assertEquals("2", (string) $int);
$strings = $sxe->xpath('/stdClass/stringProp');
list( , $string ) = each($strings);
$this->assertEquals("a string", (string) $string);
}
function testCsvResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::CSV);
$response = new Response(self::SAMPLE_CSV_RESPONSE, self::SAMPLE_CSV_HEADER, $req);
$this->assertEquals("Key1", $response->body[0][0]);
$this->assertEquals("Value1", $response->body[1][0]);
$this->assertInternalType('string', $response->body[2][0]);
$this->assertEquals("40.0", $response->body[2][0]);
}
function testParsingContentTypeCharset()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
// $response = new Response(SAMPLE_JSON_RESPONSE, "", $req);
// // Check default content type of iso-8859-1
$response = new Response(self::SAMPLE_JSON_RESPONSE, "HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8\r\n", $req);
$this->assertInstanceOf('Httpful\Response\Headers', $response->headers);
$this->assertEquals($response->headers['Content-Type'], 'text/plain; charset=utf-8');
$this->assertEquals($response->content_type, 'text/plain');
$this->assertEquals($response->charset, 'utf-8');
}
function testEmptyResponseParse()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response("", self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals(null, $response->body);
$reqXml = Request::init()->sendsAndExpects(Mime::XML);
$responseXml = new Response("", self::SAMPLE_XML_HEADER, $reqXml);
$this->assertEquals(null, $responseXml->body);
}
function testNoAutoParse()
{
$req = Request::init()->sendsAndExpects(Mime::JSON)->withoutAutoParsing();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertInternalType('string', $response->body);
$req = Request::init()->sendsAndExpects(Mime::JSON)->withAutoParsing();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertInternalType('object', $response->body);
}
function testParseHeaders()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals('application/json', $response->headers['Content-Type']);
}
function testRawHeaders()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertContains('Content-Type: application/json', $response->raw_headers);
}
function testHasErrors()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response('', "HTTP/1.1 100 Continue\r\n", $req);
$this->assertFalse($response->hasErrors());
$response = new Response('', "HTTP/1.1 200 OK\r\n", $req);
$this->assertFalse($response->hasErrors());
$response = new Response('', "HTTP/1.1 300 Multiple Choices\r\n", $req);
$this->assertFalse($response->hasErrors());
$response = new Response('', "HTTP/1.1 400 Bad Request\r\n", $req);
$this->assertTrue($response->hasErrors());
$response = new Response('', "HTTP/1.1 500 Internal Server Error\r\n", $req);
$this->assertTrue($response->hasErrors());
}
function test_parseCode()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$code = $response->_parseCode("HTTP/1.1 406 Not Acceptable\r\n");
$this->assertEquals(406, $code);
}
function testToString()
{
$req = Request::init()->sendsAndExpects(Mime::JSON);
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals(self::SAMPLE_JSON_RESPONSE, (string)$response);
}
function test_parseHeaders()
{
$parse_headers = Response\Headers::fromString(self::SAMPLE_JSON_HEADER);
$this->assertCount(3, $parse_headers);
$this->assertEquals('application/json', $parse_headers['Content-Type']);
$this->assertTrue(isset($parse_headers['Connection']));
}
function testMultiHeaders()
{
$req = Request::init();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_MULTI_HEADER, $req);
$parse_headers = $response->_parseHeaders(self::SAMPLE_MULTI_HEADER);
$this->assertEquals('Value1,Value2', $parse_headers['X-My-Header']);
}
function testDetectContentType()
{
$req = Request::init();
$response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
$this->assertEquals('application/json', $response->headers['Content-Type']);
}
function testMissingBodyContentType()
{
$body = 'A string';
$request = Request::post(HttpfulTest::TEST_URL, $body)->_curlPrep();
$this->assertEquals($body, $request->serialized_payload);
}
function testParentType()
{
// Parent type
$request = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request);
$this->assertEquals("application/xml", $response->parent_type);
$this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type);
$this->assertTrue($response->is_mime_vendor_specific);
// Make sure we still parsed as if it were plain old XML
$this->assertEquals("Nathan", $response->body->name->__toString());
}
function testMissingContentType()
{
// Parent type
$request = Request::init()->sendsAndExpects(Mime::XML);
$response = new Response('<xml><name>Nathan</name></xml>',
"HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked\r\n", $request);
$this->assertEquals("", $response->content_type);
}
function testCustomMimeRegistering()
{
// Register new mime type handler for "application/vnd.nategood.message+xml"
Httpful::register(self::SAMPLE_VENDOR_TYPE, new DemoMimeHandler());
$this->assertTrue(Httpful::hasParserRegistered(self::SAMPLE_VENDOR_TYPE));
$request = Request::init();
$response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request);
$this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type);
$this->assertEquals('custom parse', $response->body);
}
public function testShorthandMimeDefinition()
{
$r = Request::init()->expects('json');
$this->assertEquals(Mime::JSON, $r->expected_type);
$r = Request::init()->expectsJson();
$this->assertEquals(Mime::JSON, $r->expected_type);
}
public function testOverrideXmlHandler()
{
// Lazy test...
$prev = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertEquals($prev, new \Httpful\Handlers\XmlHandler());
$conf = array('namespace' => 'http://example.com');
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
$new = \Httpful\Httpful::get(\Httpful\Mime::XML);
$this->assertNotEquals($prev, $new);
}
}
class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter {
public function parse($body) {
return 'custom parse';
}
}

9
externals/httpful/tests/phpunit.xml vendored Normal file
View file

@ -0,0 +1,9 @@
<phpunit>
<testsuite name="Httpful">
<directory>.</directory>
</testsuite>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
</logging>
</phpunit>

12
externals/restful/.gitignore vendored Normal file
View file

@ -0,0 +1,12 @@
# composer
.buildpath
composer.lock
composer.phar
vendor
# phar
*.phar
# eclipse-pdt
.settings
.project

8
externals/restful/.travis.yml vendored Normal file
View file

@ -0,0 +1,8 @@
language: php
before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install --prefer-source
script: phpunit --bootstrap vendor/autoload.php tests/
php:
- 5.3
- 5.4

22
externals/restful/LICENSE vendored Normal file
View file

@ -0,0 +1,22 @@
Copyright (c) 2012 Noone
MIT License
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 the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

111
externals/restful/README.md vendored Normal file
View file

@ -0,0 +1,111 @@
# RESTful
Library for writing RESTful PHP clients.
[![Build Status](https://secure.travis-ci.org/bninja/restful.png)](http://travis-ci.org/bninja/restful)
The design of this library was heavily influenced by [Httpful](https://github.com/nategood/httpful).
## Requirements
- [PHP](http://www.php.net) >= 5.3 **with** [cURL](http://www.php.net/manual/en/curl.installation.php)
- [Httpful](https://github.com/nategood/httpful) >= 0.1
## Issues
Please use appropriately tagged github [issues](https://github.com/bninja/restful/issues) to request features or report bugs.
## Installation
You can install using [composer](#composer), a [phar](#phar) package or from [source](#source). Note that RESTful is [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) compliant:
### Composer
If you don't have Composer [install](http://getcomposer.org/doc/00-intro.md#installation) it:
$ curl -s https://getcomposer.org/installer | php
Add this to your `composer.json`:
{
"require": {
"bninja/restful": "*"
}
}
Refresh your dependencies:
$ php composer.phar update
Then make sure to `require` the autoloader and initialize both:
<?php
require(__DIR__ . '/vendor/autoload.php');
Httpful\Bootstrap::init();
RESTful\Bootstrap::init();
...
### Phar
Download an Httpful [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/nategood/httpful/downloads):
$ curl -s -L -o httpful.phar https://github.com/downloads/nategood/httpful/httpful.phar
Download a RESTful [phar](http://php.net/manual/en/book.phar.php) file, which are all [here](https://github.com/bninja/restful/downloads):
$ curl -s -L -o restful.phar https://github.com/bninja/restful/downloads/restful-{VERSION}.phar
And then `include` both:
<?php
include(__DIR__ . '/httpful.phar');
include(__DIR__ . '/restful.phar');
...
### Source
Download [Httpful](https://github.com/nategood/httpful) source:
$ curl -s -L -o httpful.zip https://github.com/nategood/httpful/zipball/master;
$ unzip httpful.zip; mv nategood-httpful* httpful; rm httpful.zip
Download the RESTful source:
$ curl -s -L -o restful.zip https://github.com/bninja/restful/zipball/master
$ unzip restful.zip; mv bninja-restful-* restful; rm restful.zip
And then `require` both bootstrap files:
<?php
require(__DIR__ . "/httpful/bootstrap.php")
require(__DIR__ . "/restful/bootstrap.php")
...
## Usage
TODO
## Testing
$ phpunit --bootstrap vendor/autoload.php tests/
## Publishing
1. Ensure that **all** [tests](#testing) pass
2. Increment minor `VERSION` in `src/RESTful/Settings` and `composer.json` (`git commit -am 'v{VERSION} release'`)
3. Tag it (`git tag -a v{VERSION} -m 'v{VERSION} release'`)
4. Push the tag (`git push --tag`)
5. [Packagist](http://packagist.org/packages/bninja/restful) will see the new tag and take it from there
6. Build (`build-phar`) and upload a [phar](http://php.net/manual/en/book.phar.php) file
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Write your code **and [tests](#testing)**
4. Ensure all tests still pass (`phpunit --bootstrap vendor/autoload.php tests/`)
5. Commit your changes (`git commit -am 'Add some feature'`)
6. Push to the branch (`git push origin my-new-feature`)
7. Create new pull request

4
externals/restful/bootstrap.php vendored Normal file
View file

@ -0,0 +1,4 @@
<?php
require(__DIR__ . '/src/RESTful/Bootstrap.php');
\RESTful\Bootstrap::init();

36
externals/restful/build-phar vendored Executable file
View file

@ -0,0 +1,36 @@
#!/usr/bin/php
<?php
include('src/RESTful/Settings.php');
function exit_unless($condition, $msg = null) {
if ($condition)
return;
echo "[FAIL] $msg";
exit(1);
}
echo "Building Phar... ";
$base_dir = dirname(__FILE__);
$source_dir = $base_dir . '/src/RESTful/';
$phar_name = 'restful.phar';
$phar_path = $base_dir . '/' . $phar_name;
$phar = new Phar($phar_path, 0, $phar_name);
$stub = <<<HEREDOC
<?php
// Phar Stub File
Phar::mapPhar('restful.phar');
include('phar://restful.phar/RESTful/Bootstrap.php');
\RESTful\Bootstrap::pharInit();
__HALT_COMPILER();
HEREDOC;
$phar->setStub($stub);
exit_unless($phar, "Unable to create a phar. Make sure you have phar.readonly=0 set in your ini file.");
$phar->buildFromDirectory(dirname($source_dir));
echo "[ OK ]\n";
echo "Renaming Phar... ";
$phar_versioned_name = 'restful-' . \RESTful\Settings::VERSION . '.phar';
$phar_versioned_path = $base_dir . '/' . $phar_versioned_name;
rename($phar_path, $phar_versioned_path);
echo "[ OK ]\n";

18
externals/restful/composer.json vendored Normal file
View file

@ -0,0 +1,18 @@
{
"name": "bninja/restful",
"description": "Library for writing RESTful PHP clients.",
"homepage": "http://github.com/bninja/restful",
"license": "MIT",
"keywords": ["http", "api", "client", "rest"],
"version": "0.1.7",
"authors": [
],
"require": {
"nategood/httpful": "*"
},
"autoload": {
"psr-0": {
"RESTful": "src/"
}
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace RESTful;
/**
* Bootstrapper for RESTful does autoloading.
*/
class Bootstrap
{
const DIR_SEPARATOR = DIRECTORY_SEPARATOR;
const NAMESPACE_SEPARATOR = '\\';
public static $initialized = false;
public static function init()
{
spl_autoload_register(array('\RESTful\Bootstrap', 'autoload'));
}
public static function autoload($classname)
{
self::_autoload(dirname(dirname(__FILE__)), $classname);
}
public static function pharInit()
{
spl_autoload_register(array('\RESTful\Bootstrap', 'pharAutoload'));
}
public static function pharAutoload($classname)
{
self::_autoload('phar://restful.phar', $classname);
}
private static function _autoload($base, $classname)
{
$parts = explode(self::NAMESPACE_SEPARATOR, $classname);
$path = $base . self::DIR_SEPARATOR . implode(self::DIR_SEPARATOR, $parts) . '.php';
if (file_exists($path)) {
require_once($path);
}
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace RESTful;
use RESTful\Exceptions\HTTPError;
use RESTful\Settings;
class Client
{
public function __construct($settings_class, $request_class = null, $convert_error = null)
{
$this->request_class = $request_class == null ? '\Httpful\Request' : $request_class;
$this->settings_class = $settings_class;
$this->convert_error = $convert_error;
}
public function get($uri)
{
$settings_class = $this->settings_class;
$url = $settings_class::$url_root . $uri;
$request_class = $this->request_class;
$request = $request_class::get($url);
return $this->_op($request);
}
public function post($uri, $payload)
{
$settings_class = $this->settings_class;
$url = $settings_class::$url_root . $uri;
$request_class = $this->request_class;
$request = $request_class::post($url, $payload, 'json');
return $this->_op($request);
}
public function put($uri, $payload)
{
$settings_class = $this->settings_class;
$url = $settings_class::$url_root . $uri;
$request_class = $this->request_class;
$request = $request_class::put($url, $payload, 'json');
return $this->_op($request);
}
public function delete($uri)
{
$settings_class = $this->settings_class;
$url = $settings_class::$url_root . $uri;
$request_class = $this->request_class;
$request = $request_class::delete($url);
return $this->_op($request);
}
private function _op($request)
{
$settings_class = $this->settings_class;
$user_agent = $settings_class::$agent . '/' . $settings_class::$version;
$request->headers['User-Agent'] = $user_agent;
if ($settings_class::$api_key != null) {
$request = $request->authenticateWith($settings_class::$api_key, '');
}
$request->expects('json');
$response = $request->sendIt();
if ($response->hasErrors() || $response->code == 300) {
if ($this->convert_error != null) {
$error = call_user_func($this->convert_error, $response);
} else {
$error = new HTTPError($response);
}
throw $error;
}
return $response;
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace RESTful;
class Collection extends Itemization
{
public function __construct($resource, $uri, $data = null)
{
parent::__construct($resource, $uri, $data);
$this->_parseUri();
}
private function _parseUri()
{
$parsed = parse_url($this->uri);
$this->_uri = $parsed['path'];
if (array_key_exists('query', $parsed)) {
foreach (explode('&', $parsed['query']) as $param) {
$param = explode('=', $param);
$key = urldecode($param[0]);
$val = (count($param) == 1) ? null : urldecode($param[1]);
// size
if ($key == 'limit') {
$this->_size = $val;
}
}
}
}
public function create($payload)
{
$class = $this->resource;
$client = $class::getClient();
$response = $client->post($this->uri, $payload);
return new $this->resource($response->body);
}
public function query()
{
return new Query($this->resource, $this->uri);
}
public function paginate()
{
return new Pagination($this->resource, $this->uri);
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace RESTful\Exceptions;
/**
* Base class for all RESTful\Exceptions.
*/
class Base extends \Exception
{
}

View file

@ -0,0 +1,28 @@
<?php
namespace RESTful\Exceptions;
/**
* Indicates an HTTP level error has occurred. The underlying HTTP response is
* stored as response member. The response payload fields if any are stored as
* members of the same name.
*
* @see \Httpful\Response
*/
class HTTPError extends Base
{
public $response;
public function __construct($response)
{
$this->response = $response;
$this->_objectify($this->response->body);
}
protected function _objectify($fields)
{
foreach ($fields as $key => $val) {
$this->$key = $val;
}
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace RESTful\Exceptions;
/**
* Indicates that a query unexpectedly returned multiple results when at most
* one was expected.
*/
class MultipleResultsFound extends Base
{
}

View file

@ -0,0 +1,10 @@
<?php
namespace RESTful\Exceptions;
/**
* Indicates that a query unexpectedly returned no results.
*/
class NoResultFound extends Base
{
}

85
externals/restful/src/RESTful/Field.php vendored Normal file
View file

@ -0,0 +1,85 @@
<?php
namespace RESTful;
class Field
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
public function __get($name)
{
return new Field($this->name . '.' . $name);
}
public function in($vals)
{
return new FilterExpression($this->name, 'in', $vals, '!in');
}
public function startswith($prefix)
{
if (!is_string($prefix)) {
throw new \InvalidArgumentException('"startswith" prefix must be a string');
}
return new FilterExpression($this->name, 'contains', $prefix);
}
public function endswith($suffix)
{
if (!is_string($suffix)) {
throw new \InvalidArgumentException('"endswith" suffix must be a string');
}
return new FilterExpression($this->name, 'contains', $suffix);
}
public function contains($fragment)
{
if (!is_string($fragment)) {
throw new \InvalidArgumentException('"contains" fragment must be a string');
}
return new FilterExpression($this->name, 'contains', $fragment, '!contains');
}
public function eq($val)
{
return new FilterExpression($this->name, '=', $val, '!eq');
}
public function lt($val)
{
return new FilterExpression($this->name, '<', $val, '>=');
}
public function lte($val)
{
return new FilterExpression($this->name, '<=', $val, '>');
}
public function gt($val)
{
return new FilterExpression($this->name, '>', $val, '<=');
}
public function gte($val)
{
return new FilterExpression($this->name, '>=', $val, '<');
}
public function asc()
{
return new SortExpression($this->name, true);
}
public function desc()
{
return new SortExpression($this->name, false);
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace RESTful;
class Fields
{
public function __get($name)
{
return new Field($name);
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace RESTful;
class FilterExpression
{
public $field,
$op,
$val,
$not_op;
public function __construct($field, $op, $val, $not_op = null)
{
$this->field = $field;
$this->op = $op;
$this->val = $val;
$this->not_op = $not_op;
}
public function not()
{
if (null === $this->not_op) {
throw new \LogicException(sprintf('Filter cannot be inverted'));
}
$temp = $this->op;
$this->op = $this->not_op;
$this->not_op = $temp;
return $this;
}
}

View file

@ -0,0 +1,99 @@
<?php
namespace RESTful;
class Itemization implements \IteratorAggregate, \ArrayAccess
{
public $resource,
$uri;
protected $_page,
$_offset = 0,
$_size = 25;
public function __construct($resource, $uri, $data = null)
{
$this->resource = $resource;
$this->uri = $uri;
if ($data != null) {
$this->_page = new Page($resource, $uri, $data);
} else {
$this->_page = null;
}
}
protected function _getPage($offset = null)
{
if ($this->_page == null) {
$this->_offset = ($offset == null) ? 0 : $offset * $this->_size;
$uri = $this->_buildUri();
$this->_page = new Page($this->resource, $uri);
} elseif ($offset != null) {
$offset = $offset * $this->_size;
if ($offset != $this->_offset) {
$this->_offset = $offset;
$uri = $this->_buildUri();
$this->_page = new Page($this->resource, $uri);
}
}
return $this->_page;
}
protected function _getItem($offset)
{
$page_offset = floor($offset / $this->_size);
$page = $this->_getPage($page_offset);
return $page->items[$offset - $page->offset];
}
public function total()
{
return $this->_getPage()->total;
}
protected function _buildUri($offset = null)
{
# TODO: hacky but works for now
$offset = ($offset == null) ? $this->_offset : $offset;
if (strpos($this->uri, '?') === false) {
$uri = $this->uri . '?';
} else {
$uri = $this->uri . '&';
}
$uri = $uri . 'offset=' . strval($offset);
return $uri;
}
// IteratorAggregate
public function getIterator()
{
$uri = $this->_buildUri($offset = 0);
$uri = $this->_buildUri($offset = 0);
return new ItemizationIterator($this->resource, $uri);
}
// ArrayAccess
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException(get_class($this) . ' array access is read-only');
}
public function offsetExists($offset)
{
return (0 <= $offset && $offset < $this->total());
}
public function offsetUnset($offset)
{
throw new \BadMethodCallException(get_class($this) . ' array access is read-only');
}
public function offsetGet($offset)
{
return $this->_getItem($offset);
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace RESTful;
class ItemizationIterator implements \Iterator
{
protected $_page,
$_offset = 0;
public function __construct($resource, $uri, $data = null)
{
$this->_page = new Page($resource, $uri, $data);
}
// Iterator
public function current()
{
return $this->_page->items[$this->_offset];
}
public function key()
{
return $this->_page->offset + $this->_offset;
}
public function next()
{
$this->_offset += 1;
if ($this->_offset >= count($this->_page->items)) {
$this->_offset = 0;
$this->_page = $this->_page->next();
}
}
public function rewind()
{
$this->_page = $this->_page->first();
$this->_offset = 0;
}
public function valid()
{
return ($this->_page != null && $this->_offset < count($this->_page->items));
}
}

72
externals/restful/src/RESTful/Page.php vendored Normal file
View file

@ -0,0 +1,72 @@
<?php
namespace RESTful;
class Page
{
public $resource,
$total,
$items,
$offset,
$limit;
private $_first_uri,
$_previous_uri,
$_next_uri,
$_last_uri;
public function __construct($resource, $uri, $data = null)
{
$this->resource = $resource;
if ($data == null) {
$client = $resource::getClient();
$data = $client->get($uri)->body;
}
$this->total = $data->total;
$this->items = array_map(
function ($x) use ($resource) {
return new $resource($x);
},
$data->items);
$this->offset = $data->offset;
$this->limit = $data->limit;
$this->_first_uri = property_exists($data, 'first_uri') ? $data->first_uri : null;
$this->_previous_uri = property_exists($data, 'previous_uri') ? $data->previous_uri : null;
$this->_next_uri = property_exists($data, 'next_uri') ? $data->next_uri : null;
$this->_last_uri = property_exists($data, 'last_uri') ? $data->last_uri : null;
}
public function first()
{
return new Page($this->resource, $this->_first_uri);
}
public function next()
{
if (!$this->hasNext()) {
return null;
}
return new Page($this->resource, $this->_next_uri);
}
public function hasNext()
{
return $this->_next_uri != null;
}
public function previous()
{
return new Page($this->resource, $this->_previous_uri);
}
public function hasPrevious()
{
return $this->_previous_uri != null;
}
public function last()
{
return new Page($this->resource, $this->_last_uri);
}
}

View file

@ -0,0 +1,90 @@
<?php
namespace RESTful;
class Pagination implements \IteratorAggregate, \ArrayAccess
{
public $resource,
$uri;
protected $_page,
$_offset = 0,
$_size = 25;
public function __construct($resource, $uri, $data = null)
{
$this->resource = $resource;
$this->uri = $uri;
if ($data != null) {
$this->_page = new Page($resource, $uri, $data);
} else {
$this->_page = null;
}
}
protected function _getPage($offset = null)
{
if ($this->_page == null) {
$this->_offset = ($offset == null) ? 0 : $offset * $this->_size;
$uri = $this->_buildUri();
$this->_page = new Page($this->resource, $uri);
} elseif ($offset != null) {
$offset = $offset * $this->_size;
if ($offset != $this->_offset) {
$this->_offset = $offset;
$uri = $this->_buildUri();
$this->_page = new Page($this->resource, $uri);
}
}
return $this->_page;
}
public function total()
{
return floor($this->_getPage()->total / $this->_size);
}
protected function _buildUri($offset = null)
{
# TODO: hacky but works for now
$offset = ($offset == null) ? $this->_offset : $offset;
if (strpos($this->uri, '?') === false) {
$uri = $this->uri . '?';
} else {
$uri = $this->uri . '&';
}
$uri = $uri . 'offset=' . strval($offset);
return $uri;
}
// IteratorAggregate
public function getIterator()
{
$uri = $this->_buildUri($offset = 0);
return new PaginationIterator($this->resource, $uri);
}
// ArrayAccess
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException(get_class($this) . ' array access is read-only');
}
public function offsetExists($offset)
{
return (0 <= $offset && $offset < $this->total());
}
public function offsetUnset($offset)
{
throw new \BadMethodCallException(get_class($this) . ' array access is read-only');
}
public function offsetGet($offset)
{
return $this->_getPage($offset);
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace RESTful;
class PaginationIterator implements \Iterator
{
public function __construct($resource, $uri, $data = null)
{
$this->_page = new Page($resource, $uri, $data);
}
// Iterator
public function current()
{
return $this->_page;
}
public function key()
{
return $this->_page->index;
}
public function next()
{
$this->_page = $this->_page->next();
}
public function rewind()
{
$this->_page = $this->_page->first();
}
public function valid()
{
return $this->_page != null;
}
}

161
externals/restful/src/RESTful/Query.php vendored Normal file
View file

@ -0,0 +1,161 @@
<?php
namespace RESTful;
use RESTful\Exceptions\NoResultFound;
use RESTful\Exceptions\MultipleResultsFound;
class Query extends Itemization
{
public $filters = array(),
$sorts = array(),
$size;
public function __construct($resource, $uri)
{
parent::__construct($resource, $uri);
$this->size = $this->_size;
$this->_parseUri($uri);
}
private function _parseUri($uri)
{
$parsed = parse_url($uri);
$this->uri = $parsed['path'];
if (array_key_exists('query', $parsed)) {
foreach (explode('&', $parsed['query']) as $param) {
$param = explode('=', $param);
$key = urldecode($param[0]);
$val = (count($param) == 1) ? null : urldecode($param[1]);
// limit
if ($key == 'limit') {
$this->size = $this->_size = $val;
} // sorts
else if ($key == 'sort') {
array_push($this->sorts, $val);
} // everything else
else {
if (!array_key_exists($key, $this->filters)) {
$this->filters[$key] = array();
}
if (!is_array($val)) {
$val = array($val);
}
$this->filters[$key] = array_merge($this->filters[$key], $val);
}
}
}
}
protected function _buildUri($offset = null)
{
// params
$params = array_merge(
$this->filters,
array(
'sort' => $this->sorts,
'limit' => $this->_size,
'offset' => ($offset == null) ? $this->_offset : $offset
)
);
$getSingle = function ($v) {
if (is_array($v) && count($v) == 1)
return $v[0];
return $v;
};
$params = array_map($getSingle, $params);
// url encode params
// NOTE: http://stackoverflow.com/a/8171667/1339571
$qs = http_build_query($params);
$qs = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $qs);
return $this->uri . '?' . $qs;
}
private function _reset()
{
$this->_page = null;
}
public function filter($expression)
{
if ($expression->op == '=') {
$field = $expression->field;
} else {
$field = $expression->field . '[' . $expression->op . ']';
}
if (is_array($expression->val)) {
$val = implode(',', $expression->val);
} else {
$val = $expression->val;
}
if (!array_key_exists($field, $this->filters)) {
$this->filters[$field] = array();
}
array_push($this->filters[$field], $val);
$this->_reset();
return $this;
}
public function sort($expression)
{
$dir = $expression->ascending ? 'asc' : 'desc';
array_push($this->sorts, $expression->field . ',' . $dir);
$this->_reset();
return $this;
}
public function limit($limit)
{
$this->size = $this->_size = $limit;
$this->_reset();
return $this;
}
public function all()
{
$items = array();
foreach ($this as $item) {
array_push($items, $item);
}
return $items;
}
public function first()
{
$prev_size = $this->_size;
$this->_size = 1;
$page = new Page($this->resource, $this->_buildUri());
$this->_size = $prev_size;
$item = count($page->items) != 0 ? $page->items[0] : null;
return $item;
}
public function one()
{
$prev_size = $this->_size;
$this->_size = 2;
$page = new Page($this->resource, $this->_buildUri());
$this->_size = $prev_size;
if (count($page->items) == 1) {
return $page->items[0];
}
if (count($page->items) == 0) {
throw new NoResultFound();
}
throw new MultipleResultsFound();
}
public function paginate()
{
return new Pagination($this->resource, $this->_buildUri());
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace RESTful;
class Registry
{
protected $_resources = array();
public function add($resource)
{
array_push($this->_resources, $resource);
}
public function match($uri)
{
foreach ($this->_resources as $resource) {
$spec = $resource::getURISpec();
$result = $spec->match($uri);
if ($result == null) {
continue;
}
$result['class'] = $resource;
return $result;
}
return null;
}
}

View file

@ -0,0 +1,205 @@
<?php
namespace RESTful;
abstract class Resource
{
protected $_collection_uris,
$_member_uris;
public static function getClient()
{
$class = get_called_class();
return $class::$_client;
}
public static function getRegistry()
{
$class = get_called_class();
return $class::$_registry;
}
public static function getURISpec()
{
$class = get_called_class();
return $class::$_uri_spec;
}
public function __construct($fields = null)
{
if ($fields == null) {
$fields = array();
}
$this->_objectify($fields);
}
public function __get($name)
{
// collection uri
if (array_key_exists($name, $this->_collection_uris)) {
$result = $this->_collection_uris[$name];
$this->$name = new Collection($result['class'], $result['uri']);
return $this->$name;
} // member uri
else if (array_key_exists($name, $this->_member_uris)) {
$result = $this->$_collection_uris[$name];
$response = self::getClient() . get($result['uri']);
$class = $result['class'];
$this->$name = new $class($response->body);
return $this->$name;
}
// unknown
$trace = debug_backtrace();
trigger_error(
sprintf('Undefined property via __get(): %s in %s on line %s', $name, $trace[0]['file'], $trace[0]['line']),
E_USER_NOTICE
);
return null;
}
public function __isset($name)
{
if (array_key_exists($name, $this->_collection_uris) || array_key_exists($name, $this->_member_uris)) {
return true;
}
return false;
}
protected function _objectify($fields)
{
// initialize uris
$this->_collection_uris = array();
$this->_member_uris = array();
foreach ($fields as $key => $val) {
// nested uri
if ((strlen($key) - 3) == strrpos($key, 'uri', 0) && $key != 'uri') {
$result = self::getRegistry()->match($val);
if ($result != null) {
$name = substr($key, 0, -4);
$class = $result['class'];
if ($result['collection']) {
$this->_collection_uris[$name] = array(
'class' => $class,
'uri' => $val,
);
} else {
$this->_member_uris[$name] = array(
'class' => $class,
'uri' => $val,
);
}
continue;
}
} elseif (is_object($val) && property_exists($val, 'uri')) {
// nested
$result = self::getRegistry()->match($val->uri);
if ($result != null) {
$class = $result['class'];
if ($result['collection']) {
$this->$key = new Collection($class, $val['uri'], $val);
} else {
$this->$key = new $class($val);
}
continue;
}
} elseif (is_array($val) && array_key_exists('uri', $val)) {
$result = self::getRegistry()->match($val['uri']);
if ($result != null) {
$class = $result['class'];
if ($result['collection']) {
$this->$key = new Collection($class, $val['uri'], $val);
} else {
$this->$key = new $class($val);
}
continue;
}
}
// default
$this->$key = $val;
}
}
public static function query()
{
$uri_spec = self::getURISpec();
if ($uri_spec == null || $uri_spec->collection_uri == null) {
$msg = sprintf('Cannot directly query %s resources', get_called_class());
throw new \LogicException($msg);
}
return new Query(get_called_class(), $uri_spec->collection_uri);
}
public static function get($uri)
{
# id
if (strncmp($uri, '/', 1)) {
$uri_spec = self::getURISpec();
if ($uri_spec == null || $uri_spec->collection_uri == null) {
$msg = sprintf('Cannot get %s resources by id %s', $class, $uri);
throw new \LogicException($msg);
}
$uri = $uri_spec->collection_uri . '/' . $uri;
}
$response = self::getClient()->get($uri);
$class = get_called_class();
return new $class($response->body);
}
public function save()
{
// payload
$payload = array();
foreach ($this as $key => $val) {
if ($key[0] == '_' || is_object($val)) {
continue;
}
$payload[$key] = $val;
}
// update
if (array_key_exists('uri', $payload)) {
$uri = $payload['uri'];
unset($payload['uri']);
$response = self::getClient()->put($uri, $payload);
} else {
// create
$class = get_class($this);
if ($class::$_uri_spec == null || $class::$_uri_spec->collection_uri == null) {
$msg = sprintf('Cannot directly create %s resources', $class);
throw new \LogicException($msg);
}
$response = self::getClient()->post($class::$_uri_spec->collection_uri, $payload);
}
// re-objectify
foreach ($this as $key => $val) {
unset($this->$key);
}
$this->_objectify($response->body);
return $this;
}
public function delete()
{
self::getClient()->delete($this->uri);
return $this;
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace RESTful;
/**
* Settings.
*
*/
class Settings
{
const VERSION = '0.1.7';
}

View file

@ -0,0 +1,15 @@
<?php
namespace RESTful;
class SortExpression
{
public $name,
$ascending;
public function __construct($field, $ascending = true)
{
$this->field = $field;
$this->ascending = $ascending;
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace RESTful;
class URISpec
{
public $collection_uri = null,
$name,
$idNames;
public function __construct($name, $idNames, $root = null)
{
$this->name = $name;
if (!is_array($idNames)) {
$idNames = array($idNames);
}
$this->idNames = $idNames;
if ($root != null) {
if ($root == '' || substr($root, -1) == '/') {
$this->collection_uri = $root . $name;
} else {
$this->collection_uri = $root . '/' . $name;
}
}
}
public function match($uri)
{
$parts = explode('/', rtrim($uri, "/"));
// collection
if ($parts[count($parts) - 1] == $this->name) {
return array(
'collection' => true,
);
}
// non-member
if (count($parts) < count($this->idNames) + 1 ||
$parts[count($parts) - 1 - count($this->idNames)] != $this->name
) {
return null;
}
// member
$ids = array_combine(
$this->idNames,
array_slice($parts, -count($this->idNames))
);
$result = array(
'collection' => false,
'ids' => $ids,
);
return $result;
}
}

View file

@ -0,0 +1,241 @@
<?php
namespace RESTful\Test;
\RESTful\Bootstrap::init();
\Httpful\Bootstrap::init();
use RESTful\URISpec;
use RESTful\Client;
use RESTful\Registry;
use RESTful\Fields;
use RESTful\Query;
use RESTful\Page;
class Settings
{
public static $url_root = 'http://api.example.com';
public static $agent = 'example-php';
public static $version = '0.1.0';
public static $api_key = null;
}
class Resource extends \RESTful\Resource
{
public static $fields, $f;
protected static $_client, $_registry, $_uri_spec;
public static function init()
{
self::$_client = new Client('Settings');
self::$_registry = new Registry();
self::$f = self::$fields = new Fields();
}
public static function getClient()
{
$class = get_called_class();
return $class::$_client;
}
public static function getRegistry()
{
$class = get_called_class();
return $class::$_registry;
}
public static function getURISpec()
{
$class = get_called_class();
return $class::$_uri_spec;
}
}
Resource::init();
class A extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('as', 'id', '/');
self::$_registry->add(get_called_class());
}
}
A::init();
class B extends Resource
{
protected static $_uri_spec = null;
public static function init()
{
self::$_uri_spec = new URISpec('bs', 'id', '/');
self::$_registry->add(get_called_class());
}
}
B::init();
class URISpecTest extends \PHPUnit_Framework_TestCase
{
public function testNoRoot()
{
$uri_spec = new URISpec('grapes', 'seed');
$this->assertEquals($uri_spec->collection_uri, null);
$result = $uri_spec->match('/some/raisins');
$this->assertEquals($result, null);
$result = $uri_spec->match('/some/grapes');
$this->assertEquals($result, array('collection' => true));
$result = $uri_spec->match('/some/grapes/1234');
$expected = array(
'collection' => false,
'ids' => array('seed' => '1234')
);
$this->assertEquals($expected, $result);
}
public function testSingleId()
{
$uri_spec = new URISpec('tomatoes', 'stem', '/v1');
$this->assertNotEquals($uri_spec->collection_uri, null);
$result = $uri_spec->match('/some/tomatoes/that/are/green');
$this->assertEquals($result, null);
$result = $uri_spec->match('/some/tomatoes');
$this->assertEquals($result, array('collection' => true));
$result = $uri_spec->match('/some/tomatoes/4321');
$expected = array(
'collection' => false,
'ids' => array('stem' => '4321')
);
$this->assertEquals($expected, $result);
}
public function testMultipleIds()
{
$uri_spec = new URISpec('tomatoes', array('stem', 'root'), '/v1');
$this->assertNotEquals($uri_spec->collection_uri, null);
$result = $uri_spec->match('/some/tomatoes/that/are/green');
$this->assertEquals($result, null);
$result = $uri_spec->match('/some/tomatoes');
$this->assertEquals($result, array('collection' => true));
$result = $uri_spec->match('/some/tomatoes/4321/1234');
$expected = array(
'collection' => false,
'ids' => array('stem' => '4321', 'root' => '1234')
);
$this->assertEquals($expected, $result);
}
}
class QueryTest extends \PHPUnit_Framework_TestCase
{
public function testParse()
{
$uri = '/some/uri?field2=123&sort=field5%2Cdesc&limit=101&field3.field4%5Bcontains%5D=hi';
$query = new Query('Resource', $uri);
$expected = array(
'field2' => array('123'),
'field3.field4[contains]' => array('hi')
);
$this->assertEquals($query->filters, $expected);
$expected = array('field5,desc');
$this->assertEquals($query->sorts, $expected);
$this->assertEquals($query->size, 101);
}
public function testBuild()
{
$query = new Query('Resource', '/some/uri');
$query->filter(Resource::$f->name->eq('Wonka Chocs'))
->filter(Resource::$f->support_email->endswith('gmail.com'))
->filter(Resource::$f->variable_fee_percentage->gte(3.5))
->sort(Resource::$f->name->asc())
->sort(Resource::$f->variable_fee_percentage->desc())
->limit(101);
$this->assertEquals(
$query->filters,
array(
'name' => array('Wonka Chocs'),
'support_email[contains]' => array('gmail.com'),
'variable_fee_percentage[>=]'=> array(3.5)
)
);
$this->assertEquals(
$query->sorts,
array('name,asc', 'variable_fee_percentage,desc')
);
$this->assertEquals(
$query->size,
101
);
}
}
class PageTest extends \PHPUnit_Framework_TestCase
{
public function testConstruct()
{
$data = new \stdClass();
$data->first_uri = 'some/first/uri';
$data->previous_uri = 'some/previous/uri';
$data->next_uri = null;
$data->last_uri = 'some/last/uri';
$data->limit= 25;
$data->offset = 0;
$data->total = 101;
$data->items = array();
$page = new Page(
'Resource',
'/some/uri',
$data
);
$this->assertEquals($page->resource, 'Resource');
$this->assertEquals($page->total, 101);
$this->assertEquals($page->items, array());
$this->assertTrue($page->hasPrevious());
$this->assertFalse($page->hasNext());
}
}
class ResourceTest extends \PHPUnit_Framework_TestCase
{
public function testQuery()
{
$query = A::query();
$this->assertEquals(get_class($query), 'RESTful\Query');
}
public function testObjectify()
{
$a = new A(array(
'uri' => '/as/123',
'field1' => 123,
'b' => array(
'uri' => '/bs/321',
'field2' => 321
))
);
$this->assertEquals(get_class($a), 'RESTful\Test\A');
$this->assertEquals($a->field1, 123);
$this->assertEquals(get_class($a->b), 'RESTful\Test\B');
$this->assertEquals($a->b->field2, 321);
}
}

8
externals/restful/tests/phpunit.xml vendored Normal file
View file

@ -0,0 +1,8 @@
<phpunit>
<testsuite name="RESTful">
<directory>.</directory>
</testsuite>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false"/>
</logging>
</phpunit>