83 - Promoting Charges to Objects

This commit is contained in:
Adam Wathan
2017-03-17 12:19:35 -04:00
parent 442cc3f240
commit 6e983c593c
4 changed files with 50 additions and 8 deletions

23
app/Billing/Charge.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
namespace App\Billing;
class Charge
{
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function amount()
{
return $this->data['amount'];
}
public function cardLastFour()
{
return $this->data['card_last_four'];
}
}

View File

@@ -5,16 +5,20 @@ namespace App\Billing;
class FakePaymentGateway implements PaymentGateway
{
private $charges;
private $tokens;
private $beforeFirstChargeCallback;
public function __construct()
{
$this->charges = collect();
$this->tokens = collect();
}
public function getValidTestToken()
public function getValidTestToken($cardNumber = '4242424242424242')
{
return "valid-token";
$token = 'fake-tok_'.str_random(24);
$this->tokens[$token] = $cardNumber;
return $token;
}
public function charge($amount, $token)
@@ -25,10 +29,14 @@ class FakePaymentGateway implements PaymentGateway
$callback($this);
}
if ($token !== $this->getValidTestToken()) {
if (! $this->tokens->has($token)) {
throw new PaymentFailedException;
}
$this->charges[] = $amount;
return $this->charges[] = new Charge([
'amount' => $amount,
'card_last_four' => substr($this->tokens[$token], -4),
]);
}
public function newChargesDuring($callback)
@@ -40,7 +48,7 @@ class FakePaymentGateway implements PaymentGateway
public function totalCharges()
{
return $this->charges->sum();
return $this->charges->map->amount()->sum();
}
public function beforeFirstCharge($callback)

View File

@@ -15,7 +15,7 @@ class CreateOrdersTable extends Migration
{
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->string('confirmation_number')->nullable();
$table->string('confirmation_number');
$table->integer('amount');
$table->string('email');
$table->string('card_last_four')->nullable();

View File

@@ -16,7 +16,18 @@ trait PaymentGatewayContractTests
});
$this->assertCount(1, $newCharges);
$this->assertEquals(2500, $newCharges->sum());
$this->assertEquals(2500, $newCharges->map->amount()->sum());
}
/** @test */
function can_get_details_about_a_successful_charge()
{
$paymentGateway = $this->getPaymentGateway();
$charge = $paymentGateway->charge(2500, $paymentGateway->getValidTestToken('0000000000004242'));
$this->assertEquals('4242', $charge->cardLastFour());
$this->assertEquals(2500, $charge->amount());
}
/** @test */
@@ -50,6 +61,6 @@ trait PaymentGatewayContractTests
});
$this->assertCount(2, $newCharges);
$this->assertEquals([5000, 4000], $newCharges->all());
$this->assertEquals([5000, 4000], $newCharges->map->amount()->all());
}
}