From 005452c3b58a2e6c5326ab6f9f6e461ec86c0b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pavel=20Jura=CC=81sek?= Date: Tue, 2 Apr 2019 15:21:45 +0200 Subject: [PATCH 1/2] Update dependencies --- composer.json | 18 ++++++++++-------- src/MetisFW/PayPal/DI/PayPalExtension.php | 19 ++++++++++--------- src/MetisFW/PayPal/Helpers/GaTracking.php | 3 --- src/MetisFW/PayPal/PayPalContext.php | 3 --- .../PayPal/Payment/BasePaymentOperation.php | 4 ++++ src/MetisFW/PayPal/UI/PaymentControl.php | 1 - 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/composer.json b/composer.json index 5e1c8c0..fac8d6b 100644 --- a/composer.json +++ b/composer.json @@ -20,16 +20,18 @@ "issues": "https://github.com/MetisFW/PayPal/issues" }, "require": { - "php": ">=5.6.0", - "nette/di": "^2.4", - "nette/application": "^2.4", - "paypal/rest-api-sdk-php": "^1.5" + "php": "^7.1", + "ext-curl": "*", + "ext-json": "*", + "nette/di": "^3.0", + "nette/application": "3.0", + "paypal/rest-api-sdk-php": "^1.14" }, "require-dev": { - "nette/bootstrap": "^2.4", - "nette/robot-loader": "^2.4", - "nette/tester": "^2.4", - "mockery/mockery": "^1.4" + "nette/bootstrap": "^3.0", + "tracy/tracy": "^2.6", + "nette/tester": "^2.2", + "mockery/mockery": "^1.2" }, "autoload": { "psr-0": { diff --git a/src/MetisFW/PayPal/DI/PayPalExtension.php b/src/MetisFW/PayPal/DI/PayPalExtension.php index 6ea341a..6c9a103 100644 --- a/src/MetisFW/PayPal/DI/PayPalExtension.php +++ b/src/MetisFW/PayPal/DI/PayPalExtension.php @@ -5,6 +5,7 @@ use Nette\Configurator; use Nette\DI\Compiler; use Nette\DI\CompilerExtension; +use Nette\DI\Config\Helpers; use Nette\Utils\Validators; class PayPalExtension extends CompilerExtension { @@ -19,26 +20,29 @@ class PayPalExtension extends CompilerExtension { public function loadConfiguration() { $builder = $this->getContainerBuilder(); - $config = $this->getConfig($this->defaults); + $config = Helpers::merge($this->getConfig(), $this->defaults); Validators::assertField($config, 'clientId'); Validators::assertField($config, 'secret'); Validators::assertField($config, 'sdkConfig', 'array'); - $builder->addDefinition($this->prefix('simplePaymentOperationFactory')) + $builder->addFactoryDefinition($this->prefix('simplePaymentOperationFactory')) ->setImplement('MetisFW\PayPal\Payment\SimplePaymentOperationFactory'); - $builder->addDefinition($this->prefix('plainPaymentOperationFactory')) + $builder->addFactoryDefinition($this->prefix('plainPaymentOperationFactory')) ->setImplement('MetisFW\PayPal\Payment\PlainPaymentOperationFactory'); $builder->addDefinition($this->prefix('credentials')) - ->setClass('PayPal\Auth\OAuthTokenCredential', array($config['clientId'], $config['secret'])); + ->setType('PayPal\Auth\OAuthTokenCredential') + ->setArguments(array($config['clientId'], $config['secret'])); $builder->addDefinition($this->prefix('apiContext')) - ->setClass('PayPal\Rest\ApiContext', array($this->prefix('@credentials'))); + ->setType('PayPal\Rest\ApiContext') + ->setArguments(array($this->prefix('@credentials'))); $paypal = $builder->addDefinition($this->prefix('PayPal')) - ->setClass('MetisFW\PayPal\PayPalContext', array($this->prefix('@apiContext'))) + ->setType('MetisFW\PayPal\PayPalContext') + ->setArguments(array($this->prefix('@apiContext'))) ->addSetup('setConfig', array($config['sdkConfig'])) ->addSetup('setCurrency', array($config['currency'])) ->addSetup('setGaTrackingEnabled', array($config['gaTrackingEnabled'])); @@ -48,9 +52,6 @@ public function loadConfiguration() { } } - /** - * @param Configurator $configurator - */ public static function register(Configurator $configurator) { $configurator->onCompile[] = function ($config, Compiler $compiler) { $compiler->addExtension('payPal', new PayPalExtension()); diff --git a/src/MetisFW/PayPal/Helpers/GaTracking.php b/src/MetisFW/PayPal/Helpers/GaTracking.php index 244e7d8..66608a8 100644 --- a/src/MetisFW/PayPal/Helpers/GaTracking.php +++ b/src/MetisFW/PayPal/Helpers/GaTracking.php @@ -3,13 +3,10 @@ namespace MetisFW\PayPal\Helpers; use Nette\Http\Url; -use Nette\SmartObject; use PayPal\Api\Payment; class GaTracking { - use SmartObject; - private function __construct() { // nothing } diff --git a/src/MetisFW/PayPal/PayPalContext.php b/src/MetisFW/PayPal/PayPalContext.php index e0542c2..563384a 100644 --- a/src/MetisFW/PayPal/PayPalContext.php +++ b/src/MetisFW/PayPal/PayPalContext.php @@ -2,13 +2,10 @@ namespace MetisFW\PayPal; -use Nette\SmartObject; use PayPal\Rest\ApiContext; class PayPalContext { - use SmartObject; - /** @var ApiContext */ private $apiContext; diff --git a/src/MetisFW/PayPal/Payment/BasePaymentOperation.php b/src/MetisFW/PayPal/Payment/BasePaymentOperation.php index 4bfb7e5..7e612ca 100644 --- a/src/MetisFW/PayPal/Payment/BasePaymentOperation.php +++ b/src/MetisFW/PayPal/Payment/BasePaymentOperation.php @@ -16,6 +16,10 @@ use PayPal\Exception\PayPalInvalidCredentialException; use PayPal\Exception\PayPalMissingCredentialException; +/** + * @method void onCancel(self $self) + * @method void onReturn(self $self, Payment $payment) + */ abstract class BasePaymentOperation implements PaymentOperation { use SmartObject; diff --git a/src/MetisFW/PayPal/UI/PaymentControl.php b/src/MetisFW/PayPal/UI/PaymentControl.php index 6534cfe..ccb1228 100644 --- a/src/MetisFW/PayPal/UI/PaymentControl.php +++ b/src/MetisFW/PayPal/UI/PaymentControl.php @@ -44,7 +44,6 @@ class PaymentControl extends Control { * @param PaymentOperation $operation */ public function __construct(PaymentOperation $operation) { - parent::__construct(); $this->operation = $operation; } From 5ef801febd821339820683274f94f0f84e58de27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pavel=20Jura=CC=81sek?= Date: Tue, 9 Apr 2019 21:38:11 +0200 Subject: [PATCH 2/2] Update coding standards, fix phpstan errors --- composer.json | 11 +- phpstan.neon | 12 + src/MetisFW/PayPal/DI/PayPalExtension.php | 116 +++---- src/MetisFW/PayPal/Helpers/GaTracking.php | 29 +- src/MetisFW/PayPal/PayPalContext.php | 138 ++++----- src/MetisFW/PayPal/PayPalException.php | 7 +- .../PayPal/Payment/BasePaymentOperation.php | 287 ++++++++---------- .../PayPal/Payment/PaymentOperation.php | 48 ++- .../PayPal/Payment/PlainPaymentOperation.php | 38 +-- .../Payment/PlainPaymentOperationFactory.php | 12 +- .../PayPal/Payment/SimplePaymentOperation.php | 121 ++++---- .../Payment/SimplePaymentOperationFactory.php | 18 +- src/MetisFW/PayPal/UI/PaymentControl.php | 253 +++++++-------- tests/PayPal/DI/PayPalExtensionTest.phpt | 46 +-- tests/PayPal/Helper/TransactionHelper.php | 134 ++++---- .../PayPal/Payment/DummyPaymentOperation.php | 40 +-- .../PaymentOperationTest.handleReturn.phpt | 108 +++---- .../PayPal/Payment/PaymentOperationTest.phpt | 265 ++++++++-------- tests/PayPal/UI/PaymentControlTest.phpt | 157 +++++----- tests/bootstrap.php | 14 +- tests/paypal.config.neon | 5 +- 21 files changed, 909 insertions(+), 950 deletions(-) create mode 100644 phpstan.neon diff --git a/composer.json b/composer.json index fac8d6b..57639e5 100644 --- a/composer.json +++ b/composer.json @@ -24,18 +24,21 @@ "ext-curl": "*", "ext-json": "*", "nette/di": "^3.0", - "nette/application": "3.0", + "nette/application": "^3.0", "paypal/rest-api-sdk-php": "^1.14" }, "require-dev": { "nette/bootstrap": "^3.0", "tracy/tracy": "^2.6", "nette/tester": "^2.2", - "mockery/mockery": "^1.2" + "mockery/mockery": "^1.2", + "phpstan/phpstan": "^0.11", + "phpstan/phpstan-nette": "^0.11" }, "autoload": { - "psr-0": { - "MetisFW\\PayPal\\": "src/" + "psr-4": { + "MetisFW\\PayPal\\": "src/MetisFW/PayPal", + "Tests\\PayPal\\": "tests/PayPal" } }, "archive": { diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..81c5ddd --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,12 @@ +parameters: + level: 7 + paths: + - src + - tests/PayPal + ignoreErrors: + - '#Cannot call method getParameter\(\) on Nette\\Application\\UI\\Presenter|null#' +# - '#Cannot call method redirectUrl\(\) on Nette\\Application\\UI\\Presenter|null#' + +includes: + - vendor/phpstan/phpstan-nette/extension.neon + - vendor/phpstan/phpstan-nette/rules.neon diff --git a/src/MetisFW/PayPal/DI/PayPalExtension.php b/src/MetisFW/PayPal/DI/PayPalExtension.php index 6c9a103..bf852f4 100644 --- a/src/MetisFW/PayPal/DI/PayPalExtension.php +++ b/src/MetisFW/PayPal/DI/PayPalExtension.php @@ -1,61 +1,71 @@ - 'CZK', - 'gaTrackingEnabled' => true - ); - - public function loadConfiguration() { - $builder = $this->getContainerBuilder(); - $config = Helpers::merge($this->getConfig(), $this->defaults); - - Validators::assertField($config, 'clientId'); - Validators::assertField($config, 'secret'); - Validators::assertField($config, 'sdkConfig', 'array'); - - $builder->addFactoryDefinition($this->prefix('simplePaymentOperationFactory')) - ->setImplement('MetisFW\PayPal\Payment\SimplePaymentOperationFactory'); - - $builder->addFactoryDefinition($this->prefix('plainPaymentOperationFactory')) - ->setImplement('MetisFW\PayPal\Payment\PlainPaymentOperationFactory'); - - $builder->addDefinition($this->prefix('credentials')) - ->setType('PayPal\Auth\OAuthTokenCredential') - ->setArguments(array($config['clientId'], $config['secret'])); - - $builder->addDefinition($this->prefix('apiContext')) - ->setType('PayPal\Rest\ApiContext') - ->setArguments(array($this->prefix('@credentials'))); - - $paypal = $builder->addDefinition($this->prefix('PayPal')) - ->setType('MetisFW\PayPal\PayPalContext') - ->setArguments(array($this->prefix('@apiContext'))) - ->addSetup('setConfig', array($config['sdkConfig'])) - ->addSetup('setCurrency', array($config['currency'])) - ->addSetup('setGaTrackingEnabled', array($config['gaTrackingEnabled'])); - - if (isset($config['experienceProfileId'])) { - $paypal->addSetup('setExperienceProfileId', array($config['experienceProfileId'])); - } - } - - public static function register(Configurator $configurator) { - $configurator->onCompile[] = function ($config, Compiler $compiler) { - $compiler->addExtension('payPal', new PayPalExtension()); - }; - } +use Nette\Schema\Expect; +use Nette\Schema\Schema; + +class PayPalExtension extends CompilerExtension +{ + + public function loadConfiguration() + { + $builder = $this->getContainerBuilder(); + $config = (array) $this->getConfig(); + + $builder->addFactoryDefinition($this->prefix('simplePaymentOperationFactory')) + ->setImplement('MetisFW\PayPal\Payment\SimplePaymentOperationFactory'); + + $builder->addFactoryDefinition($this->prefix('plainPaymentOperationFactory')) + ->setImplement('MetisFW\PayPal\Payment\PlainPaymentOperationFactory'); + + $builder->addDefinition($this->prefix('credentials')) + ->setType('PayPal\Auth\OAuthTokenCredential') + ->setArguments([$config['clientId'], $config['secret']]); + + $builder->addDefinition($this->prefix('apiContext')) + ->setType('PayPal\Rest\ApiContext') + ->setArguments([$this->prefix('@credentials')]); + + $paypal = $builder->addDefinition($this->prefix('PayPal')) + ->setType('MetisFW\PayPal\PayPalContext') + ->setArguments([$this->prefix('@apiContext')]) + ->addSetup('setConfig', [(array) $config['sdkConfig']]) + ->addSetup('setCurrency', [$config['currency']]) + ->addSetup('setGaTrackingEnabled', [$config['gaTrackingEnabled']]); + + if ($config['experienceProfileId'] !== null) { + $paypal->addSetup('setExperienceProfileId', [$config['experienceProfileId']]); + } + } + + public static function register(Configurator $configurator) + { + $configurator->onCompile[] = function ($config, Compiler $compiler) { + $compiler->addExtension('payPal', new PayPalExtension()); + }; + } + + public function getConfigSchema(): Schema + { + return Expect::structure([ + 'currency' => Expect::string('CZK'), + 'gaTrackingEnabled' => Expect::bool(true), + 'experienceProfileId' => Expect::string(), + 'clientId' => Expect::string()->required(), + 'secret' => Expect::string()->required(), + 'sdkConfig' => Expect::structure([ + 'mode' => Expect::anyOf('sandbox', 'live')->required(), + 'log.LogEnabled' => Expect::bool(), + 'log.FileName' => Expect::string(), + 'log.LogLevel' => Expect::anyOf('emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug'), + 'cache.enabled' => Expect::bool(true), + 'cache.FileName' => Expect::string(), + ]), + ]); + } } diff --git a/src/MetisFW/PayPal/Helpers/GaTracking.php b/src/MetisFW/PayPal/Helpers/GaTracking.php index 66608a8..f3d7bde 100644 --- a/src/MetisFW/PayPal/Helpers/GaTracking.php +++ b/src/MetisFW/PayPal/Helpers/GaTracking.php @@ -1,26 +1,29 @@ -getRedirectUrls(); + public static function addTrackingParameters(Payment $payment): Payment + { + $redirectUrls = $payment->getRedirectUrls(); - $url = new Url($redirectUrls->getReturnUrl()); - $url->setQueryParameter('utm_nooverride', 1); + $url = new Url($redirectUrls->getReturnUrl()); + $url->setQueryParameter('utm_nooverride', 1); - $redirectUrls->setReturnUrl($url->getAbsoluteUrl()); - $payment->setRedirectUrls($redirectUrls); + $redirectUrls->setReturnUrl($url->getAbsoluteUrl()); + $payment->setRedirectUrls($redirectUrls); - return $payment; - } + return $payment; + } } diff --git a/src/MetisFW/PayPal/PayPalContext.php b/src/MetisFW/PayPal/PayPalContext.php index 563384a..c8ebe93 100644 --- a/src/MetisFW/PayPal/PayPalContext.php +++ b/src/MetisFW/PayPal/PayPalContext.php @@ -1,85 +1,67 @@ -apiContext = $apiContext; - } - - /** - * @param array $config - */ - public function setConfig(array $config) { - $this->apiContext->setConfig($config); - } - - /** - * @param string $currency - */ - public function setCurrency($currency) { - $this->currency = $currency; - } - - /** - * @return string - */ - public function getCurrency() { - return $this->currency; - } - - /** - * @return ApiContext - */ - public function getApiContext() { - return $this->apiContext; - } - - /** - * @param bool $value - */ - public function setGaTrackingEnabled($value) { - $this->gaTrackingEnabled = $value; - } - - /** - * @return bool - */ - public function isGaTrackingEnabled() { - return $this->gaTrackingEnabled; - } - - /** - * @return string - */ - public function getExperienceProfileId() { - return $this->experienceProfileId; - } - - /** - * @param string $experienceProfileId - */ - public function setExperienceProfileId($experienceProfileId) { - $this->experienceProfileId = $experienceProfileId; - } +class PayPalContext +{ + + /** @var ApiContext */ + private $apiContext; + + /** @var string */ + private $currency; + + /** @var bool */ + private $gaTrackingEnabled = false; + + /** @var string|null */ + private $experienceProfileId; + + public function __construct(ApiContext $apiContext) + { + $this->apiContext = $apiContext; + } + + public function setConfig(array $config): void + { + $this->apiContext->setConfig($config); + } + + public function setCurrency(string $currency): void + { + $this->currency = $currency; + } + + public function getCurrency(): string + { + return $this->currency; + } + + public function getApiContext(): ApiContext + { + return $this->apiContext; + } + + public function setGaTrackingEnabled(bool $value): void + { + $this->gaTrackingEnabled = $value; + } + + public function isGaTrackingEnabled(): bool + { + return $this->gaTrackingEnabled; + } + + public function getExperienceProfileId(): ?string + { + return $this->experienceProfileId; + } + + public function setExperienceProfileId(string $experienceProfileId): void + { + $this->experienceProfileId = $experienceProfileId; + } } diff --git a/src/MetisFW/PayPal/PayPalException.php b/src/MetisFW/PayPal/PayPalException.php index c8201ff..52af428 100644 --- a/src/MetisFW/PayPal/PayPalException.php +++ b/src/MetisFW/PayPal/PayPalException.php @@ -1,7 +1,8 @@ -context = $context; - } - - /** - * @return array array of PayPal\Api\Transaction - */ - abstract protected function getTransactions(); - - /** - * @return Payer - */ - protected function getPayer() { - $payer = new Payer(); - return $payer; - } - - /** - * @see http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html - * - * @return Payment - */ - public function getPayment() { - $payer = $this->getPayer(); - if(!$payer || !($payer instanceof Payer)) { - throw new InvalidArgumentException("Method getPayer has to return instance of Payer. Instead ". - gettype($payer)." given."); - } - - if(!$payer->getPaymentMethod()) { - $payer->setPaymentMethod('paypal'); - } - - $payment = new Payment(); - $payment->setIntent("sale") - ->setPayer($payer); - - if ($this->context->getExperienceProfileId()) { - $payment->setExperienceProfileId($this->context->getExperienceProfileId()); - } - - $transactions = $this->getTransactions(); - $this->checkTransactions($transactions); - $payment->setTransactions($transactions); - - return $payment; - } - - /** - * Execute payment api call - * - * @return Payment - */ - public function createPayment(Payment $payment) { - if($this->context->isGaTrackingEnabled()) { - $payment = GaTracking::addTrackingParameters($payment); - } - - try { - return $payment->create($this->context->getApiContext()); - } - catch(\Exception $exception) { - throw $this->translateException($exception); - } - } - - /** - * @param string $paymentId - * @param string $payerId - * - * @return void - */ - public function handleReturn($paymentId, $payerId) { - try { - $payment = Payment::get($paymentId, $this->context->getApiContext()); - $execution = new PaymentExecution(); - $execution->setPayerId($payerId); - - $payment->execute($execution, $this->context->getApiContext()); - $paidPayment = Payment::get($paymentId, $this->context->getApiContext()); - } - catch(\Exception $exception) { - throw $this->translateException($exception); - } - - $this->onReturn($this, $paidPayment); - return $paidPayment; - } - - /** - * @return void - */ - public function handleCancel() { - $this->onCancel($this); - } - - /** - * @param \Exception $exception - * @return \Exception - */ - protected function translateException(\Exception $exception) { - if($exception instanceof PayPalConfigurationException || - $exception instanceof PayPalInvalidCredentialException || - $exception instanceof PayPalMissingCredentialException || - $exception instanceof PayPalConnectionException - ) { - return new PayPalException( - $exception->getMessage().'Data: '.$exception->getData(), - $exception->getCode(), - $exception); - } - - return $exception; - } - - /** - * @param array $transactions - * - * @throws \LogicException throws when some item from array is not instance of \PayPal\Api\Transaction - */ - protected function checkTransactions(array $transactions) { - foreach($transactions as $transaction) { - if(!$transaction instanceof Transaction) { - throw new \LogicException('Expect array of \PayPal\Api\Transaction instances but instance of '. - gettype($transaction).' given'); - } - } - } +abstract class BasePaymentOperation implements PaymentOperation +{ + + use SmartObject; + + /** @var PayPalContext */ + protected $context; + + /** + * @var array array of callbacks, signature: function ($this) {...} + */ + public $onCancel; + + /** + * @var array array of callbacks, signature: function ($this, Payment $payment) {...} + */ + public $onReturn; + + public function __construct(PayPalContext $context) + { + $this->context = $context; + } + + /** + * @return Transaction[] + */ + abstract protected function getTransactions(): array; + + protected function getPayer(): Payer + { + return new Payer(); + } + + /** + * @see http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html + */ + public function getPayment(): Payment + { + $payer = $this->getPayer(); + + if (!$payer->getPaymentMethod()) { + $payer->setPaymentMethod('paypal'); + } + + $payment = new Payment(); + $payment->setIntent("sale") + ->setPayer($payer); + + if ($this->context->getExperienceProfileId()) { + $payment->setExperienceProfileId($this->context->getExperienceProfileId()); + } + + $transactions = $this->getTransactions(); + $this->checkTransactions($transactions); + $payment->setTransactions($transactions); + + return $payment; + } + + /** + * Execute payment api call + */ + public function createPayment(Payment $payment): Payment + { + if ($this->context->isGaTrackingEnabled()) { + $payment = GaTracking::addTrackingParameters($payment); + } + + try { + return $payment->create($this->context->getApiContext()); + } catch (\Exception $exception) { + throw $this->translateException($exception); + } + } + + public function handleReturn(string $paymentId, string $payerId): Payment + { + try { + $payment = Payment::get($paymentId, $this->context->getApiContext()); + $execution = new PaymentExecution(); + $execution->setPayerId($payerId); + + $payment->execute($execution, $this->context->getApiContext()); + $paidPayment = Payment::get($paymentId, $this->context->getApiContext()); + } catch (\Exception $exception) { + throw $this->translateException($exception); + } + + $this->onReturn($this, $paidPayment); + + return $paidPayment; + } + + public function handleCancel(): void + { + $this->onCancel($this); + } + + protected function translateException(\Exception $exception): \Exception + { + if ($exception instanceof PayPalConfigurationException || + $exception instanceof PayPalInvalidCredentialException || + $exception instanceof PayPalMissingCredentialException || + $exception instanceof PayPalConnectionException + ) { + + $message = $exception->getMessage(); + + if ($exception instanceof PayPalConnectionException) { + $message .= ' Data: ' . $exception->getData(); + } + return new PayPalException( + $message, + $exception->getCode(), + $exception); + } + + return $exception; + } + + /** + * @throws \LogicException throws when some item from array is not instance of \PayPal\Api\Transaction + */ + protected function checkTransactions(array $transactions): void + { + foreach ($transactions as $transaction) { + if (!$transaction instanceof Transaction) { + throw new \LogicException('Expect array of \PayPal\Api\Transaction instances but instance of ' . + gettype($transaction) . ' given'); + } + } + } } diff --git a/src/MetisFW/PayPal/Payment/PaymentOperation.php b/src/MetisFW/PayPal/Payment/PaymentOperation.php index a838de7..05734ad 100644 --- a/src/MetisFW/PayPal/Payment/PaymentOperation.php +++ b/src/MetisFW/PayPal/Payment/PaymentOperation.php @@ -1,38 +1,24 @@ -checkTransactions($transactions); - $this->transactions = $transactions; - } + public function __construct(PayPalContext $context, array $transactions) + { + parent::__construct($context); + $this->checkTransactions($transactions); + $this->transactions = $transactions; + } - /** - * @return array array of PayPal\Api\Transaction - */ - protected function getTransactions() { - return $this->transactions; - } + /** + * @return Transaction[] + */ + protected function getTransactions(): array + { + return $this->transactions; + } } diff --git a/src/MetisFW/PayPal/Payment/PlainPaymentOperationFactory.php b/src/MetisFW/PayPal/Payment/PlainPaymentOperationFactory.php index dc69dc0..7ad6f4c 100644 --- a/src/MetisFW/PayPal/Payment/PlainPaymentOperationFactory.php +++ b/src/MetisFW/PayPal/Payment/PlainPaymentOperationFactory.php @@ -1,14 +1,10 @@ -name = $name; - $this->quantity = $quantity; - $this->price = $price; - $this->currency = $currency; - } - - /** - * @return array array of PayPal\Api\Transaction - */ - protected function getTransactions() { - $payPalItems = array(); - $currency = $this->currency ? $this->currency : $this->context->getCurrency(); - - $payPalItem = new Item(); - $payPalItem->setName($this->name); - $payPalItem->setCurrency($currency); - $payPalItem->setQuantity($this->quantity); - $payPalItem->setPrice($this->price); - - $payPalItems[] = $payPalItem; - $totalPrice = $this->quantity * $this->price; - - $itemLists = new ItemList(); - $itemLists->setItems($payPalItems); - - $amount = new Amount(); - $amount->setCurrency($currency); - $amount->setTotal($totalPrice); - - $transaction = new Transaction(); - $transaction->setAmount($amount); - $transaction->setItemList($itemLists); - - return array($transaction); - } - -} \ No newline at end of file +class SimplePaymentOperation extends BasePaymentOperation +{ + + /** @var string */ + private $name; + + /** @var int */ + private $quantity; + + /** @var int|float|string */ + private $price; + + /** @var string|null */ + private $currency; + + /** + * @param int|float|string $price + */ + public function __construct(PayPalContext $context, string $name, $price, int $quantity = 1, ?string $currency = null) + { + parent::__construct($context); + $this->name = $name; + $this->quantity = $quantity; + $this->price = $price; + $this->currency = $currency; + } + + /** + * @return Transaction[] + */ + protected function getTransactions(): array + { + $payPalItems = array(); + $currency = $this->currency ? $this->currency : $this->context->getCurrency(); + + $payPalItem = new Item(); + $payPalItem->setName($this->name); + $payPalItem->setCurrency($currency); + $payPalItem->setQuantity((string) $this->quantity); + $payPalItem->setPrice((double) $this->price); + + $payPalItems[] = $payPalItem; + $totalPrice = $this->quantity * (double) $this->price; + + $itemLists = new ItemList(); + $itemLists->setItems($payPalItems); + + $amount = new Amount(); + $amount->setCurrency($currency); + $amount->setTotal($totalPrice); + + $transaction = new Transaction(); + $transaction->setAmount($amount); + $transaction->setItemList($itemLists); + + return [$transaction]; + } + +} diff --git a/src/MetisFW/PayPal/Payment/SimplePaymentOperationFactory.php b/src/MetisFW/PayPal/Payment/SimplePaymentOperationFactory.php index 709ca98..29f3739 100644 --- a/src/MetisFW/PayPal/Payment/SimplePaymentOperationFactory.php +++ b/src/MetisFW/PayPal/Payment/SimplePaymentOperationFactory.php @@ -1,17 +1,13 @@ -operation = $operation; - } - - public function handleCheckout() { - try { - $payment = $this->operation->getPayment(); - $this->setPaymentParameters($payment); - - $createdPayment = $this->operation->createPayment($payment); - $this->onCheckout($this, $createdPayment); - - $approvalUrl = $createdPayment->getApprovalLink(); - $this->getPresenter()->redirectUrl($approvalUrl); - } - catch(PayPalException $exception) { - $this->errorHandler($exception); - } - } - - public function handleReturn() { - $paymentId = $this->getPresenter()->getParameter('paymentId'); - $payerId = $this->getPresenter()->getParameter('PayerID'); - - try { - $paidPayment = $this->operation->handleReturn($paymentId, $payerId); - } - catch(PayPalException $exception) { - $this->errorHandler($exception); - return; - } - - $this->onSuccess($this, $paidPayment); - } - - public function handleCancel() { - $this->operation->handleCancel(); - $this->onCancel($this); - } - - public function setTemplateFilePath($templateFilePath) { - $this->templateFilePath = $templateFilePath; - } - public function getTemplateFilePath() { - return $this->templateFilePath ? $this->templateFilePath : $this->getDefaultTemplateFilePath(); - } - - /** - * @param array $attrs - * @param string $text - */ - public function render($attrs = array(), $text = "Pay") { - $template = $this->template; - $templateFilePath = $this->getTemplateFilePath(); - $template->setFile($templateFilePath); - $template->checkoutLink = $this->link('//checkout!'); - $template->text = $text; - $template->attrs = $attrs; - $template->render(); - } - - /** - * @param \Exception $exception - * - * @throws PayPalException - * - * @return void - */ - protected function errorHandler(\Exception $exception) { - if(!$this->onError) { - throw $exception; - } - - $this->onError($this, $exception); - } - - /** - * @param Payment $payment - */ - protected function setPaymentParameters(Payment $payment) { - $redirectUrls = new RedirectUrls(); - $redirectUrls->setReturnUrl($this->link('//return!'))->setCancelUrl($this->link('//cancel!')); - $payment->setRedirectUrls($redirectUrls); - } - - protected function getDefaultTemplateFilePath() { - return __DIR__.'/templates/PaymentControl.latte'; - } +/** + * @method void onCancel(PaymentControl $control) + * @method void onError(PaymentControl $control, \Exception $exception) + * @method void onCheckout(PaymentControl $control, PayPalContext $context) + * @method void onSuccess(PaymentControl $control, array $response) + * @property-read Template $template + */ +class PaymentControl extends Control +{ + + /** + * @var PaymentOperation + */ + private $operation; + + /** + * @var string + */ + private $templateFilePath; + + /** + * @var array of callbacks, signature: function(PaymentControl $control, PayPalContext $context) + */ + public $onCheckout = []; + + /** + * @var array of callbacks, signature: function(PaymentControl $control, array $response) + */ + public $onSuccess = []; + + /** + * @var array of callbacks, signature: function(PaymentControl $control) + */ + public $onCancel = []; + + /** + * @var array of callbacks, signature: function(PaymentControl $control, \Exception $exception) + */ + public $onError = []; + + public function __construct(PaymentOperation $operation) + { + $this->operation = $operation; + } + + public function handleCheckout(): void + { + try { + $payment = $this->operation->getPayment(); + $this->setPaymentParameters($payment); + + $createdPayment = $this->operation->createPayment($payment); + $this->onCheckout($this, $createdPayment); + + $approvalUrl = $createdPayment->getApprovalLink(); + $this->getPresenter()->redirectUrl($approvalUrl); + } catch (PayPalException $exception) { + $this->errorHandler($exception); + } + } + + public function handleReturn(?string $paymentId, ?string $payerId): void + { + $paymentId = $paymentId ?: $this->getPresenter()->getParameter('paymentId'); + $payerId = $payerId ?: $this->getPresenter()->getParameter('PayerID'); + + try { + $paidPayment = $this->operation->handleReturn($paymentId, $payerId); + } catch (PayPalException $exception) { + $this->errorHandler($exception); + return; + } + + $this->onSuccess($this, $paidPayment); + } + + public function handleCancel(): void + { + $this->operation->handleCancel(); + $this->onCancel($this); + } + + public function setTemplateFilePath(string $templateFilePath): void + { + $this->templateFilePath = $templateFilePath; + } + + public function getTemplateFilePath(): string + { + return $this->templateFilePath ? $this->templateFilePath : $this->getDefaultTemplateFilePath(); + } + + public function render(array $attrs = [], string $text = "Pay"): void + { + $template = $this->template; + $templateFilePath = $this->getTemplateFilePath(); + $template->setFile($templateFilePath); + $template->checkoutLink = $this->link('//checkout!'); + $template->text = $text; + $template->attrs = $attrs; + $template->render(); + } + + /** + * @throws PayPalException + */ + protected function errorHandler(\Exception $exception): void + { + if (!$this->onError) { + throw $exception; + } + + $this->onError($this, $exception); + } + + protected function setPaymentParameters(Payment $payment): void + { + $redirectUrls = new RedirectUrls(); + $redirectUrls->setReturnUrl($this->link('//return!'))->setCancelUrl($this->link('//cancel!')); + $payment->setRedirectUrls($redirectUrls); + } + + protected function getDefaultTemplateFilePath(): string + { + return __DIR__ . '/templates/PaymentControl.latte'; + } } diff --git a/tests/PayPal/DI/PayPalExtensionTest.phpt b/tests/PayPal/DI/PayPalExtensionTest.phpt index 00244f7..0893789 100644 --- a/tests/PayPal/DI/PayPalExtensionTest.phpt +++ b/tests/PayPal/DI/PayPalExtensionTest.phpt @@ -1,6 +1,6 @@ -setTempDirectory(TEMP_DIR); - $config->addParameters(array('container' => array('class' => 'SystemContainer_'.md5(TEMP_DIR)))); - PayPalExtension::register($config); - $config->addConfig(__DIR__.'/../../paypal.config.neon'); + public function testExtensionCreated() + { + $config = new Configurator(); + $config->setTempDirectory(TEMP_DIR); + $config->addParameters(['container' => ['class' => 'SystemContainer_' . md5(TEMP_DIR)]]); + PayPalExtension::register($config); + $config->addConfig(__DIR__ . '/../../paypal.config.neon'); - $container = $config->createContainer(); - /** @var PayPalContext $paypal */ - $paypal = $container->getByType('MetisFW\PayPal\PayPalContext'); + $container = $config->createContainer(); + /** @var PayPalContext $paypal */ + $paypal = $container->getByType('MetisFW\PayPal\PayPalContext'); - Assert::notEqual(null, $paypal); + Assert::notEqual(null, $paypal); - $simpleOperationFactory = $container->getByType('MetisFW\PayPal\Payment\SimplePaymentOperationFactory'); - $operation = $simpleOperationFactory->create('Coffee', 10); - Assert::true($operation instanceof SimplePaymentOperation); + $simpleOperationFactory = $container->getByType('MetisFW\PayPal\Payment\SimplePaymentOperationFactory'); + $operation = $simpleOperationFactory->create('Coffee', 10); + Assert::true($operation instanceof SimplePaymentOperation); - $plainOperationFactory = $container->getByType('MetisFW\PayPal\Payment\PlainPaymentOperationFactory'); - $operation = $plainOperationFactory->create(array()); - Assert::true($operation instanceof PlainPaymentOperation); + $plainOperationFactory = $container->getByType('MetisFW\PayPal\Payment\PlainPaymentOperationFactory'); + $operation = $plainOperationFactory->create([]); + Assert::true($operation instanceof PlainPaymentOperation); - Assert::true($paypal->isGaTrackingEnabled()); - } + Assert::true($paypal->isGaTrackingEnabled()); + } } diff --git a/tests/PayPal/Helper/TransactionHelper.php b/tests/PayPal/Helper/TransactionHelper.php index 6ba1d3c..71b7916 100644 --- a/tests/PayPal/Helper/TransactionHelper.php +++ b/tests/PayPal/Helper/TransactionHelper.php @@ -1,6 +1,6 @@ -setAmount($amount); - $transaction->setItemList($itemLists); - $transaction->setInvoiceNumber($invoiceNumber); - $transaction->setDescription($description); - return $transaction; - } - - /** - * @param string $currency - * @param int $total - * @param Details $details - * - * @return Amount - */ - static public function createAmount(Details $details, $total, $currency) { - $amount = new Amount(); - $amount->setCurrency($currency); - $amount->setTotal($total); - $amount->setDetails($details); - return $amount; - } - - /** - * @param float $shippingPrice - * @param float $taxPrice - * @param float $subtotal - * - * @return Details - */ - static public function createDetails($shippingPrice, $taxPrice, $subtotal) { - $details = new Details(); - $details->setShipping($shippingPrice); - $details->setTax($taxPrice); - - $details->setSubtotal($subtotal); - return $details; - } - - /** - * @param array $items - * - * @return ItemList - */ - static public function createItemList(array $items) { - $itemList = new ItemList(); - $itemList->setItems($items); - return $itemList; - } - - /** - * @param string $name - * @param int $currency - * @param int $quantity - * @param string $sku - * @param int $price - * @return Item - */ - static public function createItem($name, $currency, $quantity, $sku, $price) { - $item = new Item(); - $item->setName($name); - $item->setCurrency($currency); - $item->setQuantity($quantity); - $item->setSku($sku); - $item->setPrice($price); - return $item; - } -} \ No newline at end of file +class TransactionHelper +{ + + static public function createTransaction(Amount $amount, ItemList $itemLists, string $invoiceNumber, string $description): Transaction + { + $transaction = new Transaction(); + $transaction->setAmount($amount); + $transaction->setItemList($itemLists); + $transaction->setInvoiceNumber($invoiceNumber); + $transaction->setDescription($description); + return $transaction; + } + + static public function createAmount(Details $details, int $total, string $currency): Amount + { + $amount = new Amount(); + $amount->setCurrency($currency); + $amount->setTotal($total); + $amount->setDetails($details); + return $amount; + } + + static public function createDetails(float $shippingPrice, float $taxPrice, float $subtotal): Details + { + $details = new Details(); + $details->setShipping($shippingPrice); + $details->setTax($taxPrice); + + $details->setSubtotal($subtotal); + return $details; + } + + static public function createItemList(array $items): ItemList + { + $itemList = new ItemList(); + $itemList->setItems($items); + return $itemList; + } + + static public function createItem(string $name, string $currency, int $quantity, string $sku, int $price): Item + { + $item = new Item(); + $item->setName($name); + $item->setCurrency($currency); + $item->setQuantity((string) $quantity); + $item->setSku($sku); + $item->setPrice($price); + return $item; + } + +} diff --git a/tests/PayPal/Payment/DummyPaymentOperation.php b/tests/PayPal/Payment/DummyPaymentOperation.php index 4011c4e..470df6a 100644 --- a/tests/PayPal/Payment/DummyPaymentOperation.php +++ b/tests/PayPal/Payment/DummyPaymentOperation.php @@ -1,26 +1,28 @@ -config = array( - 'clientId' => 'AUqne4ywvozUaSQ1THTZYKFr88bhtA0SS_fXBoJTfeSTIasDBWuXLiLcFlfmSXRfL-kZ3Z5shvNrT6rP', - 'secretId' => 'EDGPDc3a65JBBY7-IKkNak7aGTVTvY-NhJgfhptegSML58fWjfp89U7UKNgGk9UI-UEZ-btfaE2sGST1' - ); - } + /** + * This method is called before a test is executed. + * + * @return void + */ + protected function setUp() + { + parent::setUp(); + $this->config = [ + 'clientId' => 'AUqne4ywvozUaSQ1THTZYKFr88bhtA0SS_fXBoJTfeSTIasDBWuXLiLcFlfmSXRfL-kZ3Z5shvNrT6rP', + 'secretId' => 'EDGPDc3a65JBBY7-IKkNak7aGTVTvY-NhJgfhptegSML58fWjfp89U7UKNgGk9UI-UEZ-btfaE2sGST1' + ]; + } - public function testHandleReturn() { - $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); - $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', array($credentials))->makePartial(); + public function testHandleReturn() + { + $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); + $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', [$credentials])->makePartial(); - $context = new PayPalContext($apiContext); - $operation = new DummyPaymentOperation( - $context); + $context = new PayPalContext($apiContext); + $operation = new DummyPaymentOperation( + $context); - $paymentId = "123456"; - $payerId = "john.doe"; + $paymentId = "123456"; + $payerId = "john.doe"; - $paymentMock = \Mockery::mock('alias:\PayPal\Api\Payment'); - $approvedPayment = $paymentMock; - $paymentMock->shouldReceive('get')->with($paymentId, $apiContext)->andReturn($approvedPayment); - $approvedPayment->shouldReceive('execute')->with( - \Mockery::on(function (PaymentExecution $actualExecution) use ($payerId) { - return $actualExecution->getPayerId() == $payerId; - }), - \Mockery::on(function (ApiContext $actualApiContext) use ($apiContext) { - return $actualApiContext === $apiContext; - }) - ); - $result = new Payment(); - $paymentMock->shouldReceive('get')->with($paymentId, $payerId)->andReturn($result); + $paymentMock = \Mockery::mock('alias:\PayPal\Api\Payment'); + $approvedPayment = $paymentMock; + $paymentMock->shouldReceive('get')->with($paymentId, $apiContext)->andReturn($approvedPayment); + $approvedPayment->shouldReceive('execute')->with( + \Mockery::on(function (PaymentExecution $actualExecution) use ($payerId) { + return $actualExecution->getPayerId() == $payerId; + }), + \Mockery::on(function (ApiContext $actualApiContext) use ($apiContext) { + return $actualApiContext === $apiContext; + }) + ); + $result = new Payment(); + $paymentMock->shouldReceive('get')->with($paymentId, $payerId)->andReturn($result); - $payment = $operation->handleReturn($paymentId, $payerId); + $payment = $operation->handleReturn($paymentId, $payerId); - Assert::true($payment === $approvedPayment); - } + Assert::true($payment === $approvedPayment); + } - /** - * This method is called after a test is executed. - * - * @return void - */ - protected function tearDown() { - parent::tearDown(); - \Mockery::close(); - } + /** + * This method is called after a test is executed. + * + * @return void + */ + protected function tearDown() + { + parent::tearDown(); + \Mockery::close(); + } } diff --git a/tests/PayPal/Payment/PaymentOperationTest.phpt b/tests/PayPal/Payment/PaymentOperationTest.phpt index 9f9fa42..6dfc357 100644 --- a/tests/PayPal/Payment/PaymentOperationTest.phpt +++ b/tests/PayPal/Payment/PaymentOperationTest.phpt @@ -1,146 +1,149 @@ -config = array( - 'clientId' => 'AUqne4ywvozUaSQ1THTZYKFr88bhtA0SS_fXBoJTfeSTIasDBWuXLiLcFlfmSXRfL-kZ3Z5shvNrT6rP', - 'secretId' => 'EDGPDc3a65JBBY7-IKkNak7aGTVTvY-NhJgfhptegSML58fWjfp89U7UKNgGk9UI-UEZ-btfaE2sGST1' - ); - } - - public function testGetPayment() { - $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', array()); - $context = new PayPalContext($apiContext); - $operation = new DummyPaymentOperation($context); - - $payment = $operation->getPayment(); - Assert::equal('123456789', $payment->transactions[0]->invoice_number); - } - - public function testCreatePayment() { - $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); - $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', array($credentials))->makePartial(); - $context = new PayPalContext($apiContext); - $operation = new DummyPaymentOperation($context); - $payment = $operation->getPayment(); - - $redirectUrls = new RedirectUrls(); - $redirectUrls->setReturnUrl('http://localhost/return'); - $redirectUrls->setCancelUrl('http://localhost/cancel'); - $payment->setRedirectUrls($redirectUrls); - - $result = $operation->createPayment($payment); - Assert::equal('created', $result->getState()); - Assert::equal('http://localhost/return', $payment->getRedirectUrls()->getReturnUrl()); - Assert::notEqual(null, $result->getApprovalLink()); - } - - public function testCreatePaymentGaTracking() { - $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); - $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', array($credentials))->makePartial(); - $context = new PayPalContext($apiContext); - $context->setGaTrackingEnabled(true); - - $operation = new DummyPaymentOperation($context); - $payment = $operation->getPayment(); - - $redirectUrls = new RedirectUrls(); - $redirectUrls->setReturnUrl('http://localhost/return'); - $redirectUrls->setCancelUrl('http://localhost/cancel'); - $payment->setRedirectUrls($redirectUrls); - - $result = $operation->createPayment($payment); - Assert::equal('created', $result->getState()); - Assert::equal('http://localhost/return?utm_nooverride=1', $payment->getRedirectUrls()->getReturnUrl()); - Assert::notEqual(null, $result->getApprovalLink()); - } - - public function testCreatePaymentSimpleOperation() { - $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); - $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', array($credentials))->makePartial(); - $context = new PayPalContext($apiContext); - $context->setCurrency('CZK'); - $operation = new SimplePaymentOperation($context, "Coffee", 10); - $payment = $operation->getPayment(); - - $redirectUrls = new RedirectUrls(); - $redirectUrls->setReturnUrl('http://localhost/return'); - $redirectUrls->setCancelUrl('http://localhost/cancel'); - $payment->setRedirectUrls($redirectUrls); - - $result = $operation->createPayment($payment); - Assert::equal('created', $result->getState()); - Assert::notEqual(null, $result->getApprovalLink()); - } - - public function testCreatePaymentPlainPaymentOperation() { - $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); - $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', array($credentials))->makePartial(); - $context = new PayPalContext($apiContext); - - $item = TransactionHelper::createItem('Coffee', 'EUR', 2, '#123', 20); - $itemList = TransactionHelper::createItemList(array($item)); - $details = TransactionHelper::createDetails(1, 2, 40); - $amount = TransactionHelper::createAmount($details, 43, 'EUR'); - $invoiceNumber = '123456789'; - $description = 'The best coffee ever'; - $transaction = TransactionHelper::createTransaction($amount, $itemList, $invoiceNumber, $description); - - $plainOperation = new PlainPaymentOperation($context, array($transaction)); - /** @var Payment $payment */ - $payment = $plainOperation->getPayment(); - - $redirectUrls = new RedirectUrls(); - $redirectUrls->setReturnUrl('http://localhost/return'); - $redirectUrls->setCancelUrl('http://localhost/cancel'); - $payment->setRedirectUrls($redirectUrls); - - /** @var Payment $result */ - $result = $plainOperation->createPayment($payment); - Assert::equal('created', $result->getState()); - Assert::notEqual(null, $result->getApprovalLink()); - } - - /** - * This method is called after a test is executed. - * - * @return void - */ - protected function tearDown() { - parent::tearDown(); - \Mockery::close(); - } +require_once __DIR__ . '/../Helper/TransactionHelper.php'; + +class PaymentOperationTest extends TestCase +{ + + /** @var array */ + private $config; + + /** + * This method is called before a test is executed. + * + * @return void + */ + protected function setUp() + { + parent::setUp(); + $this->config = [ + 'clientId' => 'AUqne4ywvozUaSQ1THTZYKFr88bhtA0SS_fXBoJTfeSTIasDBWuXLiLcFlfmSXRfL-kZ3Z5shvNrT6rP', + 'secretId' => 'EDGPDc3a65JBBY7-IKkNak7aGTVTvY-NhJgfhptegSML58fWjfp89U7UKNgGk9UI-UEZ-btfaE2sGST1' + ]; + } + + public function testGetPayment() + { + $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', []); + $context = new PayPalContext($apiContext); + $operation = new DummyPaymentOperation($context); + + $payment = $operation->getPayment(); + Assert::equal('123456789', $payment->transactions[0]->invoice_number); + } + + public function testCreatePayment() + { + $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); + $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', [$credentials])->makePartial(); + $context = new PayPalContext($apiContext); + $operation = new DummyPaymentOperation($context); + $payment = $operation->getPayment(); + + $redirectUrls = new RedirectUrls(); + $redirectUrls->setReturnUrl('http://localhost/return'); + $redirectUrls->setCancelUrl('http://localhost/cancel'); + $payment->setRedirectUrls($redirectUrls); + + $result = $operation->createPayment($payment); + Assert::equal('created', $result->getState()); + Assert::equal('http://localhost/return', $payment->getRedirectUrls()->getReturnUrl()); + Assert::notEqual(null, $result->getApprovalLink()); + } + + public function testCreatePaymentGaTracking() + { + $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); + $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', [$credentials])->makePartial(); + $context = new PayPalContext($apiContext); + $context->setGaTrackingEnabled(true); + + $operation = new DummyPaymentOperation($context); + $payment = $operation->getPayment(); + + $redirectUrls = new RedirectUrls(); + $redirectUrls->setReturnUrl('http://localhost/return'); + $redirectUrls->setCancelUrl('http://localhost/cancel'); + $payment->setRedirectUrls($redirectUrls); + + $result = $operation->createPayment($payment); + Assert::equal('created', $result->getState()); + Assert::equal('http://localhost/return?utm_nooverride=1', $payment->getRedirectUrls()->getReturnUrl()); + Assert::notEqual(null, $result->getApprovalLink()); + } + + public function testCreatePaymentSimpleOperation() + { + $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); + $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', [$credentials])->makePartial(); + $context = new PayPalContext($apiContext); + $context->setCurrency('CZK'); + $operation = new SimplePaymentOperation($context, "Coffee", 10); + $payment = $operation->getPayment(); + + $redirectUrls = new RedirectUrls(); + $redirectUrls->setReturnUrl('http://localhost/return'); + $redirectUrls->setCancelUrl('http://localhost/cancel'); + $payment->setRedirectUrls($redirectUrls); + + $result = $operation->createPayment($payment); + Assert::equal('created', $result->getState()); + Assert::notEqual(null, $result->getApprovalLink()); + } + + public function testCreatePaymentPlainPaymentOperation() + { + $credentials = new OAuthTokenCredential($this->config['clientId'], $this->config['secretId']); + $apiContext = \Mockery::mock('\PayPal\Rest\ApiContext', [$credentials])->makePartial(); + $context = new PayPalContext($apiContext); + + $item = TransactionHelper::createItem('Coffee', 'EUR', 2, '#123', 20); + $itemList = TransactionHelper::createItemList([$item]); + $details = TransactionHelper::createDetails(1, 2, 40); + $amount = TransactionHelper::createAmount($details, 43, 'EUR'); + $invoiceNumber = '123456789'; + $description = 'The best coffee ever'; + $transaction = TransactionHelper::createTransaction($amount, $itemList, $invoiceNumber, $description); + + $plainOperation = new PlainPaymentOperation($context, [$transaction]); + /** @var Payment $payment */ + $payment = $plainOperation->getPayment(); + + $redirectUrls = new RedirectUrls(); + $redirectUrls->setReturnUrl('http://localhost/return'); + $redirectUrls->setCancelUrl('http://localhost/cancel'); + $payment->setRedirectUrls($redirectUrls); + + /** @var Payment $result */ + $result = $plainOperation->createPayment($payment); + Assert::equal('created', $result->getState()); + Assert::notEqual(null, $result->getApprovalLink()); + } + + /** + * This method is called after a test is executed. + * + * @return void + */ + protected function tearDown() + { + parent::tearDown(); + \Mockery::close(); + } } diff --git a/tests/PayPal/UI/PaymentControlTest.phpt b/tests/PayPal/UI/PaymentControlTest.phpt index f9bee6a..230493a 100644 --- a/tests/PayPal/UI/PaymentControlTest.phpt +++ b/tests/PayPal/UI/PaymentControlTest.phpt @@ -1,4 +1,4 @@ -operationMock = \Mockery::mock('\MetisFW\PayPal\Payment\PaymentOperation'); - $this->control = \Mockery::mock( - '\MetisFW\PayPal\UI\PaymentControl', - array($this->operationMock)) - ->makePartial() - ->shouldAllowMockingProtectedMethods(); - } - - public function testCheckout() { - $plainPayment = new Payment(); - $this->operationMock->shouldReceive('getPayment')->andReturn($plainPayment); - - $createdPayment = \Mockery::mock('\PayPal\Api\Payment'); - $this->operationMock->shouldReceive('createPayment')->with($plainPayment)->andReturn($createdPayment); - $approvalLink = "www.example.com"; - $createdPayment->shouldReceive('getApprovalLink')->andReturn($approvalLink); - - $this->control->shouldReceive('setPaymentParameters')->once(); - $this->control->shouldReceive('onCheckout'); - $this->control->shouldReceive('getPresenter->redirectUrl')->with($approvalLink); - $this->control->handleCheckout(); - - Assert::true(true); - } - - public function testHandleReturn() { - $paymentId = "123456"; - $payerId = "654321"; - $this->control->shouldReceive('getPresenter->getParameter')->with('paymentId')->andReturn($paymentId); - $this->control->shouldReceive('getPresenter->getParameter')->with('PayerID')->andReturn($payerId); - - $this->operationMock->shouldReceive('handleReturn'); - $this->control->shouldReceive('onSuccess'); - $this->control->handleReturn($paymentId, $payerId); - } - - public function testHandleCancel() { - $this->operationMock->shouldReceive('handleCancel'); - $this->control->shouldReceive('onCancel'); - $this->control->handleCancel(); - } - - public function testSetup() { - Assert::same($this->control->getTemplateFilePath(), $this->control->getDefaultTemplateFilePath()); - $templateFilePath = '/foo/path.latte'; - $this->control->setTemplateFilePath($templateFilePath); - Assert::same($this->control->getTemplateFilePath(), $templateFilePath); - } - - /** - * This method is called after a test is executed. - * - * @return void - */ - protected function tearDown() { - parent::tearDown(); - \Mockery::close(); - } +require_once __DIR__ . '/../../bootstrap.php'; + +class PaymentControlTest extends TestCase +{ + + /** + * @var MockInterface + */ + private $operationMock; + + /** + * @var PaymentControl + */ + private $control; + + public function setUp() + { + parent::setUp(); + + $this->operationMock = \Mockery::mock('\MetisFW\PayPal\Payment\PaymentOperation'); + $this->control = \Mockery::mock('\MetisFW\PayPal\UI\PaymentControl', [$this->operationMock]) + ->makePartial() + ->shouldAllowMockingProtectedMethods(); + } + + public function testCheckout() + { + $plainPayment = new Payment(); + $this->operationMock->shouldReceive('getPayment')->andReturn($plainPayment); + + $createdPayment = \Mockery::mock('\PayPal\Api\Payment'); + $this->operationMock->shouldReceive('createPayment')->with($plainPayment)->andReturn($createdPayment); + $approvalLink = "www.example.com"; + $createdPayment->shouldReceive('getApprovalLink')->andReturn($approvalLink); + + $this->control->shouldReceive('setPaymentParameters')->once(); + $this->control->shouldReceive('onCheckout'); + $this->control->shouldReceive('getPresenter->redirectUrl')->with($approvalLink); + $this->control->handleCheckout(); + + Assert::true(true); + } + + public function testHandleReturn() + { + $paymentId = "123456"; + $payerId = "654321"; + $this->control->shouldReceive('getPresenter->getParameter')->with('paymentId')->andReturn($paymentId); + $this->control->shouldReceive('getPresenter->getParameter')->with('PayerID')->andReturn($payerId); + + $this->operationMock->shouldReceive('handleReturn'); + $this->control->shouldReceive('onSuccess'); + $this->control->handleReturn($paymentId, $payerId); + } + + public function testHandleCancel() + { + $this->operationMock->shouldReceive('handleCancel'); + $this->control->shouldReceive('onCancel'); + $this->control->handleCancel(); + } + + public function testSetup() + { + Assert::same($this->control->getTemplateFilePath(), $this->control->getDefaultTemplateFilePath()); + $templateFilePath = '/foo/path.latte'; + $this->control->setTemplateFilePath($templateFilePath); + Assert::same($this->control->getTemplateFilePath(), $templateFilePath); + } + + /** + * This method is called after a test is executed. + * + * @return void + */ + protected function tearDown() + { + parent::tearDown(); + \Mockery::close(); + } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 4b79e4d..2f0511d 100755 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,4 +1,4 @@ -run(); } -} \ No newline at end of file +} diff --git a/tests/paypal.config.neon b/tests/paypal.config.neon index d0cdd10..a71459a 100644 --- a/tests/paypal.config.neon +++ b/tests/paypal.config.neon @@ -4,10 +4,9 @@ payPal: currency: EUR sdkConfig: mode: sandbox - log.Enabled: true + log.LogEnabled: true log.FileName: './tmp/PayPal.log' - log.LogLevel: DEBUG - validation.level: log + log.LogLevel: debug cache.enabled: true # 'http.CURLOPT_CONNECTTIMEOUT' => 30 # 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'/