add api client to main repository

This commit is contained in:
David Remer 2020-08-31 13:38:54 +03:00
parent 7c5638764e
commit f5bb4048cd
100 changed files with 10765 additions and 2 deletions

View file

@ -0,0 +1,220 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Authentication;
use Brain\Monkey\Expectation\Exception\ExpectationArgsRequired;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Psr\Log\LoggerInterface;
use Psr\SimpleCache\CacheInterface;
use Mockery;
use function Brain\Monkey\Functions\expect;
class PayPalBearerTest extends TestCase
{
public function testDefault()
{
$json = '{"access_token":"abc","expires_in":100, "created":' . time() . '}';
$cache = Mockery::mock(CacheInterface::class);
$cache
->expects('get')
->andReturn('{"access_token":"abc","expires_in":100, "created":100}');
$cache
->expects('set');
$host = 'https://example.com';
$key = 'key';
$secret = 'secret';
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldNotReceive('log');
$bearer = new PayPalBearer($cache, $host, $key, $secret, $logger);
expect('trailingslashit')
->with($host)
->andReturn($host . '/');
expect('wp_remote_get')
->andReturnUsing(
function ($url, $args) use ($json, $key, $secret, $host) {
if ($url !== $host . '/v1/oauth2/token?grant_type=client_credentials') {
return false;
}
if ($args['method'] !== 'POST') {
return false;
}
if ($args['headers']['Authorization'] !== 'Basic ' . base64_encode($key . ':' . $secret)) {
return false;
}
return [
'body' => $json,
];
}
);
expect('is_wp_error')
->andReturn(false);
expect('wp_remote_retrieve_response_code')
->andReturn(200);
$token = $bearer->bearer();
$this->assertEquals("abc", $token->token());
$this->assertTrue($token->isValid());
}
public function testNoTokenCached()
{
$json = '{"access_token":"abc","expires_in":100, "created":' . time() . '}';
$cache = Mockery::mock(CacheInterface::class);
$cache
->expects('get')
->andReturn('');
$cache
->expects('set');
$host = 'https://example.com';
$key = 'key';
$secret = 'secret';
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldNotReceive('log');
$bearer = new PayPalBearer($cache, $host, $key, $secret, $logger);
expect('trailingslashit')
->with($host)
->andReturn($host . '/');
expect('wp_remote_get')
->andReturnUsing(
function ($url, $args) use ($json, $key, $secret, $host) {
if ($url !== $host . '/v1/oauth2/token?grant_type=client_credentials') {
return false;
}
if ($args['method'] !== 'POST') {
return false;
}
if ($args['headers']['Authorization'] !== 'Basic ' . base64_encode($key . ':' . $secret)) {
return false;
}
return [
'body' => $json,
];
}
);
expect('is_wp_error')
->andReturn(false);
expect('wp_remote_retrieve_response_code')
->andReturn(200);
$token = $bearer->bearer();
$this->assertEquals("abc", $token->token());
$this->assertTrue($token->isValid());
}
public function testCachedTokenIsStillValid()
{
$json = '{"access_token":"abc","expires_in":100, "created":' . time() . '}';
$cache = Mockery::mock(CacheInterface::class);
$cache
->expects('get')
->andReturn($json);
$host = 'https://example.com';
$key = 'key';
$secret = 'secret';
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldNotReceive('log');
$bearer = new PayPalBearer($cache, $host, $key, $secret, $logger);
$token = $bearer->bearer();
$this->assertEquals("abc", $token->token());
$this->assertTrue($token->isValid());
}
public function testExceptionThrownOnError()
{
$json = '{"access_token":"abc","expires_in":100, "created":' . time() . '}';
$cache = Mockery::mock(CacheInterface::class);
$cache
->expects('get')
->andReturn('');
$host = 'https://example.com';
$key = 'key';
$secret = 'secret';
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('log');
$bearer = new PayPalBearer($cache, $host, $key, $secret, $logger);
expect('trailingslashit')
->with($host)
->andReturn($host . '/');
expect('wp_remote_get')
->andReturnUsing(
function ($url, $args) use ($json, $key, $secret, $host) {
if ($url !== $host . '/v1/oauth2/token?grant_type=client_credentials') {
return false;
}
if ($args['method'] !== 'POST') {
return false;
}
if ($args['headers']['Authorization'] !== 'Basic ' . base64_encode($key . ':' . $secret)) {
return false;
}
return [
'body' => $json,
];
}
);
expect('is_wp_error')
->andReturn(true);
$this->expectException(RuntimeException::class);
$bearer->bearer();
}
public function testExceptionThrownBecauseOfHttpStatusCode()
{
$json = '{"access_token":"abc","expires_in":100, "created":' . time() . '}';
$cache = Mockery::mock(CacheInterface::class);
$cache
->expects('get')
->andReturn('');
$host = 'https://example.com';
$key = 'key';
$secret = 'secret';
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('log');
$bearer = new PayPalBearer($cache, $host, $key, $secret, $logger);
expect('trailingslashit')
->with($host)
->andReturn($host . '/');
expect('wp_remote_get')
->andReturnUsing(
function ($url, $args) use ($json, $key, $secret, $host) {
if ($url !== $host . '/v1/oauth2/token?grant_type=client_credentials') {
return false;
}
if ($args['method'] !== 'POST') {
return false;
}
if ($args['headers']['Authorization'] !== 'Basic ' . base64_encode($key . ':' . $secret)) {
return false;
}
return [
'body' => $json,
];
}
);
expect('is_wp_error')
->andReturn(false);
expect('wp_remote_retrieve_response_code')
->andReturn(500);
$this->expectException(RuntimeException::class);
$bearer->bearer();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Endpoint;
use Inpsyde\PayPalCommerce\ApiClient\Entity\ApplicationContext;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Order;
use Inpsyde\PayPalCommerce\ApiClient\Entity\OrderStatus;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Payer;
use Inpsyde\PayPalCommerce\ApiClient\Entity\PaymentSource;
use Inpsyde\PayPalCommerce\ApiClient\Entity\PurchaseUnit;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class OrderTest extends TestCase
{
public function testOrder()
{
$id = 'id';
$createTime = new \DateTime();
$updateTime = new \DateTime();
$unit = Mockery::mock(PurchaseUnit::class);
$unit->expects('toArray')->andReturn([1]);
$status = Mockery::mock(OrderStatus::class);
$status->expects('name')->andReturn('CREATED');
$payer = Mockery::mock(Payer::class);
$payer
->expects('toArray')->andReturn(['payer']);
$intent = 'AUTHORIZE';
$applicationContext = Mockery::mock(ApplicationContext::class);
$applicationContext
->expects('toArray')
->andReturn(['applicationContext']);
$paymentSource = Mockery::mock(PaymentSource::class);
$paymentSource
->expects('toArray')
->andReturn(['paymentSource']);
$testee = new Order(
$id,
[$unit],
$status,
$applicationContext,
$paymentSource,
$payer,
$intent,
$createTime,
$updateTime
);
$this->assertEquals($id, $testee->id());
$this->assertEquals($createTime, $testee->createTime());
$this->assertEquals($updateTime, $testee->updateTime());
$this->assertEquals([$unit], $testee->purchaseUnits());
$this->assertEquals($payer, $testee->payer());
$this->assertEquals($intent, $testee->intent());
$this->assertEquals($status, $testee->status());
$expected = [
'id' => $id,
'intent' => $intent,
'status' => 'CREATED',
'purchase_units' => [
[1],
],
'create_time' => $createTime->format(\DateTimeInterface::ISO8601),
'update_time' => $updateTime->format(\DateTimeInterface::ISO8601),
'payer' => ['payer'],
'application_context' => ['applicationContext'],
'payment_source' => ['paymentSource']
];
$this->assertEquals($expected, $testee->toArray());
}
public function testOrderNoDatesOrPayer()
{
$id = 'id';
$unit = Mockery::mock(PurchaseUnit::class);
$unit->expects('toArray')->andReturn([1]);
$status = Mockery::mock(OrderStatus::class);
$status->expects('name')->andReturn('CREATED');
$testee = new Order(
$id,
[$unit],
$status
);
$this->assertEquals(null, $testee->createTime());
$this->assertEquals(null, $testee->updateTime());
$this->assertEquals(null, $testee->payer());
$this->assertEquals('CAPTURE', $testee->intent());
$array = $testee->toArray();
$this->assertFalse(array_key_exists('payer', $array));
$this->assertFalse(array_key_exists('create_time', $array));
$this->assertFalse(array_key_exists('update_time', $array));
}
}

View file

@ -0,0 +1,259 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Endpoint;
use Inpsyde\PayPalCommerce\ApiClient\Authentication\Bearer;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Authorization;
use Inpsyde\PayPalCommerce\ApiClient\Entity\ErrorResponseCollection;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Token;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\Factory\AuthorizationFactory;
use Inpsyde\PayPalCommerce\ApiClient\Factory\ErrorResponseCollectionFactory;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
use Psr\Log\LoggerInterface;
use function Brain\Monkey\Functions\expect;
class PaymentsEndpointTest extends TestCase
{
public function testAuthorizationDefault()
{
$host = 'https://example.com/';
$authorizationId = 'somekindofid';
$bearer = Mockery::mock(Bearer::class);
$token = Mockery::mock(Token::class);
$token
->expects('token')->andReturn('bearer');
$bearer
->expects('bearer')->andReturn($token);
$authorization = Mockery::mock(Authorization::class);
$authorizationFactory = Mockery::mock(AuthorizationFactory::class);
$authorizationFactory
->expects('fromPayPalRequest')
->andReturn($authorization);
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldNotReceive('log');
$rawResponse = ['body' => '{"is_correct":true}'];
$testee = new PaymentsEndpoint(
$host,
$bearer,
$authorizationFactory,
$logger
);
expect('wp_remote_get')->andReturnUsing(
function ($url, $args) use ($rawResponse, $host, $authorizationId) {
if ($url !== $host . 'v2/payments/authorizations/' . $authorizationId) {
return false;
}
if ($args['headers']['Authorization'] !== 'Bearer bearer') {
return false;
}
if ($args['headers']['Content-Type'] !== 'application/json') {
return false;
}
return $rawResponse;
}
);
expect('is_wp_error')->with($rawResponse)->andReturn(false);
expect('wp_remote_retrieve_response_code')->with($rawResponse)->andReturn(200);
$result = $testee->authorization($authorizationId);
$this->assertEquals($authorization, $result);
}
public function testAuthorizationWpError()
{
$host = 'https://example.com/';
$authorizationId = 'somekindofid';
$token = Mockery::mock(Token::class);
$token
->expects('token')->andReturn('bearer');
$bearer = Mockery::mock(Bearer::class);
$bearer->expects('bearer')->andReturn($token);
$authorizationFactory = Mockery::mock(AuthorizationFactory::class);
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('log');
$rawResponse = ['body' => '{"is_correct":true}'];
$testee = new PaymentsEndpoint(
$host,
$bearer,
$authorizationFactory,
$logger
);
expect('wp_remote_get')->andReturn($rawResponse);
expect('is_wp_error')->with($rawResponse)->andReturn(true);
$this->expectException(RuntimeException::class);
$testee->authorization($authorizationId);
}
public function testAuthorizationIsNot200()
{
$host = 'https://example.com/';
$authorizationId = 'somekindofid';
$token = Mockery::mock(Token::class);
$token
->expects('token')->andReturn('bearer');
$bearer = Mockery::mock(Bearer::class);
$bearer->expects('bearer')->andReturn($token);
$authorizationFactory = Mockery::mock(AuthorizationFactory::class);
$rawResponse = ['body' => '{"some_error":true}'];
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldReceive('log');
$testee = new PaymentsEndpoint(
$host,
$bearer,
$authorizationFactory,
$logger
);
expect('wp_remote_get')->andReturn($rawResponse);
expect('is_wp_error')->with($rawResponse)->andReturn(false);
expect('wp_remote_retrieve_response_code')->with($rawResponse)->andReturn(500);
$this->expectException(RuntimeException::class);
$testee->authorization($authorizationId);
}
public function testCaptureDefault()
{
$host = 'https://example.com/';
$authorizationId = 'somekindofid';
$token = Mockery::mock(Token::class);
$token
->expects('token')->andReturn('bearer');
$bearer = Mockery::mock(Bearer::class);
$bearer
->expects('bearer')->andReturn($token);
$authorization = Mockery::mock(Authorization::class);
$authorizationFactory = Mockery::mock(AuthorizationFactory::class);
$authorizationFactory
->expects('fromPayPalRequest')
->andReturn($authorization);
$logger = Mockery::mock(LoggerInterface::class);
$logger->shouldNotReceive('log');
$rawResponse = ['body' => '{"is_correct":true}'];
$testee = new PaymentsEndpoint(
$host,
$bearer,
$authorizationFactory,
$logger
);
expect('wp_remote_get')->andReturnUsing(
function ($url, $args) use ($rawResponse, $host, $authorizationId) {
if ($url !== $host . 'v2/payments/authorizations/' . $authorizationId . '/capture') {
return false;
}
if ($args['method'] !== 'POST') {
return false;
}
if ($args['headers']['Authorization'] !== 'Bearer bearer') {
return false;
}
if ($args['headers']['Content-Type'] !== 'application/json') {
return false;
}
return $rawResponse;
}
);
expect('is_wp_error')->with($rawResponse)->andReturn(false);
expect('wp_remote_retrieve_response_code')->with($rawResponse)->andReturn(201);
$result = $testee->capture($authorizationId);
$this->assertEquals($authorization, $result);
}
public function testCaptureIsWpError()
{
$host = 'https://example.com/';
$authorizationId = 'somekindofid';
$token = Mockery::mock(Token::class);
$token
->expects('token')->andReturn('bearer');
$bearer = Mockery::mock(Bearer::class);
$bearer->expects('bearer')->andReturn($token);
$authorizationFactory = Mockery::mock(AuthorizationFactory::class);
$logger = Mockery::mock(LoggerInterface::class);
$logger->expects('log');
$rawResponse = ['body' => '{"is_correct":true}'];
$testee = new PaymentsEndpoint(
$host,
$bearer,
$authorizationFactory,
$logger
);
expect('wp_remote_get')->andReturn($rawResponse);
expect('is_wp_error')->with($rawResponse)->andReturn(true);
$this->expectException(RuntimeException::class);
$testee->capture($authorizationId);
}
public function testAuthorizationIsNot201()
{
$host = 'https://example.com/';
$authorizationId = 'somekindofid';
$token = Mockery::mock(Token::class);
$token
->expects('token')->andReturn('bearer');
$bearer = Mockery::mock(Bearer::class);
$bearer->expects('bearer')->andReturn($token);
$authorizationFactory = Mockery::mock(AuthorizationFactory::class);
$rawResponse = ['body' => '{"some_error":true}'];
$logger = Mockery::mock(LoggerInterface::class);
$logger->expects('log');
$testee = new PaymentsEndpoint(
$host,
$bearer,
$authorizationFactory,
$logger
);
expect('wp_remote_get')->andReturn($rawResponse);
expect('is_wp_error')->with($rawResponse)->andReturn(false);
expect('wp_remote_retrieve_response_code')->with($rawResponse)->andReturn(500);
$this->expectException(RuntimeException::class);
$testee->capture($authorizationId);
}
}

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class AddressTest extends TestCase
{
public function test()
{
$testee = new Address(
'countryCode',
'addressLine1',
'addressLine2',
'adminArea1',
'adminArea2',
'postalCode'
);
$this->assertEquals('countryCode', $testee->countryCode());
$this->assertEquals('addressLine1', $testee->addressLine1());
$this->assertEquals('addressLine2', $testee->addressLine2());
$this->assertEquals('adminArea1', $testee->adminArea1());
$this->assertEquals('adminArea2', $testee->adminArea2());
$this->assertEquals('postalCode', $testee->postalCode());
}
public function testToArray()
{
$testee = new Address(
'countryCode',
'addressLine1',
'addressLine2',
'adminArea1',
'adminArea2',
'postalCode'
);
$expected = [
'country_code' => 'countryCode',
'address_line_1' => 'addressLine1',
'address_line_2' => 'addressLine2',
'admin_area_1' => 'adminArea1',
'admin_area_2' => 'adminArea2',
'postal_code' => 'postalCode',
];
$actual = $testee->toArray();
$this->assertEquals($expected, $actual);
}
}

View file

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class AmountBreakdownTest extends TestCase
{
public function test()
{
$itemTotal = Mockery::mock(Money::class);
$itemTotal
->expects('toArray')->andReturn(['itemTotal']);
$shipping = Mockery::mock(Money::class);
$shipping
->expects('toArray')->andReturn(['shipping']);
$taxTotal = Mockery::mock(Money::class);
$taxTotal
->expects('toArray')->andReturn(['taxTotal']);
$handling = Mockery::mock(Money::class);
$handling
->expects('toArray')->andReturn(['handling']);
$insurance = Mockery::mock(Money::class);
$insurance
->expects('toArray')->andReturn(['insurance']);
$shippingDiscount = Mockery::mock(Money::class);
$shippingDiscount
->expects('toArray')->andReturn(['shippingDiscount']);
$discount = Mockery::mock(Money::class);
$discount
->expects('toArray')->andReturn(['discount']);
$testee = new AmountBreakdown(
$itemTotal,
$shipping,
$taxTotal,
$handling,
$insurance,
$shippingDiscount,
$discount
);
$this->assertEquals($itemTotal, $testee->itemTotal());
$this->assertEquals($shipping, $testee->shipping());
$this->assertEquals($taxTotal, $testee->taxTotal());
$this->assertEquals($handling, $testee->handling());
$this->assertEquals($insurance, $testee->insurance());
$this->assertEquals($shippingDiscount, $testee->shippingDiscount());
$this->assertEquals($discount, $testee->discount());
$expected = [
'item_total' => ['itemTotal'],
'shipping' => ['shipping'],
'tax_total' => ['taxTotal'],
'handling' => ['handling'],
'insurance' => ['insurance'],
'shipping_discount' => ['shippingDiscount'],
'discount' => ['discount'],
];
$this->assertEquals($expected, $testee->toArray());
}
/**
* @dataProvider dataDropArrayKeyIfNoValueGiven
*/
public function testDropArrayKeyIfNoValueGiven($keyMissing, $methodName)
{
$itemTotal = Mockery::mock(Money::class);
$itemTotal
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['itemTotal']);
$shipping = Mockery::mock(Money::class);
$shipping
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['shipping']);
$taxTotal = Mockery::mock(Money::class);
$taxTotal
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['taxTotal']);
$handling = Mockery::mock(Money::class);
$handling
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['handling']);
$insurance = Mockery::mock(Money::class);
$insurance
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['insurance']);
$shippingDiscount = Mockery::mock(Money::class);
$shippingDiscount
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['shippingDiscount']);
$discount = Mockery::mock(Money::class);
$discount
->shouldReceive('toArray')->zeroOrMoreTimes()->andReturn(['discount']);
$items = [
'item_total' => $itemTotal,
'shipping' => $shipping,
'tax_total' => $taxTotal,
'handling' => $handling,
'insurance' => $insurance,
'shipping_discount' => $shippingDiscount,
'discount' => $discount,
];
$items[$keyMissing] = null;
$testee = new AmountBreakdown(...array_values($items));
$array = $testee->toArray();
$result = ! array_key_exists($keyMissing, $array);
$this->assertTrue($result);
$this->assertNull($testee->{$methodName}(), "$methodName should return null");
}
public function dataDropArrayKeyIfNoValueGiven() : array
{
return [
['item_total', 'itemTotal'],
['shipping', 'shipping'],
['tax_total', 'taxTotal'],
['handling', 'handling'],
['insurance', 'insurance'],
['shipping_discount', 'shippingDiscount'],
['discount', 'discount'],
];
}
}

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class AmountTest extends TestCase
{
public function test()
{
$money = Mockery::mock(Money::class);
$money->shouldReceive('currencyCode')->andReturn('currencyCode');
$money->shouldReceive('value')->andReturn(1.10);
$testee = new Amount($money);
$this->assertEquals('currencyCode', $testee->currencyCode());
$this->assertEquals(1.10, $testee->value());
}
public function testBreakdownIsNull()
{
$money = Mockery::mock(Money::class);
$money->shouldReceive('currencyCode')->andReturn('currencyCode');
$money->shouldReceive('value')->andReturn(1.10);
$testee = new Amount($money);
$this->assertNull($testee->breakdown());
$expectedArray = [
'currency_code' => 'currencyCode',
'value' => 1.10,
];
$this->assertEquals($expectedArray, $testee->toArray());
}
public function testBreakdown()
{
$money = Mockery::mock(Money::class);
$money->shouldReceive('currencyCode')->andReturn('currencyCode');
$money->shouldReceive('value')->andReturn(1.10);
$breakdown = Mockery::mock(AmountBreakdown::class);
$breakdown->shouldReceive('toArray')->andReturn([1]);
$testee = new Amount($money, $breakdown);
$this->assertEquals($breakdown, $testee->breakdown());
$expectedArray = [
'currency_code' => 'currencyCode',
'value' => 1.10,
'breakdown' => [1],
];
$this->assertEquals($expectedArray, $testee->toArray());
}
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class AuthorizationStatusTest extends TestCase
{
/**
* @dataProvider statusDataProvider
* @param $status
*/
public function testValidStatusProvided($status)
{
$authorizationStatus = new AuthorizationStatus($status);
$this->assertEquals($authorizationStatus->name(), $status);
}
public function testInvalidStatusProvided()
{
$this->expectException(RuntimeException::class);
new AuthorizationStatus('invalid');
}
public function testStatusComparision()
{
$authorizationStatus = new AuthorizationStatus('CREATED');
$this->assertTrue($authorizationStatus->is('CREATED'));
$this->assertFalse($authorizationStatus->is('NOT_CREATED'));
}
public function statusDataProvider(): array
{
return [
['INTERNAL'],
['CREATED'],
['CAPTURED'],
['DENIED'],
['EXPIRED'],
['PARTIALLY_CAPTURED'],
['VOIDED'],
['PENDING'],
];
}
}

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class AuthorizationTest extends TestCase
{
public function testIdAndStatus()
{
$authorizationStatus = \Mockery::mock(AuthorizationStatus::class);
$testee = new Authorization('foo', $authorizationStatus);
$this->assertEquals('foo', $testee->id());
$this->assertEquals($authorizationStatus, $testee->status());
}
public function testToArray()
{
$authorizationStatus = \Mockery::mock(AuthorizationStatus::class);
$authorizationStatus->expects('name')->andReturn('CAPTURED');
$testee = new Authorization('foo', $authorizationStatus);
$expected = [
'id' => 'foo',
'status' => 'CAPTURED',
];
$this->assertEquals($expected, $testee->toArray());
}
}

View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class ItemTest extends TestCase
{
public function test()
{
$unitAmount = Mockery::mock(Money::class);
$tax = Mockery::mock(Money::class);
$testee = new Item(
'name',
$unitAmount,
1,
'description',
$tax,
'sku',
'PHYSICAL_GOODS'
);
$this->assertEquals('name', $testee->name());
$this->assertEquals($unitAmount, $testee->unitAmount());
$this->assertEquals(1, $testee->quantity());
$this->assertEquals('description', $testee->description());
$this->assertEquals($tax, $testee->tax());
$this->assertEquals('sku', $testee->sku());
$this->assertEquals('PHYSICAL_GOODS', $testee->category());
}
public function testDigitalGoodsCategory()
{
$unitAmount = Mockery::mock(Money::class);
$tax = Mockery::mock(Money::class);
$testee = new Item(
'name',
$unitAmount,
1,
'description',
$tax,
'sku',
'DIGITAL_GOODS'
);
$this->assertEquals('DIGITAL_GOODS', $testee->category());
}
public function testToArray()
{
$unitAmount = Mockery::mock(Money::class);
$unitAmount
->expects('toArray')
->andReturn([1]);
$tax = Mockery::mock(Money::class);
$tax
->expects('toArray')
->andReturn([2]);
$testee = new Item(
'name',
$unitAmount,
1,
'description',
$tax,
'sku',
'PHYSICAL_GOODS'
);
$expected = [
'name' => 'name',
'unit_amount' => [1],
'quantity' => 1,
'description' => 'description',
'sku' => 'sku',
'category' => 'PHYSICAL_GOODS',
'tax' => [2],
];
$this->assertEquals($expected, $testee->toArray());
}
}

View file

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class MoneyTest extends TestCase
{
public function test()
{
$testee = new Money(1.10, 'currencyCode');
$this->assertEquals(1.10, $testee->value());
$this->assertEquals('currencyCode', $testee->currencyCode());
$expected = [
'currency_code' => 'currencyCode',
'value' => 1.10,
];
$this->assertEquals($expected, $testee->toArray());
}
}

View file

@ -0,0 +1,202 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class PayerTest extends TestCase
{
public function testPayer()
{
$birthday = new \DateTime();
$address = Mockery::mock(Address::class);
$address
->expects('toArray')
->andReturn(['address']);
$phone = Mockery::mock(PhoneWithType::class);
$phone
->expects('toArray')
->andReturn(['phone']);
$taxInfo = Mockery::mock(PayerTaxInfo::class);
$taxInfo
->expects('toArray')
->andReturn(['taxInfo']);
$payerName = Mockery::mock(PayerName::class);
$payerName
->expects('toArray')
->andReturn(['payerName']);
$email = 'email@example.com';
$payerId = 'payerId';
$payer = new Payer(
$payerName,
$email,
$payerId,
$address,
$birthday,
$phone,
$taxInfo
);
$this->assertEquals($payerName, $payer->name());
$this->assertEquals($email, $payer->emailAddress());
$this->assertEquals($payerId, $payer->payerId());
$this->assertEquals($address, $payer->address());
$this->assertEquals($birthday, $payer->birthDate());
$this->assertEquals($phone, $payer->phone());
$this->assertEquals($taxInfo, $payer->taxInfo());
$array = $payer->toArray();
$this->assertEquals($birthday->format('Y-m-d'), $array['birth_date']);
$this->assertEquals(['payerName'], $array['name']);
$this->assertEquals($email, $array['email_address']);
$this->assertEquals(['address'], $array['address']);
$this->assertEquals($payerId, $array['payer_id']);
$this->assertEquals(['phone'], $array['phone']);
$this->assertEquals(['taxInfo'], $array['tax_info']);
}
public function testPayerNoId()
{
$birthday = new \DateTime();
$address = Mockery::mock(Address::class);
$address
->expects('toArray')
->andReturn(['address']);
$phone = Mockery::mock(PhoneWithType::class);
$phone
->expects('toArray')
->andReturn(['phone']);
$taxInfo = Mockery::mock(PayerTaxInfo::class);
$taxInfo
->expects('toArray')
->andReturn(['taxInfo']);
$payerName = Mockery::mock(PayerName::class);
$payerName
->expects('toArray')
->andReturn(['payerName']);
$email = 'email@example.com';
$payerId = '';
$payer = new Payer(
$payerName,
$email,
$payerId,
$address,
$birthday,
$phone,
$taxInfo
);
$this->assertEquals($payerId, $payer->payerId());
$array = $payer->toArray();
$this->assertArrayNotHasKey('payer_id', $array);
}
public function testPayerNoPhone()
{
$birthday = new \DateTime();
$address = Mockery::mock(Address::class);
$address
->expects('toArray')
->andReturn(['address']);
$phone = null;
$taxInfo = Mockery::mock(PayerTaxInfo::class);
$taxInfo
->expects('toArray')
->andReturn(['taxInfo']);
$payerName = Mockery::mock(PayerName::class);
$payerName
->expects('toArray')
->andReturn(['payerName']);
$email = 'email@example.com';
$payerId = 'payerId';
$payer = new Payer(
$payerName,
$email,
$payerId,
$address,
$birthday,
$phone,
$taxInfo
);
$this->assertEquals($phone, $payer->phone());
$array = $payer->toArray();
$this->assertArrayNotHasKey('phone', $array);
}
public function testPayerNoTaxInfo()
{
$birthday = new \DateTime();
$address = Mockery::mock(Address::class);
$address
->expects('toArray')
->andReturn(['address']);
$phone = Mockery::mock(PhoneWithType::class);
$phone
->expects('toArray')
->andReturn(['phone']);
$taxInfo = null;
$payerName = Mockery::mock(PayerName::class);
$payerName
->expects('toArray')
->andReturn(['payerName']);
$email = 'email@example.com';
$payerId = 'payerId';
$payer = new Payer(
$payerName,
$email,
$payerId,
$address,
$birthday,
$phone,
$taxInfo
);
$this->assertEquals($taxInfo, $payer->taxInfo());
$array = $payer->toArray();
$this->assertArrayNotHasKey('tax_info', $array);
}
public function testPayerNoBirthDate()
{
$birthday = null;
$address = Mockery::mock(Address::class);
$address
->expects('toArray')
->andReturn(['address']);
$phone = Mockery::mock(PhoneWithType::class);
$phone
->expects('toArray')
->andReturn(['phone']);
$taxInfo = Mockery::mock(PayerTaxInfo::class);
$taxInfo
->expects('toArray')
->andReturn(['taxInfo']);
$payerName = Mockery::mock(PayerName::class);
$payerName
->expects('toArray')
->andReturn(['payerName']);
$email = 'email@example.com';
$payerId = 'payerId';
$payer = new Payer(
$payerName,
$email,
$payerId,
$address,
$birthday,
$phone,
$taxInfo
);
$this->assertEquals($birthday, $payer->birthDate());
$array = $payer->toArray();
$this->assertArrayNotHasKey('birth_date', $array);
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class PaymentsTest extends TestCase
{
public function testAuthorizations()
{
$authorization = \Mockery::mock(Authorization::class);
$authorizations = [$authorization];
$testee = new Payments(...$authorizations);
$this->assertEquals($authorizations, $testee->authorizations());
}
public function testToArray()
{
$authorization = \Mockery::mock(Authorization::class);
$authorization->shouldReceive('toArray')->andReturn(
[
'id' => 'foo',
'status' => 'CREATED',
]
);
$authorizations = [$authorization];
$testee = new Payments(...$authorizations);
$this->assertEquals(
[
'authorizations' => [
[
'id' => 'foo',
'status' => 'CREATED',
],
],
],
$testee->toArray()
);
}
}

View file

@ -0,0 +1,502 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class PurchaseUnitTest extends TestCase
{
public function test()
{
$amount = Mockery::mock(
Amount::class,
[
'breakdown' => null,
'toArray' => ['amount'],
]
);
$item1 = Mockery::mock(
Item::class,
[
'toArray' => ['item1'],
'category' => Item::DIGITAL_GOODS,
]
);
$item2 = Mockery::mock(
Item::class,
[
'toArray' => ['item2'],
'category' => Item::PHYSICAL_GOODS,
]
);
$shipping = Mockery::mock(Shipping::class, ['toArray' => ['shipping']]);
$testee = new PurchaseUnit(
$amount,
[$item1, $item2],
$shipping,
'referenceId',
'description',
null,
'customId',
'invoiceId',
'softDescriptor'
);
$this->assertEquals($amount, $testee->amount());
$this->assertEquals('referenceId', $testee->referenceId());
$this->assertEquals('description', $testee->description());
$this->assertNull($testee->payee());
$this->assertEquals('customId', $testee->customId());
$this->assertEquals('invoiceId', $testee->invoiceId());
$this->assertEquals('softDescriptor', $testee->softDescriptor());
$this->assertEquals($shipping, $testee->shipping());
$this->assertEquals([$item1, $item2], $testee->items());
self::assertTrue($testee->containsPhysicalGoodsItems());
$expected = [
'reference_id' => 'referenceId',
'amount' => ['amount'],
'description' => 'description',
'items' => [['item1'], ['item2']],
'shipping' => ['shipping'],
'custom_id' => 'customId',
'invoice_id' => 'invoiceId',
'soft_descriptor' => 'softDescriptor',
];
$this->assertEquals($expected, $testee->toArray());
}
/**
* @dataProvider dataForDitchTests
* @param array $items
* @param Amount $amount
* @param bool $doDitch
*/
public function testDitchMethod(array $items, Amount $amount, bool $doDitch, string $message)
{
$testee = new PurchaseUnit(
$amount,
$items
);
$array = $testee->toArray();
$resultItems = $doDitch === ! array_key_exists('items', $array);
$resultBreakdown = $doDitch === ! array_key_exists('breakdown', $array['amount']);
$this->assertTrue($resultItems, $message);
$this->assertTrue($resultBreakdown, $message);
}
public function dataForDitchTests() : array
{
$data = [
'default' => [
'message' => 'Items should not be ditched.',
'ditch' => false,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 26,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'dont_ditch_with_discount' => [
'message' => 'Items should not be ditched.',
'ditch' => false,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 23,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => 3,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'ditch_with_discount' => [
'message' => 'Items should be ditched because of discount.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 25,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => 3,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'dont_ditch_with_shipping_discount' => [
'message' => 'Items should not be ditched.',
'ditch' => false,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 23,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => 3,
'handling' => null,
'insurance' => null,
],
],
'ditch_with_handling' => [
'message' => 'Items should be ditched because of handling.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 26,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => 3,
'insurance' => null,
],
],
'dont_ditch_with_handling' => [
'message' => 'Items should not be ditched.',
'ditch' => false,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 29,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => 3,
'insurance' => null,
],
],
'ditch_with_insurance' => [
'message' => 'Items should be ditched because of insurance.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 26,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => 3,
],
],
'dont_ditch_with_insurance' => [
'message' => 'Items should not be ditched.',
'ditch' => false,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 29,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => 3,
],
],
'ditch_with_shipping_discount' => [
'message' => 'Items should be ditched because of shipping discount.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 25,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => 3,
'handling' => null,
'insurance' => null,
],
],
'dont_ditch_with_shipping' => [
'message' => 'Items should not be ditched.',
'ditch' => false,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 29,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => 3,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'ditch_because_shipping' => [
'message' => 'Items should be ditched because of shipping.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 28,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => 3,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'ditch_items_total' => [
'message' => 'Items should be ditched because the item total does not add up.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 26,
'breakdown' => [
'itemTotal' => 11,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'ditch_tax_total' => [
'message' => 'Items should be ditched because the tax total does not add up.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 26,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 5,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
'ditch_total_amount' => [
'message' => 'Items should be ditched because the total amount is way out of order.',
'ditch' => true,
'items' => [
[
'value' => 10,
'quantity' => 2,
'tax' => 3,
'category' => Item::PHYSICAL_GOODS,
],
],
'amount' => 260,
'breakdown' => [
'itemTotal' => 20,
'taxTotal' => 6,
'shipping' => null,
'discount' => null,
'shippingDiscount' => null,
'handling' => null,
'insurance' => null,
],
],
];
$values = [];
foreach ($data as $testKey => $test) {
$items = [];
foreach ($test['items'] as $key => $item) {
$unitAmount = Mockery::mock(Money::class);
$unitAmount->shouldReceive('value')->andReturn($item['value']);
$tax = Mockery::mock(Money::class);
$tax->shouldReceive('value')->andReturn($item['tax']);
$items[$key] = Mockery::mock(
Item::class,
[
'unitAmount' => $unitAmount,
'tax' => $tax,
'quantity'=> $item['quantity'],
'category' => $item['category'],
'toArray' => [],
]
);
}
$breakdown = null;
if ($test['breakdown']) {
$breakdown = Mockery::mock(AmountBreakdown::class);
foreach ($test['breakdown'] as $method => $value) {
$breakdown->shouldReceive($method)->andReturnUsing(function () use ($value) {
if (! is_numeric($value)) {
return null;
}
$money = Mockery::mock(Money::class);
$money->shouldReceive('value')->andReturn($value);
return $money;
});
}
}
$amount = Mockery::mock(Amount::class);
$amount->shouldReceive('toArray')->andReturn(['value' => [], 'breakdown' => []]);
$amount->shouldReceive('value')->andReturn($test['amount']);
$amount->shouldReceive('breakdown')->andReturn($breakdown);
$values[$testKey] = [
$items,
$amount,
$test['ditch'],
$test['message'],
];
}
return $values;
}
public function testPayee()
{
$amount = Mockery::mock(Amount::class);
$amount->shouldReceive('breakdown')->andReturnNull();
$amount->shouldReceive('toArray')->andReturn(['amount']);
$item1 = Mockery::mock(Item::class);
$item1->shouldReceive('toArray')->andReturn(['item1']);
$item2 = Mockery::mock(Item::class);
$item2->shouldReceive('toArray')->andReturn(['item2']);
$shipping = Mockery::mock(Shipping::class);
$shipping->shouldReceive('toArray')->andReturn(['shipping']);
$payee = Mockery::mock(Payee::class);
$payee->shouldReceive('toArray')->andReturn(['payee']);
$testee = new PurchaseUnit(
$amount,
[],
$shipping,
'referenceId',
'description',
$payee,
'customId',
'invoiceId',
'softDescriptor'
);
$this->assertEquals($payee, $testee->payee());
$expected = [
'reference_id' => 'referenceId',
'amount' => ['amount'],
'description' => 'description',
'items' => [],
'shipping' => ['shipping'],
'custom_id' => 'customId',
'invoice_id' => 'invoiceId',
'soft_descriptor' => 'softDescriptor',
'payee' => ['payee'],
];
$this->assertEquals($expected, $testee->toArray());
}
}

View file

@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Entity;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class TokenTest extends TestCase
{
/**
* @dataProvider dataForTestDefault
* @param \stdClass $data
*/
public function testDefault(\stdClass $data)
{
$token = new Token($data);
$this->assertEquals($data->token, $token->token());
$this->assertTrue($token->isValid());
}
public function dataForTestDefault() : array
{
return [
'default' => [
(object)[
'created' => time(),
'expires_in' => 100,
'token' => 'abc',
],
],
'created_not_needed' => [
(object)[
'expires_in' => 100,
'token' => 'abc',
],
],
];
}
public function testIsValid()
{
$data = (object) [
'created' => time() - 100,
'expires_in' => 99,
'token' => 'abc',
];
$token = new Token($data);
$this->assertFalse($token->isValid());
}
public function testFromBearerJson()
{
$data = json_encode([
'expires_in' => 100,
'access_token' => 'abc',
]);
$token = Token::fromJson($data);
$this->assertEquals('abc', $token->token());
$this->assertTrue($token->isValid());
}
public function testFromIdentityJson()
{
$data = json_encode([
'expires_in' => 100,
'client_token' => 'abc',
]);
$token = Token::fromJson($data);
$this->assertEquals('abc', $token->token());
$this->assertTrue($token->isValid());
}
public function testAsJson()
{
$data = (object) [
'created' => 100,
'expires_in' => 100,
'token' => 'abc',
];
$token = new Token($data);
$json = json_decode($token->asJson());
$this->assertEquals($data->token, $json->token);
$this->assertEquals($data->created, $json->created);
$this->assertEquals($data->expires_in, $json->expires_in);
}
/**
* @dataProvider dataForTestExceptions
* @param \stdClass $data
*/
public function testExceptions(\stdClass $data)
{
$this->expectException(RuntimeException::class);
new Token($data);
}
public function dataForTestExceptions() : array
{
return [
'created_is_not_integer' => [
(object) [
'created' => 'abc',
'expires_in' => 123,
'token' => 'abc',
],
],
'expires_in_is_not_integer' => [
(object) [
'expires_in' => 'abc',
'token' => 'abc',
],
],
'access_token_is_not_string' => [
(object) [
'expires_in' => 123,
'token' => ['abc'],
],
],
'access_token_does_not_exist' => [
(object) [
'expires_in' => 123,
],
],
'expires_in_does_not_exist' => [
(object) [
'token' => 'abc',
],
],
];
}
}

View file

@ -0,0 +1,205 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class AddressFactoryTest extends TestCase
{
public function testFromWcCustomer()
{
$testee = new AddressFactory();
$customer = Mockery::mock(\WC_Customer::class);
$customer
->expects('get_shipping_country')
->andReturn('shipping_country');
$customer
->expects('get_shipping_address_1')
->andReturn('shipping_address_1');
$customer
->expects('get_shipping_address_2')
->andReturn('shipping_address_2');
$customer
->expects('get_shipping_state')
->andReturn('shipping_state');
$customer
->expects('get_shipping_city')
->andReturn('shipping_city');
$customer
->expects('get_shipping_postcode')
->andReturn('shipping_postcode');
$result = $testee->fromWcCustomer($customer);
$this->assertEquals('shipping_country', $result->countryCode());
$this->assertEquals('shipping_address_1', $result->addressLine1());
$this->assertEquals('shipping_address_2', $result->addressLine2());
$this->assertEquals('shipping_state', $result->adminArea1());
$this->assertEquals('shipping_city', $result->adminArea2());
$this->assertEquals('shipping_postcode', $result->postalCode());
}
public function testFromWcCustomersBillingAddress()
{
$testee = new AddressFactory();
$customer = Mockery::mock(\WC_Customer::class);
$customer
->expects('get_billing_country')
->andReturn('billing_country');
$customer
->expects('get_billing_address_1')
->andReturn('billing_address_1');
$customer
->expects('get_billing_address_2')
->andReturn('billing_address_2');
$customer
->expects('get_billing_state')
->andReturn('billing_state');
$customer
->expects('get_billing_city')
->andReturn('billing_city');
$customer
->expects('get_billing_postcode')
->andReturn('billing_postcode');
$result = $testee->fromWcCustomer($customer, 'billing');
$this->assertEquals('billing_country', $result->countryCode());
$this->assertEquals('billing_address_1', $result->addressLine1());
$this->assertEquals('billing_address_2', $result->addressLine2());
$this->assertEquals('billing_state', $result->adminArea1());
$this->assertEquals('billing_city', $result->adminArea2());
$this->assertEquals('billing_postcode', $result->postalCode());
}
public function testFromWcOrder()
{
$testee = new AddressFactory();
$order = Mockery::mock(\WC_Order::class);
$order
->expects('get_shipping_country')
->andReturn('shipping_country');
$order
->expects('get_shipping_address_1')
->andReturn('shipping_address_1');
$order
->expects('get_shipping_address_2')
->andReturn('shipping_address_2');
$order
->expects('get_shipping_state')
->andReturn('shipping_state');
$order
->expects('get_shipping_city')
->andReturn('shipping_city');
$order
->expects('get_shipping_postcode')
->andReturn('shipping_postcode');
$result = $testee->fromWcOrder($order);
$this->assertEquals('shipping_country', $result->countryCode());
$this->assertEquals('shipping_address_1', $result->addressLine1());
$this->assertEquals('shipping_address_2', $result->addressLine2());
$this->assertEquals('shipping_state', $result->adminArea1());
$this->assertEquals('shipping_city', $result->adminArea2());
$this->assertEquals('shipping_postcode', $result->postalCode());
}
/**
* @dataProvider dataFromPayPalRequest
*/
public function testFromPayPalRequest($data)
{
$testee = new AddressFactory();
$result = $testee->fromPayPalRequest($data);
$expectedAddressLine1 = (isset($data->address_line_1)) ? $data->address_line_1 : '';
$expectedAddressLine2 = (isset($data->address_line_2)) ? $data->address_line_2 : '';
$expectedAdminArea1 = (isset($data->admin_area_1)) ? $data->admin_area_1 : '';
$expectedAdminArea2 = (isset($data->admin_area_2)) ? $data->admin_area_2 : '';
$expectedPostalCode = (isset($data->postal_code)) ? $data->postal_code : '';
$this->assertEquals($data->country_code, $result->countryCode());
$this->assertEquals($expectedAddressLine1, $result->addressLine1());
$this->assertEquals($expectedAddressLine2, $result->addressLine2());
$this->assertEquals($expectedAdminArea1, $result->adminArea1());
$this->assertEquals($expectedAdminArea2, $result->adminArea2());
$this->assertEquals($expectedPostalCode, $result->postalCode());
}
public function testFromPayPalRequestThrowsError()
{
$testee = new AddressFactory();
$data = (object) [
'address_line_1' => 'shipping_address_1',
'address_line_2' => 'shipping_address_2',
'admin_area_1' => 'shipping_admin_area_1',
'admin_area_2' => 'shipping_admin_area_2',
'postal_code' => 'shipping_postcode',
];
$this->expectException(RuntimeException::class);
$testee->fromPayPalRequest($data);
}
public function dataFromPayPalRequest() : array
{
return [
'default' => [
(object) [
'country_code' => 'shipping_country',
'address_line_1' => 'shipping_address_1',
'address_line_2' => 'shipping_address_2',
'admin_area_1' => 'shipping_admin_area_1',
'admin_area_2' => 'shipping_admin_area_2',
'postal_code' => 'shipping_postcode',
],
],
'no_admin_area_2' => [
(object) [
'country_code' => 'shipping_country',
'address_line_1' => 'shipping_address_1',
'address_line_2' => 'shipping_address_2',
'admin_area_1' => 'shipping_admin_area_1',
'postal_code' => 'shipping_postcode',
],
],
'no_postal_code' => [
(object) [
'country_code' => 'shipping_country',
'address_line_1' => 'shipping_address_1',
'address_line_2' => 'shipping_address_2',
'admin_area_1' => 'shipping_admin_area_1',
'admin_area_2' => 'shipping_admin_area_2',
],
],
'no_admin_area_1' => [
(object) [
'country_code' => 'shipping_country',
'address_line_1' => 'shipping_address_1',
'address_line_2' => 'shipping_address_2',
'admin_area_2' => 'shipping_admin_area_2',
'postal_code' => 'shipping_postcode',
],
],
'no_address_line_1' => [
(object) [
'country_code' => 'shipping_country',
'address_line_2' => 'shipping_address_2',
'admin_area_1' => 'shipping_admin_area_1',
'admin_area_2' => 'shipping_admin_area_2',
'postal_code' => 'shipping_postcode',
],
],
'no_address_line_2' => [
(object) [
'country_code' => 'shipping_country',
'address_line_1' => 'shipping_address_1',
'admin_area_1' => 'shipping_admin_area_1',
'admin_area_2' => 'shipping_admin_area_2',
'postal_code' => 'shipping_postcode',
],
],
];
}
}

View file

@ -0,0 +1,581 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Amount;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Item;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Money;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
use function Brain\Monkey\Functions\expect;
class AmountFactoryTest extends TestCase
{
public function testFromWcCartDefault()
{
$itemFactory = Mockery::mock(ItemFactory::class);
$testee = new AmountFactory($itemFactory);
$expectedCurrency = 'EUR';
$cart = Mockery::mock(\WC_Cart::class);
$cart
->shouldReceive('get_total')
->withAnyArgs()
->andReturn(1);
$cart
->shouldReceive('get_cart_contents_total')
->andReturn(2);
$cart
->shouldReceive('get_discount_total')
->andReturn(3);
$cart
->shouldReceive('get_shipping_total')
->andReturn(4);
$cart
->shouldReceive('get_shipping_tax')
->andReturn(5);
$cart
->shouldReceive('get_cart_contents_tax')
->andReturn(6);
$cart
->shouldReceive('get_discount_tax')
->andReturn(7);
expect('get_woocommerce_currency')->andReturn($expectedCurrency);
$result = $testee->fromWcCart($cart);
$this->assertEquals($expectedCurrency, $result->currencyCode());
$this->assertEquals((float) 1, $result->value());
$this->assertEquals((float) 10, $result->breakdown()->discount()->value());
$this->assertEquals($expectedCurrency, $result->breakdown()->discount()->currencyCode());
$this->assertEquals((float) 9, $result->breakdown()->shipping()->value());
$this->assertEquals($expectedCurrency, $result->breakdown()->shipping()->currencyCode());
$this->assertEquals((float) 5, $result->breakdown()->itemTotal()->value());
$this->assertEquals($expectedCurrency, $result->breakdown()->itemTotal()->currencyCode());
$this->assertEquals((float) 13, $result->breakdown()->taxTotal()->value());
$this->assertEquals($expectedCurrency, $result->breakdown()->taxTotal()->currencyCode());
}
public function testFromWcCartNoDiscount()
{
$itemFactory = Mockery::mock(ItemFactory::class);
$testee = new AmountFactory($itemFactory);
$expectedCurrency = 'EUR';
$expectedTotal = 1;
$cart = Mockery::mock(\WC_Cart::class);
$cart
->shouldReceive('get_total')
->withAnyArgs()
->andReturn($expectedTotal);
$cart
->shouldReceive('get_cart_contents_total')
->andReturn(2);
$cart
->shouldReceive('get_discount_total')
->andReturn(0);
$cart
->shouldReceive('get_shipping_total')
->andReturn(4);
$cart
->shouldReceive('get_shipping_tax')
->andReturn(5);
$cart
->shouldReceive('get_cart_contents_tax')
->andReturn(6);
$cart
->shouldReceive('get_discount_tax')
->andReturn(0);
expect('get_woocommerce_currency')->andReturn($expectedCurrency);
$result = $testee->fromWcCart($cart);
$this->assertNull($result->breakdown()->discount());
}
public function testFromWcOrderDefault()
{
$itemFactory = Mockery::mock(ItemFactory::class);
$order = Mockery::mock(\WC_Order::class);
$unitAmount = Mockery::mock(Money::class);
$unitAmount
->shouldReceive('value')
->andReturn(3);
$tax = Mockery::mock(Money::class);
$tax
->shouldReceive('value')
->andReturn(1);
$item = Mockery::mock(Item::class);
$item
->shouldReceive('quantity')
->andReturn(2);
$item
->shouldReceive('unitAmount')
->andReturn($unitAmount);
$item
->shouldReceive('tax')
->andReturn($tax);
$itemFactory
->expects('fromWcOrder')
->with($order)
->andReturn([$item]);
$testee = new AmountFactory($itemFactory);
$expectedCurrency = 'EUR';
$order
->shouldReceive('get_total')
->andReturn(100);
$order
->shouldReceive('get_currency')
->andReturn($expectedCurrency);
$order
->shouldReceive('get_shipping_total')
->andReturn(1);
$order
->shouldReceive('get_shipping_tax')
->andReturn(.5);
$order
->shouldReceive('get_total_discount')
->with(false)
->andReturn(3);
$result = $testee->fromWcOrder($order);
$this->assertEquals((float) 3, $result->breakdown()->discount()->value());
$this->assertEquals((float) 6, $result->breakdown()->itemTotal()->value());
$this->assertEquals((float) 1.5, $result->breakdown()->shipping()->value());
$this->assertEquals((float) 100, $result->value());
$this->assertEquals((float) 2, $result->breakdown()->taxTotal()->value());
$this->assertEquals($expectedCurrency, $result->breakdown()->discount()->currencyCode());
$this->assertEquals($expectedCurrency, $result->breakdown()->itemTotal()->currencyCode());
$this->assertEquals($expectedCurrency, $result->breakdown()->shipping()->currencyCode());
$this->assertEquals($expectedCurrency, $result->breakdown()->taxTotal()->currencyCode());
$this->assertEquals($expectedCurrency, $result->currencyCode());
}
public function testFromWcOrderDiscountIsNull()
{
$itemFactory = Mockery::mock(ItemFactory::class);
$order = Mockery::mock(\WC_Order::class);
$unitAmount = Mockery::mock(Money::class);
$unitAmount
->shouldReceive('value')
->andReturn(3);
$tax = Mockery::mock(Money::class);
$tax
->shouldReceive('value')
->andReturn(1);
$item = Mockery::mock(Item::class);
$item
->shouldReceive('quantity')
->andReturn(2);
$item
->shouldReceive('unitAmount')
->andReturn($unitAmount);
$item
->shouldReceive('tax')
->andReturn($tax);
$itemFactory
->expects('fromWcOrder')
->with($order)
->andReturn([$item]);
$testee = new AmountFactory($itemFactory);
$expectedCurrency = 'EUR';
$order
->shouldReceive('get_total')
->andReturn(100);
$order
->shouldReceive('get_currency')
->andReturn($expectedCurrency);
$order
->shouldReceive('get_shipping_total')
->andReturn(1);
$order
->shouldReceive('get_shipping_tax')
->andReturn(.5);
$order
->shouldReceive('get_total_discount')
->with(false)
->andReturn(0);
$result = $testee->fromWcOrder($order);
$this->assertNull($result->breakdown()->discount());
}
/**
* @dataProvider dataFromPayPalResponse
* @param $response
*/
public function testFromPayPalResponse($response, $expectsException)
{
$itemFactory = Mockery::mock(ItemFactory::class);
$testee = new AmountFactory($itemFactory);
if ($expectsException) {
$this->expectException(RuntimeException::class);
}
$result = $testee->fromPayPalResponse($response);
if ($expectsException) {
return;
}
$this->assertEquals($response->value, $result->value());
$this->assertEquals($response->currency_code, $result->currencyCode());
$breakdown = $result->breakdown();
if (! isset($response->breakdown)) {
$this->assertNull($breakdown);
return;
}
if ($breakdown->shipping()) {
$this->assertEquals($response->breakdown->shipping->value, $breakdown->shipping()->value());
$this->assertEquals($response->breakdown->shipping->currency_code, $breakdown->shipping()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->shipping));
}
if ($breakdown->itemTotal()) {
$this->assertEquals($response->breakdown->item_total->value, $breakdown->itemTotal()->value());
$this->assertEquals($response->breakdown->item_total->currency_code, $breakdown->itemTotal()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->item_total));
}
if ($breakdown->taxTotal()) {
$this->assertEquals($response->breakdown->tax_total->value, $breakdown->taxTotal()->value());
$this->assertEquals($response->breakdown->tax_total->currency_code, $breakdown->taxTotal()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->tax_total));
}
if ($breakdown->handling()) {
$this->assertEquals($response->breakdown->handling->value, $breakdown->handling()->value());
$this->assertEquals($response->breakdown->handling->currency_code, $breakdown->handling()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->handling));
}
if ($breakdown->insurance()) {
$this->assertEquals($response->breakdown->insurance->value, $breakdown->insurance()->value());
$this->assertEquals($response->breakdown->insurance->currency_code, $breakdown->insurance()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->insurance));
}
if ($breakdown->shippingDiscount()) {
$this->assertEquals($response->breakdown->shipping_discount->value, $breakdown->shippingDiscount()->value());
$this->assertEquals($response->breakdown->shipping_discount->currency_code, $breakdown->shippingDiscount()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->shipping_discount));
}
if ($breakdown->discount()) {
$this->assertEquals($response->breakdown->discount->value, $breakdown->discount()->value());
$this->assertEquals($response->breakdown->discount->currency_code, $breakdown->discount()->currencyCode());
} else {
$this->assertTrue(! isset($response->breakdown->discount));
}
}
public function dataFromPayPalResponse() : array
{
return [
'no_value' => [
(object) [
"currency_code" => "A",
],
true,
],
'no_currency_code' => [
(object) [
"value" => (float) 1,
],
true,
],
'no_value_in_breakdown' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"currency_code" => "B",
],
],
],
true,
],
'no_currency_code_in_breakdown' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
],
],
],
true,
],
'default' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
'no_item_total' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
],
],
false,
],
'no_tax_total' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
'no_handling' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
'no_insurance' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
'no_shipping_discount' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
'no_discount' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"shipping" => (object) [
"value" => (float) 7,
"currency_code" => "G",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
'no_shipping' => [
(object) [
"value" => (float) 1,
"currency_code" => "A",
"breakdown" => (object) [
"discount" => (object) [
"value" => (float) 2,
"currency_code" => "B",
],
"shipping_discount" => (object) [
"value" => (float) 3,
"currency_code" => "C",
],
"insurance" => (object) [
"value" => (float) 4,
"currency_code" => "D",
],
"handling" => (object) [
"value" => (float) 5,
"currency_code" => "E",
],
"tax_total" => (object) [
"value" => (float) 6,
"currency_code" => "F",
],
"item_total" => (object) [
"value" => (float) 8,
"currency_code" => "H",
],
],
],
false,
],
];
}
}

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Authorization;
use Inpsyde\PayPalCommerce\ApiClient\Entity\AuthorizationStatus;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
class AuthorizationFactoryTest extends TestCase
{
public function testFromPayPalRequestDefault()
{
$response = (object)[
'id' => 'foo',
'status' => 'CAPTURED',
];
$testee = new AuthorizationFactory();
$result = $testee->fromPayPalRequest($response);
$this->assertInstanceOf(Authorization::class, $result);
$this->assertEquals('foo', $result->id());
$this->assertInstanceOf(AuthorizationStatus::class, $result->status());
$this->assertEquals('CAPTURED', $result->status()->name());
}
public function testReturnExceptionIdIsMissing()
{
$this->expectException(RuntimeException::class);
$response = (object)[
'status' => 'CAPTURED',
];
$testee = new AuthorizationFactory();
$testee->fromPayPalRequest($response);
}
public function testReturnExceptionStatusIsMissing()
{
$this->expectException(RuntimeException::class);
$response = (object)[
'id' => 'foo',
];
$testee = new AuthorizationFactory();
$testee->fromPayPalRequest($response);
}
}

