From 85c79f32b8773b17012d3e400d39544ded0facff Mon Sep 17 00:00:00 2001 From: Adam Wathan Date: Sat, 19 Nov 2016 20:50:31 -0500 Subject: [PATCH] 6.5 - Hooking into Charges --- app/Billing/FakePaymentGateway.php | 10 ++++++++++ tests/unit/Billing/FakePaymentGatewayTest.php | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/app/Billing/FakePaymentGateway.php b/app/Billing/FakePaymentGateway.php index 8f72e51..0e91109 100644 --- a/app/Billing/FakePaymentGateway.php +++ b/app/Billing/FakePaymentGateway.php @@ -5,6 +5,7 @@ namespace App\Billing; class FakePaymentGateway implements PaymentGateway { private $charges; + private $beforeFirstChargeCallback; public function __construct() { @@ -18,6 +19,10 @@ class FakePaymentGateway implements PaymentGateway public function charge($amount, $token) { + if ($this->beforeFirstChargeCallback !== null) { + $this->beforeFirstChargeCallback->__invoke($this); + } + if ($token !== $this->getValidTestToken()) { throw new PaymentFailedException; } @@ -28,4 +33,9 @@ class FakePaymentGateway implements PaymentGateway { return $this->charges->sum(); } + + public function beforeFirstCharge($callback) + { + $this->beforeFirstChargeCallback = $callback; + } } diff --git a/tests/unit/Billing/FakePaymentGatewayTest.php b/tests/unit/Billing/FakePaymentGatewayTest.php index 0e5e439..192fe6f 100644 --- a/tests/unit/Billing/FakePaymentGatewayTest.php +++ b/tests/unit/Billing/FakePaymentGatewayTest.php @@ -30,4 +30,20 @@ class FakePaymentGatewayTest extends TestCase $this->fail(); } + + /** @test */ + function running_a_hook_before_the_first_charge() + { + $paymentGateway = new FakePaymentGateway; + $callbackRan = false; + + $paymentGateway->beforeFirstCharge(function ($paymentGateway) use (&$callbackRan) { + $callbackRan = true; + $this->assertEquals(0, $paymentGateway->totalCharges()); + }); + + $paymentGateway->charge(2500, $paymentGateway->getValidTestToken()); + $this->assertTrue($callbackRan); + $this->assertEquals(2500, $paymentGateway->totalCharges()); + } }