View file

@ -0,0 +1,420 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Item;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use function Brain\Monkey\Functions\expect;
use Mockery;
class ItemFactoryTest extends TestCase
{
public function testFromCartDefault()
{
$testee = new ItemFactory();
$product = Mockery::mock(\WC_Product_Simple::class);
$product
->expects('get_name')
->andReturn('name');
$product
->expects('get_description')
->andReturn('description');
$product
->expects('get_sku')
->andReturn('sku');
$product
->expects('is_virtual')
->andReturn(false);
$items = [
[
'data' => $product,
'quantity' => 1,
],
];
$cart = Mockery::mock(\WC_Cart::class);
$cart
->expects('get_cart_contents')
->andReturn($items);
expect('get_woocommerce_currency')
->andReturn('EUR');
expect('wc_get_price_including_tax')
->with($product)
->andReturn(2.995);
expect('wc_get_price_excluding_tax')
->with($product)
->andReturn(1);
$result = $testee->fromWcCart($cart);
$this->assertCount(1, $result);
$item = current($result);
$this->assertInstanceOf(Item::class, $item);
/**
* @var Item $item
*/
$this->assertEquals(Item::PHYSICAL_GOODS, $item->category());
$this->assertEquals('description', $item->description());
$this->assertEquals(1, $item->quantity());
$this->assertEquals('name', $item->name());
$this->assertEquals('sku', $item->sku());
$this->assertEquals(1, $item->unitAmount()->value());
$this->assertEquals(2, $item->tax()->value());
}
public function testFromCartDigitalGood()
{
$testee = new ItemFactory();
$product = Mockery::mock(\WC_Product_Simple::class);
$product
->expects('get_name')
->andReturn('name');
$product
->expects('get_description')
->andReturn('description');
$product
->expects('get_sku')
->andReturn('sku');
$product
->expects('is_virtual')
->andReturn(true);
$items = [
[
'data' => $product,
'quantity' => 1,
],
];
$cart = Mockery::mock(\WC_Cart::class);
$cart
->expects('get_cart_contents')
->andReturn($items);
expect('get_woocommerce_currency')
->andReturn('EUR');
expect('wc_get_price_including_tax')
->with($product)
->andReturn(2.995);
expect('wc_get_price_excluding_tax')
->with($product)
->andReturn(1);
$result = $testee->fromWcCart($cart);
$item = current($result);
$this->assertEquals(Item::DIGITAL_GOODS, $item->category());
}
public function testFromWcOrderDefault()
{
$testee = new ItemFactory();
$product = Mockery::mock(\WC_Product::class);
$product
->expects('get_name')
->andReturn('name');
$product
->expects('get_description')
->andReturn('description');
$product
->expects('get_sku')
->andReturn('sku');
$product
->expects('is_virtual')
->andReturn(false);
$item = Mockery::mock(\WC_Order_Item_Product::class);
$item
->expects('get_product')
->andReturn($product);
$item
->expects('get_quantity')
->andReturn(1);
$order = Mockery::mock(\WC_Order::class);
$order
->expects('get_currency')
->andReturn('EUR');
$order
->expects('get_items')
->andReturn([$item]);
$order
->expects('get_item_subtotal')
->with($item, true)
->andReturn(3);
$order
->expects('get_item_subtotal')
->with($item, false)
->andReturn(1);
$result = $testee->fromWcOrder($order);
$this->assertCount(1, $result);
$item = current($result);
/**
* @var Item $item
*/
$this->assertInstanceOf(Item::class, $item);
$this->assertEquals('name', $item->name());
$this->assertEquals('description', $item->description());
$this->assertEquals(1, $item->quantity());
$this->assertEquals(Item::PHYSICAL_GOODS, $item->category());
$this->assertEquals(1, $item->unitAmount()->value());
$this->assertEquals(2, $item->tax()->value());
}
public function testFromWcOrderDigitalGood()
{
$testee = new ItemFactory();
$product = Mockery::mock(\WC_Product::class);
$product
->expects('get_name')
->andReturn('name');
$product
->expects('get_description')
->andReturn('description');
$product
->expects('get_sku')
->andReturn('sku');
$product
->expects('is_virtual')
->andReturn(true);
$item = Mockery::mock(\WC_Order_Item_Product::class);
$item
->expects('get_product')
->andReturn($product);
$item
->expects('get_quantity')
->andReturn(1);
$order = Mockery::mock(\WC_Order::class);
$order
->expects('get_currency')
->andReturn('EUR');
$order
->expects('get_items')
->andReturn([$item]);
$order
->expects('get_item_subtotal')
->with($item, true)
->andReturn(3);
$order
->expects('get_item_subtotal')
->with($item, false)
->andReturn(1);
$result = $testee->fromWcOrder($order);
$item = current($result);
/**
* @var Item $item
*/
$this->assertEquals(Item::DIGITAL_GOODS, $item->category());
}
public function testFromWcOrderMaxStringLength()
{
$name = 'öawjetöagrjjaglörjötairgjaflkögjöalfdgjöalfdjblköajtlkfjdbljslkgjfklösdgjalkerjtlrajglkfdajblköajflköbjsdgjadfgjaöfgjaölkgjkladjgfköajgjaflgöjafdlgjafdögjdsflkgjö4jwegjfsdbvxj öskögjtaeröjtrgt';
$description = 'öawjetöagrjjaglörjötairgjaflkögjöalfdgjöalfdjblköajtlkfjdbljslkgjfklösdgjalkerjtlrajglkfdajblköajflköbjsdgjadfgjaöfgjaölkgjkladjgfköajgjaflgöjafdlgjafdögjdsflkgjö4jwegjfsdbvxj öskögjtaeröjtrgt';
$testee = new ItemFactory();
$product = Mockery::mock(\WC_Product::class);
$product
->expects('get_name')
->andReturn($name);
$product
->expects('get_description')
->andReturn($description);
$product
->expects('get_sku')
->andReturn('sku');
$product
->expects('is_virtual')
->andReturn(true);
$item = Mockery::mock(\WC_Order_Item_Product::class);
$item
->expects('get_product')
->andReturn($product);
$item
->expects('get_quantity')
->andReturn(1);
$order = Mockery::mock(\WC_Order::class);
$order
->expects('get_currency')
->andReturn('EUR');
$order
->expects('get_items')
->andReturn([$item]);
$order
->expects('get_item_subtotal')
->with($item, true)
->andReturn(3);
$order
->expects('get_item_subtotal')
->with($item, false)
->andReturn(1);
$result = $testee->fromWcOrder($order);
$item = current($result);
/**
* @var Item $item
*/
$this->assertEquals(mb_substr($name, 0, 127), $item->name());
$this->assertEquals(mb_substr($description, 0, 127), $item->description());
}
public function testFromPayPalResponse()
{
$testee = new ItemFactory();
$response = (object) [
'name' => 'name',
'description' => 'description',
'quantity' => 1,
'unit_amount' => (object) [
'value' => 1,
'currency_code' => 'EUR',
],
];
$item = $testee->fromPayPalResponse($response);
$this->assertInstanceOf(Item::class, $item);
/**
* @var Item $item
*/
$this->assertInstanceOf(Item::class, $item);
$this->assertEquals('name', $item->name());
$this->assertEquals('description', $item->description());
$this->assertEquals(1, $item->quantity());
$this->assertEquals(Item::PHYSICAL_GOODS, $item->category());
$this->assertEquals(1, $item->unitAmount()->value());
$this->assertNull($item->tax());
}
public function testFromPayPalResponseDigitalGood()
{
$testee = new ItemFactory();
$response = (object) [
'name' => 'name',
'description' => 'description',
'quantity' => 1,
'unit_amount' => (object) [
'value' => 1,
'currency_code' => 'EUR',
],
'category' => Item::DIGITAL_GOODS,
];
$item = $testee->fromPayPalResponse($response);
/**
* @var Item $item
*/
$this->assertEquals(Item::DIGITAL_GOODS, $item->category());
}
public function testFromPayPalResponseHasTax()
{
$testee = new ItemFactory();
$response = (object) [
'name' => 'name',
'description' => 'description',
'quantity' => 1,
'unit_amount' => (object) [
'value' => 1,
'currency_code' => 'EUR',
],
'tax' => (object) [
'value' => 100,
'currency_code' => 'EUR',
],
];
$item = $testee->fromPayPalResponse($response);
$this->assertEquals(100, $item->tax()->value());
}
public function testFromPayPalResponseThrowsWithoutName()
{
$testee = new ItemFactory();
$response = (object) [
'description' => 'description',
'quantity' => 1,
'unit_amount' => (object) [
'value' => 1,
'currency_code' => 'EUR',
],
'tax' => (object) [
'value' => 100,
'currency_code' => 'EUR',
],
];
$this->expectException(RuntimeException::class);
$testee->fromPayPalResponse($response);
}
public function testFromPayPalResponseThrowsWithoutQuantity()
{
$testee = new ItemFactory();
$response = (object) [
'name' => 'name',
'description' => 'description',
'unit_amount' => (object) [
'value' => 1,
'currency_code' => 'EUR',
],
'tax' => (object) [
'value' => 100,
'currency_code' => 'EUR',
],
];
$this->expectException(RuntimeException::class);
$testee->fromPayPalResponse($response);
}
public function testFromPayPalResponseThrowsWithStringInQuantity()
{
$testee = new ItemFactory();
$response = (object) [
'name' => 'name',
'description' => 'description',
'quantity' => 'should-not-be-a-string',
'unit_amount' => (object) [
'value' => 1,
'currency_code' => 'EUR',
],
'tax' => (object) [
'value' => 100,
'currency_code' => 'EUR',
],
];
$this->expectException(RuntimeException::class);
$testee->fromPayPalResponse($response);
}
public function testFromPayPalResponseThrowsWithWrongUnitAmount()
{
$testee = new ItemFactory();
$response = (object) [
'name' => 'name',
'description' => 'description',
'quantity' => 1,
'unit_amount' => (object) [
],
'tax' => (object) [
'value' => 100,
'currency_code' => 'EUR',
],
];
$this->expectException(RuntimeException::class);
$testee->fromPayPalResponse($response);
}
}

View file

@ -0,0 +1,221 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Order;
use Inpsyde\PayPalCommerce\ApiClient\Entity\OrderStatus;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Payer;
use Inpsyde\PayPalCommerce\ApiClient\Entity\PaymentSource;
use Inpsyde\PayPalCommerce\ApiClient\Entity\PurchaseUnit;
use Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException;
use Inpsyde\PayPalCommerce\ApiClient\Repository\ApplicationContextRepository;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class OrderFactoryTest extends TestCase
{
public function testFromWcOrder()
{
$createTime = new \DateTime();
$updateTime = new \DateTime();
$payer = Mockery::mock(Payer::class);
$status = Mockery::mock(OrderStatus::class);
$order = Mockery::mock(Order::class);
$order->expects('id')->andReturn('id');
$order->expects('status')->andReturn($status);
$order->expects('payer')->andReturn($payer);
$order->expects('intent')->andReturn('intent');
$order->expects('createTime')->andReturn($createTime);
$order->expects('updateTime')->andReturn($updateTime);
$order->expects('applicationContext')->andReturnNull();
$order->expects('paymentSource')->andReturnNull();
$wcOrder = Mockery::mock(\WC_Order::class);
$purchaseUnitFactory = Mockery::mock(PurchaseUnitFactory::class);
$purchaseUnit = Mockery::mock(PurchaseUnit::class);
$purchaseUnitFactory->expects('fromWcOrder')->with($wcOrder)->andReturn($purchaseUnit);
$payerFactory = Mockery::mock(PayerFactory::class);
$applicationRepository = Mockery::mock(ApplicationContextRepository::class);
$applicationFactory = Mockery::mock(ApplicationContextFactory::class);
$paymentSourceFactory = Mockery::mock(PaymentSourceFactory::class);
$testee = new OrderFactory(
$purchaseUnitFactory,
$payerFactory,
$applicationRepository,
$applicationFactory,
$paymentSourceFactory
);
$result = $testee->fromWcOrder($wcOrder, $order);
$resultPurchaseUnit = current($result->purchaseUnits());
$this->assertEquals($purchaseUnit, $resultPurchaseUnit);
}
/**
* @dataProvider dataForTestFromPayPalResponseTest
* @param $orderData
*/
public function testFromPayPalResponse($orderData)
{
$purchaseUnitFactory = Mockery::mock(PurchaseUnitFactory::class);
if (count($orderData->purchase_units)) {
$purchaseUnitFactory
->expects('fromPayPalResponse')
->times(count($orderData->purchase_units))
->andReturn(Mockery::mock(PurchaseUnit::class));
}
$payerFactory = Mockery::mock(PayerFactory::class);
if (isset($orderData->payer)) {
$payerFactory
->expects('fromPayPalResponse')
->andReturn(Mockery::mock(Payer::class));
}
$applicationRepository = Mockery::mock(ApplicationContextRepository::class);
$applicationFactory = Mockery::mock(ApplicationContextFactory::class);
$paymentSourceFactory = Mockery::mock(PaymentSourceFactory::class);
$testee = new OrderFactory(
$purchaseUnitFactory,
$payerFactory,
$applicationRepository,
$applicationFactory,
$paymentSourceFactory
);
$order = $testee->fromPayPalResponse($orderData);
$this->assertCount(count($orderData->purchase_units), $order->purchaseUnits());
$this->assertEquals($orderData->id, $order->id());
$this->assertEquals($orderData->status, $order->status()->name());
$this->assertEquals($orderData->intent, $order->intent());
if (! isset($orderData->create_time)) {
$this->assertNull($order->createTime());
} else {
$this->assertEquals($orderData->create_time, $order->createTime()->format(\DateTime::ISO8601));
}
if (! isset($orderData->payer)) {
$this->assertNull($order->payer());
} else {
$this->assertInstanceOf(Payer::class, $order->payer());
}
if (! isset($orderData->update_time)) {
$this->assertNull($order->updateTime());
} else {
$this->assertEquals($orderData->update_time, $order->updateTime()->format(\DateTime::ISO8601));
}
}
public function dataForTestFromPayPalResponseTest() : array
{
return [
'default' => [
(object) [
'id' => 'id',
'purchase_units' => [new \stdClass(), new \stdClass()],
'status' => OrderStatus::APPROVED,
'intent' => 'CAPTURE',
'create_time' => '2005-08-15T15:52:01+0000',
'update_time' => '2005-09-15T15:52:01+0000',
'payer' => new \stdClass(),
],
],
'no_update_time' => [
(object) [
'id' => 'id',
'purchase_units' => [new \stdClass(), new \stdClass()],
'status' => OrderStatus::APPROVED,
'intent' => 'CAPTURE',
'create_time' => '2005-08-15T15:52:01+0000',
'payer' => new \stdClass(),
],
],
'no_create_time' => [
(object) [
'id' => 'id',
'purchase_units' => [new \stdClass(), new \stdClass()],
'status' => OrderStatus::APPROVED,
'intent' => 'CAPTURE',
'update_time' => '2005-09-15T15:52:01+0000',
'payer' => new \stdClass(),
],
],
'no_payer' => [
(object) [
'id' => 'id',
'purchase_units' => [new \stdClass(), new \stdClass()],
'status' => OrderStatus::APPROVED,
'intent' => 'CAPTURE',
'create_time' => '2005-08-15T15:52:01+0000',
'update_time' => '2005-09-15T15:52:01+0000',
],
],
];
}
/**
* @dataProvider dataForTestFromPayPalResponseExceptionsTest
* @param $orderData
*/
public function testFromPayPalResponseExceptions($orderData)
{
$purchaseUnitFactory = Mockery::mock(PurchaseUnitFactory::class);
$payerFactory = Mockery::mock(PayerFactory::class);
$applicationRepository = Mockery::mock(ApplicationContextRepository::class);
$applicationFactory = Mockery::mock(ApplicationContextFactory::class);
$paymentSourceFactory = Mockery::mock(PaymentSourceFactory::class);
$testee = new OrderFactory(
$purchaseUnitFactory,
$payerFactory,
$applicationRepository,
$applicationFactory,
$paymentSourceFactory
);
$this->expectException(RuntimeException::class);
$testee->fromPayPalResponse($orderData);
}
public function dataForTestFromPayPalResponseExceptionsTest() : array
{
return [
'no_id' => [
(object) [
'purchase_units' => [],
'status' => '',
'intent' => '',
],
],
'no_purchase_units' => [
(object) [
'id' => '',
'status' => '',
'intent' => '',
],
],
'purchase_units_is_not_array' => [
(object) [
'id' => '',
'purchase_units' => 1,
'status' => '',
'intent' => '',
],
],
'no_status' => [
(object) [
'id' => '',
'purchase_units' => [],
'intent' => '',
],
],
'no_intent' => [
(object) [
'id' => '',
'purchase_units' => [],
'status' => '',
],
],
];
}
}

View file

@ -0,0 +1,269 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Address;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class PayerFactoryTest extends TestCase
{
public function testFromWcCustomer()
{
$expectedPhone = '012345678901';
$expectedEmail = 'test@example.com';
$expectedFirstName = 'John';
$expectedLastName = 'Locke';
$address = Mockery::mock(Address::class);
$customer = Mockery::mock(\WC_Customer::class);
$customer
->shouldReceive('get_billing_phone')
->andReturn($expectedPhone);
$customer
->shouldReceive('get_billing_email')
->andReturn($expectedEmail);
$customer
->shouldReceive('get_billing_last_name')
->andReturn($expectedLastName);
$customer
->shouldReceive('get_billing_first_name')
->andReturn($expectedFirstName);
$addressFactory = Mockery::mock(AddressFactory::class);
$addressFactory
->expects('fromWcCustomer')
->with($customer, 'billing')
->andReturn($address);
$testee = new PayerFactory($addressFactory);
$result = $testee->fromCustomer($customer);
$this->assertEquals($expectedEmail, $result->emailAddress());
$this->assertEquals($expectedLastName, $result->name()->surname());
$this->assertEquals($expectedFirstName, $result->name()->givenName());
$this->assertEquals($address, $result->address());
$this->assertEquals($expectedPhone, $result->phone()->phone()->nationalNumber());
$this->assertNull($result->birthDate());
$this->assertEmpty($result->payerId());
}
/**
* The phone number is only allowed to contain numbers.
* The WC_Customer get_billing_phone can contain other characters, which need to
* get stripped.
*/
public function testFromWcCustomerStringsFromNumberAreRemoved()
{
$expectedPhone = '012345678901';
$expectedEmail = 'test@example.com';
$expectedFirstName = 'John';
$expectedLastName = 'Locke';
$address = Mockery::mock(Address::class);
$customer = Mockery::mock(\WC_Customer::class);
$customer
->shouldReceive('get_billing_phone')
->andReturn($expectedPhone . 'abcdefg');
$customer
->shouldReceive('get_billing_email')
->andReturn($expectedEmail);
$customer
->shouldReceive('get_billing_last_name')
->andReturn($expectedLastName);
$customer
->shouldReceive('get_billing_first_name')
->andReturn($expectedFirstName);
$addressFactory = Mockery::mock(AddressFactory::class);
$addressFactory
->expects('fromWcCustomer')
->with($customer, 'billing')
->andReturn($address);
$testee = new PayerFactory($addressFactory);
$result = $testee->fromCustomer($customer);
$this->assertEquals($expectedPhone, $result->phone()->phone()->nationalNumber());
}
public function testFromWcCustomerNoNumber()
{
$expectedEmail = 'test@example.com';
$expectedFirstName = 'John';
$expectedLastName = 'Locke';
$address = Mockery::mock(Address::class);
$customer = Mockery::mock(\WC_Customer::class);
$customer
->shouldReceive('get_billing_phone')
->andReturn('');
$customer
->shouldReceive('get_billing_email')
->andReturn($expectedEmail);
$customer
->shouldReceive('get_billing_last_name')
->andReturn($expectedLastName);
$customer
->shouldReceive('get_billing_first_name')
->andReturn($expectedFirstName);
$addressFactory = Mockery::mock(AddressFactory::class);
$addressFactory
->expects('fromWcCustomer')
->with($customer, 'billing')
->andReturn($address);
$testee = new PayerFactory($addressFactory);
$result = $testee->fromCustomer($customer);
$this->assertNull($result->phone());
}
/**
* The phone number is not allowed to be longer than 14 characters.
* We need to make sure, we strip the number if longer.
*/
public function testFromWcCustomerTooLongNumberGetsStripped()
{
$expectedPhone = '01234567890123';
$expectedEmail = 'test@example.com';
$expectedFirstName = 'John';
$expectedLastName = 'Locke';
$address = Mockery::mock(Address::class);
$customer = Mockery::mock(\WC_Customer::class);
$customer
->shouldReceive('get_billing_phone')
->andReturn($expectedPhone . '456789');
$customer
->shouldReceive('get_billing_email')
->andReturn($expectedEmail);
$customer
->shouldReceive('get_billing_last_name')
->andReturn($expectedLastName);
$customer
->shouldReceive('get_billing_first_name')
->andReturn($expectedFirstName);
$addressFactory = Mockery::mock(AddressFactory::class);
$addressFactory
->expects('fromWcCustomer')
->with($customer, 'billing')
->andReturn($address);
$testee = new PayerFactory($addressFactory);
$result = $testee->fromCustomer($customer);
$this->assertEquals($expectedPhone, $result->phone()->phone()->nationalNumber());
}
/**
* @dataProvider dataForTestFromPayPalResponse
*/
public function testFromPayPalResponse($data)
{
$addressFactory = Mockery::mock(AddressFactory::class);
$addressFactory
->expects('fromPayPalRequest')
->with($data->address)
->andReturn(Mockery::mock(Address::class));
$testee = new PayerFactory($addressFactory);
$payer = $testee->fromPayPalResponse($data);
$this->assertEquals($data->email_address, $payer->emailAddress());
$this->assertEquals($data->payer_id, $payer->payerId());
$this->assertEquals($data->name->given_name, $payer->name()->givenName());
$this->assertEquals($data->name->surname, $payer->name()->surname());
if (isset($data->phone)) {
$this->assertEquals($data->phone->phone_type, $payer->phone()->type());
$this->assertEquals($data->phone->phone_number->national_number, $payer->phone()->phone()->nationalNumber());
} else {
$this->assertNull($payer->phone());
}
$this->assertInstanceOf(Address::class, $payer->address());
if (isset($data->tax_info)) {
$this->assertEquals($data->tax_info->tax_id, $payer->taxInfo()->taxId());
$this->assertEquals($data->tax_info->tax_id_type, $payer->taxInfo()->type());
} else {
$this->assertNull($payer->taxInfo());
}
if (isset($data->birth_date)) {
$this->assertEquals($data->birth_date, $payer->birthDate()->format('Y-m-d'));
} else {
$this->assertNull($payer->birthDate());
}
}
public function dataForTestFromPayPalResponse() : array
{
return [
'default' => [
(object)[
'address' => new \stdClass(),
'name' => (object)[
'given_name' => 'given_name',
'surname' => 'surname',
],
'phone' => (object)[
'phone_type' => 'HOME',
'phone_number' => (object)[
'national_number' => '1234567890',
],
],
'tax_info' => (object)[
'tax_id' => 'tax_id',
'tax_id_type' => 'BR_CPF',
],
'birth_date' => '1970-01-01',
'email_address' => 'email_address',
'payer_id' => 'payer_id',
],
],
'no_phone' => [
(object)[
'address' => new \stdClass(),
'name' => (object)[
'given_name' => 'given_name',
'surname' => 'surname',
],
'tax_info' => (object)[
'tax_id' => 'tax_id',
'tax_id_type' => 'BR_CPF',
],
'birth_date' => '1970-01-01',
'email_address' => 'email_address',
'payer_id' => 'payer_id',
],
],
'no_tax_info' => [
(object)[
'address' => new \stdClass(),
'name' => (object)[
'given_name' => 'given_name',
'surname' => 'surname',
],
'phone' => (object)[
'phone_type' => 'HOME',
'phone_number' => (object)[
'national_number' => '1234567890',
],
],
'birth_date' => '1970-01-01',
'email_address' => 'email_address',
'payer_id' => 'payer_id',
],
],
'no_birth_date' => [
(object)[
'address' => new \stdClass(),
'name' => (object)[
'given_name' => 'given_name',
'surname' => 'surname',
],
'phone' => (object)[
'phone_type' => 'HOME',
'phone_number' => (object)[
'national_number' => '1234567890',
],
],
'tax_info' => (object)[
'tax_id' => 'tax_id',
'tax_id_type' => 'BR_CPF',
],
'email_address' => 'email_address',
'payer_id' => 'payer_id',
],
],
];
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Authorization;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Payments;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class PaymentsFactoryTest extends TestCase
{
public function testFromPayPalResponse()
{
$authorization = Mockery::mock(Authorization::class);
$authorization->shouldReceive('toArray')->andReturn(['id' => 'foo', 'status' => 'CREATED']);
$authorizationsFactory = Mockery::mock(AuthorizationFactory::class);
$authorizationsFactory->shouldReceive('fromPayPalRequest')->andReturn($authorization);
$response = (object)[
'authorizations' => [
(object)['id' => 'foo', 'status' => 'CREATED'],
],
];
$testee = new PaymentsFactory($authorizationsFactory);
$result = $testee->fromPayPalResponse($response);
$this->assertInstanceOf(Payments::class, $result);
$expectedToArray = [
'authorizations' => [
['id' => 'foo', 'status' => 'CREATED'],
],
];
$this->assertEquals($expectedToArray, $result->toArray());
}
}

View file

@ -0,0 +1,659 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Factory;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Address;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Amount;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Item;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Payee;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Payments;
use Inpsyde\PayPalCommerce\ApiClient\Entity\PurchaseUnit;
use Inpsyde\PayPalCommerce\ApiClient\Entity\Shipping;
use Inpsyde\PayPalCommerce\ApiClient\Repository\PayeeRepository;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
use function Brain\Monkey\Functions\expect;
class PurchaseUnitFactoryTest extends TestCase
{
public function testWcOrderDefault()
{
$wcOrderId = 1;
$wcOrder = Mockery::mock(\WC_Order::class);
$wcOrder
->expects('get_id')->andReturn($wcOrderId);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->shouldReceive('fromWcOrder')
->with($wcOrder)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->shouldReceive('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->shouldReceive('fromWcOrder')
->with($wcOrder)
->andReturn([]);
$address = Mockery::mock(Address::class);
$address
->shouldReceive('countryCode')
->twice()
->andReturn('DE');
$address
->shouldReceive('postalCode')
->andReturn('12345');
$shipping = Mockery::mock(Shipping::class);
$shipping
->shouldReceive('address')
->andReturn($address);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shippingFactory
->shouldReceive('fromWcOrder')
->with($wcOrder)
->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcOrder($wcOrder);
$this->assertTrue(is_a($unit, PurchaseUnit::class));
$this->assertEquals($payee, $unit->payee());
$this->assertEquals('', $unit->description());
$this->assertEquals('default', $unit->referenceId());
$this->assertEquals('WC-' . $wcOrderId, $unit->customId());
$this->assertEquals('', $unit->softDescriptor());
$this->assertEquals('WC-' . $wcOrderId, $unit->invoiceId());
$this->assertEquals([], $unit->items());
$this->assertEquals($amount, $unit->amount());
$this->assertEquals($shipping, $unit->shipping());
}
public function testWcOrderShippingGetsDroppedWhenNoPostalCode()
{
$wcOrder = Mockery::mock(\WC_Order::class);
$wcOrder
->expects('get_id')->andReturn(1);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->expects('fromWcOrder')
->with($wcOrder)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->expects('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->expects('fromWcOrder')
->with($wcOrder)
->andReturn([]);
$address = Mockery::mock(Address::class);
$address
->expects('countryCode')
->twice()
->andReturn('DE');
$address
->expects('postalCode')
->andReturn('');
$shipping = Mockery::mock(Shipping::class);
$shipping
->expects('address')
->times(3)
->andReturn($address);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shippingFactory
->expects('fromWcOrder')
->with($wcOrder)
->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcOrder($wcOrder);
$this->assertEquals(null, $unit->shipping());
}
public function testWcOrderShippingGetsDroppedWhenNoCountryCode()
{
$wcOrder = Mockery::mock(\WC_Order::class);
$wcOrder
->expects('get_id')->andReturn(1);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->expects('fromWcOrder')
->with($wcOrder)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->expects('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->expects('fromWcOrder')
->with($wcOrder)
->andReturn([]);
$address = Mockery::mock(Address::class);
$address
->expects('countryCode')
->andReturn('');
$shipping = Mockery::mock(Shipping::class);
$shipping
->expects('address')
->andReturn($address);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shippingFactory
->expects('fromWcOrder')
->with($wcOrder)
->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcOrder($wcOrder);
$this->assertEquals(null, $unit->shipping());
}
public function testWcCartDefault()
{
$wcCustomer = Mockery::mock(\WC_Customer::class);
expect('WC')
->andReturn((object) ['customer' => $wcCustomer]);
$wcCart = Mockery::mock(\WC_Cart::class);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->expects('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn([]);
$address = Mockery::mock(Address::class);
$address
->shouldReceive('countryCode')
->andReturn('DE');
$address
->shouldReceive('postalCode')
->andReturn('12345');
$shipping = Mockery::mock(Shipping::class);
$shipping
->shouldReceive('address')
->zeroOrMoreTimes()
->andReturn($address);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shippingFactory
->expects('fromWcCustomer')
->with($wcCustomer)
->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcCart($wcCart);
$this->assertTrue(is_a($unit, PurchaseUnit::class));
$this->assertEquals($payee, $unit->payee());
$this->assertEquals('', $unit->description());
$this->assertEquals('default', $unit->referenceId());
$this->assertEquals('', $unit->customId());
$this->assertEquals('', $unit->softDescriptor());
$this->assertEquals('', $unit->invoiceId());
$this->assertEquals([], $unit->items());
$this->assertEquals($amount, $unit->amount());
$this->assertEquals($shipping, $unit->shipping());
}
public function testWcCartShippingGetsDroppendWhenNoCustomer()
{
expect('WC')
->andReturn((object) ['customer' => null]);
$wcCart = Mockery::mock(\WC_Cart::class);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->expects('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn([]);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcCart($wcCart);
$this->assertNull($unit->shipping());
}
public function testWcCartShippingGetsDroppendWhenNoPostalCode()
{
expect('WC')
->andReturn((object) ['customer' => Mockery::mock(\WC_Customer::class)]);
$wcCart = Mockery::mock(\WC_Cart::class);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->expects('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn([]);
$address = Mockery::mock(Address::class);
$address
->shouldReceive('countryCode')
->andReturn('DE');
$address
->shouldReceive('postalCode')
->andReturn('');
$shipping = Mockery::mock(Shipping::class);
$shipping
->shouldReceive('address')
->andReturn($address);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shippingFactory
->expects('fromWcCustomer')
->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcCart($wcCart);
$this->assertNull($unit->shipping());
}
public function testWcCartShippingGetsDroppendWhenNoCountryCode()
{
expect('WC')
->andReturn((object) ['customer' => Mockery::mock(\WC_Customer::class)]);
$wcCart = Mockery::mock(\WC_Cart::class);
$amount = Mockery::mock(Amount::class);
$amountFactory = Mockery::mock(AmountFactory::class);
$amountFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$payee = Mockery::mock(Payee::class);
$payeeRepository
->expects('payee')->andReturn($payee);
$itemFactory = Mockery::mock(ItemFactory::class);
$itemFactory
->expects('fromWcCart')
->with($wcCart)
->andReturn([]);
$address = Mockery::mock(Address::class);
$address
->shouldReceive('countryCode')
->andReturn('');
$shipping = Mockery::mock(Shipping::class);
$shipping
->shouldReceive('address')
->andReturn($address);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shippingFactory
->expects('fromWcCustomer')
->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$unit = $testee->fromWcCart($wcCart);
$this->assertNull($unit->shipping());
}
public function testFromPayPalResponseDefault()
{
$rawItem = (object) ['items' => 1];
$rawAmount = (object) ['amount' => 1];
$rawPayee = (object) ['payee' => 1];
$rawShipping = (object) ['shipping' => 1];
$amountFactory = Mockery::mock(AmountFactory::class);
$amount = Mockery::mock(Amount::class);
$amountFactory->expects('fromPayPalResponse')->with($rawAmount)->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payee = Mockery::mock(Payee::class);
$payeeFactory->expects('fromPayPalResponse')->with($rawPayee)->andReturn($payee);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$itemFactory = Mockery::mock(ItemFactory::class);
$item = Mockery::mock(Item::class, ['category' => Item::PHYSICAL_GOODS]);
$itemFactory->expects('fromPayPalResponse')->with($rawItem)->andReturn($item);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shipping = Mockery::mock(Shipping::class);
$shippingFactory->expects('fromPayPalResponse')->with($rawShipping)->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$response = (object) [
'reference_id' => 'default',
'description' => 'description',
'custom_id' => 'customId',
'invoice_id' => 'invoiceId',
'soft_descriptor' => 'softDescriptor',
'amount' => $rawAmount,
'items' => [$rawItem],
'payee' => $rawPayee,
'shipping' => $rawShipping,
];
$unit = $testee->fromPayPalResponse($response);
$this->assertTrue(is_a($unit, PurchaseUnit::class));
$this->assertEquals($payee, $unit->payee());
$this->assertEquals('description', $unit->description());
$this->assertEquals('default', $unit->referenceId());
$this->assertEquals('customId', $unit->customId());
$this->assertEquals('softDescriptor', $unit->softDescriptor());
$this->assertEquals('invoiceId', $unit->invoiceId());
$this->assertEquals([$item], $unit->items());
$this->assertEquals($amount, $unit->amount());
$this->assertEquals($shipping, $unit->shipping());
}
public function testFromPayPalResponsePayeeIsNull()
{
$rawItem = (object) ['items' => 1];
$rawAmount = (object) ['amount' => 1];
$rawPayee = (object) ['payee' => 1];
$rawShipping = (object) ['shipping' => 1];
$amountFactory = Mockery::mock(AmountFactory::class);
$amount = Mockery::mock(Amount::class);
$amountFactory->expects('fromPayPalResponse')->with($rawAmount)->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$itemFactory = Mockery::mock(ItemFactory::class);
$item = Mockery::mock(Item::class, ['category' => Item::PHYSICAL_GOODS]);
$itemFactory->expects('fromPayPalResponse')->with($rawItem)->andReturn($item);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shipping = Mockery::mock(Shipping::class);
$shippingFactory->expects('fromPayPalResponse')->with($rawShipping)->andReturn($shipping);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$response = (object) [
'reference_id' => 'default',
'description' => 'description',
'customId' => 'customId',
'invoiceId' => 'invoiceId',
'softDescriptor' => 'softDescriptor',
'amount' => $rawAmount,
'items' => [$rawItem],
'shipping' => $rawShipping,
];
$unit = $testee->fromPayPalResponse($response);
$this->assertNull($unit->payee());
}
public function testFromPayPalResponseShippingIsNull()
{
$rawItem = (object) ['items' => 1];
$rawAmount = (object) ['amount' => 1];
$rawPayee = (object) ['payee' => 1];
$amountFactory = Mockery::mock(AmountFactory::class);
$amount = Mockery::mock(Amount::class);
$amountFactory->expects('fromPayPalResponse')->with($rawAmount)->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payee = Mockery::mock(Payee::class);
$payeeFactory->expects('fromPayPalResponse')->with($rawPayee)->andReturn($payee);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$itemFactory = Mockery::mock(ItemFactory::class);
$item = Mockery::mock(Item::class, ['category' => Item::PHYSICAL_GOODS]);
$itemFactory->expects('fromPayPalResponse')->with($rawItem)->andReturn($item);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$response = (object) [
'reference_id' => 'default',
'description' => 'description',
'customId' => 'customId',
'invoiceId' => 'invoiceId',
'softDescriptor' => 'softDescriptor',
'amount' => $rawAmount,
'items' => [$rawItem],
'payee' => $rawPayee,
];
$unit = $testee->fromPayPalResponse($response);
$this->assertNull($unit->shipping());
}
public function testFromPayPalResponseNeedsReferenceId()
{
$amountFactory = Mockery::mock(AmountFactory::class);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$itemFactory = Mockery::mock(ItemFactory::class);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$paymentsFacory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFacory
);
$response = (object) [
'description' => 'description',
'customId' => 'customId',
'invoiceId' => 'invoiceId',
'softDescriptor' => 'softDescriptor',
'amount' => '',
'items' => [],
'payee' => '',
'shipping' => '',
];
$this->expectException(\Inpsyde\PayPalCommerce\ApiClient\Exception\RuntimeException::class);
$testee->fromPayPalResponse($response);
}
public function testFromPayPalResponsePaymentsGetAppended()
{
$rawItem = (object)['items' => 1];
$rawAmount = (object)['amount' => 1];
$rawPayee = (object)['payee' => 1];
$rawShipping = (object)['shipping' => 1];
$rawPayments = (object)['payments' => 1];
$amountFactory = Mockery::mock(AmountFactory::class);
$amount = Mockery::mock(Amount::class);
$amountFactory->expects('fromPayPalResponse')->with($rawAmount)->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payee = Mockery::mock(Payee::class);
$payeeFactory->expects('fromPayPalResponse')->with($rawPayee)->andReturn($payee);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$itemFactory = Mockery::mock(ItemFactory::class);
$item = Mockery::mock(Item::class, ['category' => Item::PHYSICAL_GOODS]);
$itemFactory->expects('fromPayPalResponse')->with($rawItem)->andReturn($item);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shipping = Mockery::mock(Shipping::class);
$shippingFactory->expects('fromPayPalResponse')->with($rawShipping)->andReturn($shipping);
$paymentsFactory = Mockery::mock(PaymentsFactory::class);
$payments = Mockery::mock(Payments::class);
$paymentsFactory->expects('fromPayPalResponse')->with($rawPayments)->andReturn($payments);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFactory
);
$response = (object)[
'reference_id' => 'default',
'description' => 'description',
'customId' => 'customId',
'invoiceId' => 'invoiceId',
'softDescriptor' => 'softDescriptor',
'amount' => $rawAmount,
'items' => [$rawItem],
'payee' => $rawPayee,
'shipping' => $rawShipping,
'payments' => $rawPayments,
];
$unit = $testee->fromPayPalResponse($response);
$this->assertEquals($payments, $unit->payments());
}
public function testFromPayPalResponsePaymentsIsNull()
{
$rawItem = (object)['items' => 1];
$rawAmount = (object)['amount' => 1];
$rawPayee = (object)['payee' => 1];
$rawShipping = (object)['shipping' => 1];
$rawPayments = (object)['payments' => 1];
$amountFactory = Mockery::mock(AmountFactory::class);
$amount = Mockery::mock(Amount::class);
$amountFactory->expects('fromPayPalResponse')->with($rawAmount)->andReturn($amount);
$payeeFactory = Mockery::mock(PayeeFactory::class);
$payee = Mockery::mock(Payee::class);
$payeeFactory->expects('fromPayPalResponse')->with($rawPayee)->andReturn($payee);
$payeeRepository = Mockery::mock(PayeeRepository::class);
$itemFactory = Mockery::mock(ItemFactory::class);
$item = Mockery::mock(Item::class, ['category' => Item::PHYSICAL_GOODS]);
$itemFactory->expects('fromPayPalResponse')->with($rawItem)->andReturn($item);
$shippingFactory = Mockery::mock(ShippingFactory::class);
$shipping = Mockery::mock(Shipping::class);
$shippingFactory->expects('fromPayPalResponse')->with($rawShipping)->andReturn($shipping);
$paymentsFactory = Mockery::mock(PaymentsFactory::class);
$testee = new PurchaseUnitFactory(
$amountFactory,
$payeeRepository,
$payeeFactory,
$itemFactory,
$shippingFactory,
$paymentsFactory
);
$response = (object)[
'reference_id' => 'default',
'description' => 'description',
'customId' => 'customId',
'invoiceId' => 'invoiceId',
'softDescriptor' => 'softDescriptor',
'amount' => $rawAmount,
'items' => [$rawItem],
'payee' => $rawPayee,
'shipping' => $rawShipping,
];
$unit = $testee->fromPayPalResponse($response);
$this->assertNull($unit->payments());
}
}

View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient\Repository;
use Inpsyde\PayPalCommerce\ApiClient\Config\Config;
use Inpsyde\PayPalCommerce\ApiClient\TestCase;
use Mockery;
class PayeeRepositoryTest extends TestCase
{
public function testDefault()
{
$merchantEmail = 'merchant_email';
$merchantId = 'merchant_id';
$testee = new PayeeRepository($merchantEmail, $merchantId);
$payee = $testee->payee();
$this->assertEquals($merchantId, $payee->merchantId());
$this->assertEquals($merchantEmail, $payee->email());
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Inpsyde\PayPalCommerce\ApiClient;
use function Brain\Monkey\setUp;
use function Brain\Monkey\tearDown;
use function Brain\Monkey\Functions\expect;
use Mockery;
class TestCase extends \PHPUnit\Framework\TestCase
{
public function setUp(): void
{
parent::setUp();
expect('__')->andReturnUsing(function (string $text) {
return $text;
});
setUp();
}
public function tearDown(): void
{
tearDown();
Mockery::close();
parent::tearDown();
}
}