From 4699c5db7ecf0df481537fd887a0cb4984fe5b11 Mon Sep 17 00:00:00 2001 From: Olivier Bellone Date: Fri, 23 Aug 2019 10:22:18 -0700 Subject: [PATCH] Modernize exceptions --- examples/oauth.php | 4 +- init.php | 44 ++-- lib/Account.php | 36 ++- lib/AlipayAccount.php | 10 +- lib/ApiOperations/All.php | 4 +- lib/ApiOperations/Create.php | 2 + lib/ApiOperations/Delete.php | 2 + lib/ApiOperations/NestedResource.php | 10 + lib/ApiOperations/Request.php | 8 +- lib/ApiOperations/Retrieve.php | 2 + lib/ApiOperations/Update.php | 4 + lib/ApiRequestor.php | 113 +++------ lib/ApiResource.php | 2 +- lib/ApplicationFee.php | 8 + lib/ApplicationFeeRefund.php | 2 +- lib/Balance.php | 2 + lib/BankAccount.php | 12 +- lib/Capability.php | 10 +- lib/Card.php | 10 +- lib/Charge.php | 4 +- lib/Collection.php | 6 +- lib/CreditNote.php | 2 + lib/Customer.php | 23 ++ lib/CustomerBalanceTransaction.php | 10 +- lib/Dispute.php | 2 + lib/EphemeralKey.php | 5 +- lib/Error/Api.php | 14 -- lib/Error/ApiConnection.php | 13 -- lib/Error/Authentication.php | 12 - lib/Error/Base.php | 95 -------- lib/Error/Card.php | 39 ---- lib/Error/Idempotency.php | 12 - lib/Error/InvalidRequest.php | 31 --- lib/Error/OAuth/InvalidClient.php | 14 -- lib/Error/OAuth/InvalidGrant.php | 14 -- lib/Error/OAuth/InvalidRequest.php | 13 -- lib/Error/OAuth/InvalidScope.php | 12 - lib/Error/OAuth/OAuthBase.php | 39 ---- lib/Error/OAuth/UnsupportedGrantType.php | 12 - lib/Error/OAuth/UnsupportedResponseType.php | 12 - lib/Error/Permission.php | 12 - lib/Error/RateLimit.php | 13 -- lib/Error/SignatureVerification.php | 27 --- lib/Exception/ApiConnectionException.php | 14 ++ lib/Exception/ApiErrorException.php | 215 ++++++++++++++++++ lib/Exception/AuthenticationException.php | 13 ++ lib/Exception/BadMethodCallException.php | 7 + lib/Exception/CardException.php | 86 +++++++ lib/Exception/ExceptionInterface.php | 26 +++ lib/Exception/IdempotencyException.php | 13 ++ lib/Exception/InvalidArgumentException.php | 7 + lib/Exception/InvalidRequestException.php | 62 +++++ lib/Exception/OAuth/ExceptionInterface.php | 10 + .../OAuth/InvalidClientException.php | 14 ++ lib/Exception/OAuth/InvalidGrantException.php | 15 ++ .../OAuth/InvalidRequestException.php | 13 ++ lib/Exception/OAuth/InvalidScopeException.php | 12 + lib/Exception/OAuth/OAuthErrorException.php | 19 ++ .../OAuth/UnknownOAuthErrorException.php | 14 ++ .../OAuth/UnsupportedGrantTypeException.php | 13 ++ .../UnsupportedResponseTypeException.php | 13 ++ lib/Exception/PermissionException.php | 13 ++ lib/Exception/RateLimitException.php | 14 ++ .../SignatureVerificationException.php | 76 +++++++ lib/Exception/UnexpectedValueException.php | 7 + lib/Exception/UnknownApiErrorException.php | 14 ++ lib/File.php | 2 + lib/HttpClient/ClientInterface.php | 4 +- lib/HttpClient/CurlClient.php | 12 +- lib/Invoice.php | 12 + lib/Issuing/Authorization.php | 4 + lib/Issuing/Card.php | 2 + lib/OAuth.php | 6 +- lib/Order.php | 4 + lib/PaymentIntent.php | 6 + lib/PaymentMethod.php | 4 + lib/Payout.php | 2 + lib/Person.php | 10 +- lib/Review.php | 2 + lib/SetupIntent.php | 4 + lib/Source.php | 11 +- lib/StripeObject.php | 8 +- lib/Subscription.php | 4 + lib/SubscriptionItem.php | 4 + lib/SubscriptionSchedule.php | 4 + lib/TaxId.php | 9 +- lib/Topup.php | 2 + lib/Transfer.php | 8 + lib/TransferReversal.php | 4 +- lib/Util/DefaultLogger.php | 2 +- lib/Util/RequestOptions.php | 4 +- lib/Webhook.php | 16 +- lib/WebhookSignature.php | 32 +-- tests/Stripe/AlipayAccountTest.php | 4 +- tests/Stripe/ApiRequestorTest.php | 43 ++-- tests/Stripe/BankAccountTest.php | 4 +- tests/Stripe/CapabilityTest.php | 4 +- tests/Stripe/CardTest.php | 4 +- tests/Stripe/CollectionTest.php | 2 +- .../Error/SignatureVerificationTest.php | 12 - .../ApiErrorExceptionTest.php} | 12 +- .../OAuth/OAuthErrorExceptionTest.php} | 13 +- .../SignatureVerificationExceptionTest.php | 14 ++ tests/Stripe/HttpClient/CurlClientTest.php | 2 +- tests/Stripe/OAuthTest.php | 2 +- tests/Stripe/PersonTest.php | 4 +- tests/Stripe/SourceTest.php | 2 +- tests/Stripe/Util/RequestOptionsTest.php | 2 +- tests/Stripe/WebhookTest.php | 14 +- 109 files changed, 1096 insertions(+), 635 deletions(-) delete mode 100644 lib/Error/Api.php delete mode 100644 lib/Error/ApiConnection.php delete mode 100644 lib/Error/Authentication.php delete mode 100644 lib/Error/Base.php delete mode 100644 lib/Error/Card.php delete mode 100644 lib/Error/Idempotency.php delete mode 100644 lib/Error/InvalidRequest.php delete mode 100644 lib/Error/OAuth/InvalidClient.php delete mode 100644 lib/Error/OAuth/InvalidGrant.php delete mode 100644 lib/Error/OAuth/InvalidRequest.php delete mode 100644 lib/Error/OAuth/InvalidScope.php delete mode 100644 lib/Error/OAuth/OAuthBase.php delete mode 100644 lib/Error/OAuth/UnsupportedGrantType.php delete mode 100644 lib/Error/OAuth/UnsupportedResponseType.php delete mode 100644 lib/Error/Permission.php delete mode 100644 lib/Error/RateLimit.php delete mode 100644 lib/Error/SignatureVerification.php create mode 100644 lib/Exception/ApiConnectionException.php create mode 100644 lib/Exception/ApiErrorException.php create mode 100644 lib/Exception/AuthenticationException.php create mode 100644 lib/Exception/BadMethodCallException.php create mode 100644 lib/Exception/CardException.php create mode 100644 lib/Exception/ExceptionInterface.php create mode 100644 lib/Exception/IdempotencyException.php create mode 100644 lib/Exception/InvalidArgumentException.php create mode 100644 lib/Exception/InvalidRequestException.php create mode 100644 lib/Exception/OAuth/ExceptionInterface.php create mode 100644 lib/Exception/OAuth/InvalidClientException.php create mode 100644 lib/Exception/OAuth/InvalidGrantException.php create mode 100644 lib/Exception/OAuth/InvalidRequestException.php create mode 100644 lib/Exception/OAuth/InvalidScopeException.php create mode 100644 lib/Exception/OAuth/OAuthErrorException.php create mode 100644 lib/Exception/OAuth/UnknownOAuthErrorException.php create mode 100644 lib/Exception/OAuth/UnsupportedGrantTypeException.php create mode 100644 lib/Exception/OAuth/UnsupportedResponseTypeException.php create mode 100644 lib/Exception/PermissionException.php create mode 100644 lib/Exception/RateLimitException.php create mode 100644 lib/Exception/SignatureVerificationException.php create mode 100644 lib/Exception/UnexpectedValueException.php create mode 100644 lib/Exception/UnknownApiErrorException.php delete mode 100644 tests/Stripe/Error/SignatureVerificationTest.php rename tests/Stripe/{Error/BaseTest.php => Exception/ApiErrorExceptionTest.php} (76%) rename tests/Stripe/{Error/OAuth/OAuthBaseTest.php => Exception/OAuth/OAuthErrorExceptionTest.php} (78%) create mode 100644 tests/Stripe/Exception/SignatureVerificationExceptionTest.php diff --git a/examples/oauth.php b/examples/oauth.php index 3a6291129..9280c3409 100644 --- a/examples/oauth.php +++ b/examples/oauth.php @@ -15,7 +15,7 @@ 'grant_type' => 'authorization_code', 'code' => $code, ]); - } catch (\Stripe\Error\OAuth\OAuthBase $e) { + } catch (\Stripe\Exception\OAuth\OAuthErrorException $e) { exit("Error: " . $e->getMessage()); } @@ -38,7 +38,7 @@ \Stripe\OAuth::deauthorize([ 'stripe_user_id' => $accountId, ]); - } catch (\Stripe\Error\OAuth\OAuthBase $e) { + } catch (\Stripe\Exception\OAuth\OAuthErrorException $e) { exit("Error: " . $e->getMessage()); } diff --git a/init.php b/init.php index 2822d0c8d..5f3c0b904 100644 --- a/init.php +++ b/init.php @@ -16,26 +16,32 @@ require(dirname(__FILE__) . '/lib/HttpClient/ClientInterface.php'); require(dirname(__FILE__) . '/lib/HttpClient/CurlClient.php'); -// Errors -require(dirname(__FILE__) . '/lib/Error/Base.php'); -require(dirname(__FILE__) . '/lib/Error/Api.php'); -require(dirname(__FILE__) . '/lib/Error/ApiConnection.php'); -require(dirname(__FILE__) . '/lib/Error/Authentication.php'); -require(dirname(__FILE__) . '/lib/Error/Card.php'); -require(dirname(__FILE__) . '/lib/Error/Idempotency.php'); -require(dirname(__FILE__) . '/lib/Error/InvalidRequest.php'); -require(dirname(__FILE__) . '/lib/Error/Permission.php'); -require(dirname(__FILE__) . '/lib/Error/RateLimit.php'); -require(dirname(__FILE__) . '/lib/Error/SignatureVerification.php'); +// Exceptions +require(dirname(__FILE__) . '/lib/Exception/ExceptionInterface.php'); +require(dirname(__FILE__) . '/lib/Exception/ApiErrorException.php'); +require(dirname(__FILE__) . '/lib/Exception/ApiConnectionException.php'); +require(dirname(__FILE__) . '/lib/Exception/AuthenticationException.php'); +require(dirname(__FILE__) . '/lib/Exception/BadMethodCallException.php'); +require(dirname(__FILE__) . '/lib/Exception/CardException.php'); +require(dirname(__FILE__) . '/lib/Exception/IdempotencyException.php'); +require(dirname(__FILE__) . '/lib/Exception/InvalidArgumentException.php'); +require(dirname(__FILE__) . '/lib/Exception/InvalidRequestException.php'); +require(dirname(__FILE__) . '/lib/Exception/PermissionException.php'); +require(dirname(__FILE__) . '/lib/Exception/RateLimitException.php'); +require(dirname(__FILE__) . '/lib/Exception/SignatureVerificationException.php'); +require(dirname(__FILE__) . '/lib/Exception/UnexpectedValueException.php'); +require(dirname(__FILE__) . '/lib/Exception/UnknownApiErrorException.php'); -// OAuth errors -require(dirname(__FILE__) . '/lib/Error/OAuth/OAuthBase.php'); -require(dirname(__FILE__) . '/lib/Error/OAuth/InvalidClient.php'); -require(dirname(__FILE__) . '/lib/Error/OAuth/InvalidGrant.php'); -require(dirname(__FILE__) . '/lib/Error/OAuth/InvalidRequest.php'); -require(dirname(__FILE__) . '/lib/Error/OAuth/InvalidScope.php'); -require(dirname(__FILE__) . '/lib/Error/OAuth/UnsupportedGrantType.php'); -require(dirname(__FILE__) . '/lib/Error/OAuth/UnsupportedResponseType.php'); +// OAuth exceptions +require(dirname(__FILE__) . '/lib/Exception/OAuth/ExceptionInterface.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/OAuthErrorException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/InvalidClientException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/InvalidGrantException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/InvalidRequestException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/InvalidScopeException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/UnknownOAuthErrorException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/UnsupportedGrantTypeException.php'); +require(dirname(__FILE__) . '/lib/Exception/OAuth/UnsupportedResponseTypeException.php'); // API operations require(dirname(__FILE__) . '/lib/ApiOperations/All.php'); diff --git a/lib/Account.php b/lib/Account.php index 4993ca354..91cd2fa28 100644 --- a/lib/Account.php +++ b/lib/Account.php @@ -103,6 +103,8 @@ public function instanceUrl() * options array containing an `id` key. * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Account */ public static function retrieve($id = null, $opts = null) @@ -118,6 +120,8 @@ public static function retrieve($id = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Account The rejected account. */ public function reject($params = null, $opts = null) @@ -132,6 +136,8 @@ public function reject($params = null, $opts = null) * @param array|null $clientId * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return StripeObject Object containing the response from the API. */ public function deauthorize($clientId = null, $opts = null) @@ -156,6 +162,8 @@ public function deauthorize($clientId = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Capability */ public static function retrieveCapability($id, $capabilityId, $params = null, $opts = null) @@ -181,6 +189,8 @@ public static function updateCapability($id, $capabilityId, $params = null, $opt * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of capabilities. */ public static function allCapabilities($id, $params = null, $opts = null) @@ -193,6 +203,8 @@ public static function allCapabilities($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return BankAccount|Card */ public static function createExternalAccount($id, $params = null, $opts = null) @@ -206,6 +218,8 @@ public static function createExternalAccount($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return BankAccount|Card */ public static function retrieveExternalAccount($id, $externalAccountId, $params = null, $opts = null) @@ -219,6 +233,8 @@ public static function retrieveExternalAccount($id, $externalAccountId, $params * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return BankAccount|Card */ public static function updateExternalAccount($id, $externalAccountId, $params = null, $opts = null) @@ -232,6 +248,8 @@ public static function updateExternalAccount($id, $externalAccountId, $params = * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return BankAccount|Card */ public static function deleteExternalAccount($id, $externalAccountId, $params = null, $opts = null) @@ -244,6 +262,8 @@ public static function deleteExternalAccount($id, $externalAccountId, $params = * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of external accounts (BankAccount or Card). */ public static function allExternalAccounts($id, $params = null, $opts = null) @@ -256,6 +276,8 @@ public static function allExternalAccounts($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return LoginLink */ public static function createLoginLink($id, $params = null, $opts = null) @@ -267,6 +289,8 @@ public static function createLoginLink($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of persons. */ public function persons($params = null, $options = null) @@ -283,6 +307,8 @@ public function persons($params = null, $options = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Person */ public static function createPerson($id, $params = null, $opts = null) @@ -296,6 +322,8 @@ public static function createPerson($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Person */ public static function retrievePerson($id, $personId, $params = null, $opts = null) @@ -309,6 +337,8 @@ public static function retrievePerson($id, $personId, $params = null, $opts = nu * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Person */ public static function updatePerson($id, $personId, $params = null, $opts = null) @@ -322,6 +352,8 @@ public static function updatePerson($id, $personId, $params = null, $opts = null * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Person */ public static function deletePerson($id, $personId, $params = null, $opts = null) @@ -334,6 +366,8 @@ public static function deletePerson($id, $personId, $params = null, $opts = null * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of persons. */ public static function allPersons($id, $params = null, $opts = null) @@ -370,7 +404,7 @@ private function serializeAdditionalOwners($legalEntity, $additionalOwners) $originalValue = []; } if (($originalValue) && (count($originalValue) > count($additionalOwners))) { - throw new \InvalidArgumentException( + throw new Exception\InvalidArgumentException( "You cannot delete an item from an array, you must instead set a new array" ); } diff --git a/lib/AlipayAccount.php b/lib/AlipayAccount.php index fbb13103b..1dcc09517 100644 --- a/lib/AlipayAccount.php +++ b/lib/AlipayAccount.php @@ -29,7 +29,7 @@ public function instanceUrl() $path = 'sources'; } else { $msg = "Alipay accounts cannot be accessed without a customer ID."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\UnexpectedValueException($msg); } $parentExtn = urlencode(Util\Util::utf8($parent)); $extn = urlencode(Util\Util::utf8($this['id'])); @@ -40,7 +40,7 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException * * @deprecated Alipay accounts are deprecated. Please use the sources API instead. * @link https://stripe.com/docs/sources/alipay @@ -50,7 +50,7 @@ public static function retrieve($_id, $_opts = null) $msg = "Alipay accounts cannot be retrieved without a customer ID. " . "Retrieve an Alipay account using `Customer::retrieveSource(" . "'customer_id', 'alipay_account_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg); } /** @@ -58,7 +58,7 @@ public static function retrieve($_id, $_opts = null) * @param array|null $_params * @param array|string|null $_options * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException * * @deprecated Alipay accounts are deprecated. Please use the sources API instead. * @link https://stripe.com/docs/sources/alipay @@ -68,6 +68,6 @@ public static function update($_id, $_params = null, $_options = null) $msg = "Alipay accounts cannot be updated without a customer ID. " . "Update an Alipay account using `Customer::updateSource(" . "'customer_id', 'alipay_account_id', \$updateParams)`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg); } } diff --git a/lib/ApiOperations/All.php b/lib/ApiOperations/All.php index e59e80b41..d7ee2aa04 100644 --- a/lib/ApiOperations/All.php +++ b/lib/ApiOperations/All.php @@ -13,6 +13,8 @@ trait All * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return \Stripe\Collection of ApiResources */ public static function all($params = null, $opts = null) @@ -23,7 +25,7 @@ public static function all($params = null, $opts = null) list($response, $opts) = static::_staticRequest('get', $url, $params, $opts); $obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts); if (!($obj instanceof \Stripe\Collection)) { - throw new \Stripe\Error\Api( + throw new \Stripe\Exception\UnexpectedValueException( 'Expected type ' . \Stripe\Collection::class . ', got "' . get_class($obj) . '" instead.' ); } diff --git a/lib/ApiOperations/Create.php b/lib/ApiOperations/Create.php index 4ec66703f..8dc3975ac 100644 --- a/lib/ApiOperations/Create.php +++ b/lib/ApiOperations/Create.php @@ -13,6 +13,8 @@ trait Create * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return static The created resource. */ public static function create($params = null, $options = null) diff --git a/lib/ApiOperations/Delete.php b/lib/ApiOperations/Delete.php index 9581765b8..62de777a6 100644 --- a/lib/ApiOperations/Delete.php +++ b/lib/ApiOperations/Delete.php @@ -13,6 +13,8 @@ trait Delete * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return static The deleted resource. */ public function delete($params = null, $opts = null) diff --git a/lib/ApiOperations/NestedResource.php b/lib/ApiOperations/NestedResource.php index 212235436..a3cabfd15 100644 --- a/lib/ApiOperations/NestedResource.php +++ b/lib/ApiOperations/NestedResource.php @@ -49,6 +49,8 @@ protected static function _nestedResourceUrl($id, $nestedPath, $nestedId = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return \Stripe\StripeObject */ protected static function _createNestedResource($id, $nestedPath, $params = null, $options = null) @@ -64,6 +66,8 @@ protected static function _createNestedResource($id, $nestedPath, $params = null * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return \Stripe\StripeObject */ protected static function _retrieveNestedResource($id, $nestedPath, $nestedId, $params = null, $options = null) @@ -79,6 +83,8 @@ protected static function _retrieveNestedResource($id, $nestedPath, $nestedId, $ * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return \Stripe\StripeObject */ protected static function _updateNestedResource($id, $nestedPath, $nestedId, $params = null, $options = null) @@ -94,6 +100,8 @@ protected static function _updateNestedResource($id, $nestedPath, $nestedId, $pa * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return \Stripe\StripeObject */ protected static function _deleteNestedResource($id, $nestedPath, $nestedId, $params = null, $options = null) @@ -108,6 +116,8 @@ protected static function _deleteNestedResource($id, $nestedPath, $nestedId, $pa * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return \Stripe\StripeObject */ protected static function _allNestedResources($id, $nestedPath, $params = null, $options = null) diff --git a/lib/ApiOperations/Request.php b/lib/ApiOperations/Request.php index dd048dc5f..1ee09999d 100644 --- a/lib/ApiOperations/Request.php +++ b/lib/ApiOperations/Request.php @@ -12,7 +12,7 @@ trait Request /** * @param array|null|mixed $params The list of parameters to validate * - * @throws \Stripe\Error\Api if $params exists and is not an array + * @throws \Stripe\Exception\InvalidArgumentException if $params exists and is not an array */ protected static function _validateParams($params = null) { @@ -21,7 +21,7 @@ protected static function _validateParams($params = null) . "method calls. (HINT: an example call to create a charge " . "would be: \"Stripe\\Charge::create(['amount' => 100, " . "'currency' => 'usd', 'source' => 'tok_1234'])\")"; - throw new \Stripe\Error\Api($message); + throw new \Stripe\Exception\InvalidArgumentException($message); } } @@ -31,6 +31,8 @@ protected static function _validateParams($params = null) * @param array $params list of parameters for the request * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return array tuple containing (the JSON response, $options) */ protected function _request($method, $url, $params = [], $options = null) @@ -47,6 +49,8 @@ protected function _request($method, $url, $params = [], $options = null) * @param array $params list of parameters for the request * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return array tuple containing (the JSON response, $options) */ protected static function _staticRequest($method, $url, $params, $options) diff --git a/lib/ApiOperations/Retrieve.php b/lib/ApiOperations/Retrieve.php index ed52296b7..7e5d4206f 100644 --- a/lib/ApiOperations/Retrieve.php +++ b/lib/ApiOperations/Retrieve.php @@ -15,6 +15,8 @@ trait Retrieve * or an options array containing an `id` key. * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return static */ public static function retrieve($id, $opts = null) diff --git a/lib/ApiOperations/Update.php b/lib/ApiOperations/Update.php index e17db280f..1560b7f43 100644 --- a/lib/ApiOperations/Update.php +++ b/lib/ApiOperations/Update.php @@ -15,6 +15,8 @@ trait Update * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return static The updated resource. */ public static function update($id, $params = null, $opts = null) @@ -31,6 +33,8 @@ public static function update($id, $params = null, $opts = null) /** * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return static The saved resource. */ public function save($opts = null) diff --git a/lib/ApiRequestor.php b/lib/ApiRequestor.php index 356e3500d..eb5e0e1b9 100644 --- a/lib/ApiRequestor.php +++ b/lib/ApiRequestor.php @@ -100,22 +100,9 @@ private static function _encodeObjects($d) * @param array|null $params * @param array|null $headers * - * @return array An array whose first element is an API response and second - * element is the API key used to make the request. - * @throws Error\Api - * @throws Error\Authentication - * @throws Error\Card - * @throws Error\InvalidRequest - * @throws Error\OAuth\InvalidClient - * @throws Error\OAuth\InvalidGrant - * @throws Error\OAuth\InvalidRequest - * @throws Error\OAuth\InvalidScope - * @throws Error\OAuth\UnsupportedGrantType - * @throws Error\OAuth\UnsupportedResponseType - * @throws Error\Permission - * @throws Error\RateLimit - * @throws Error\Idempotency - * @throws Error\ApiConnection + * @return array tuple containing (ApiReponse, API key) + * + * @throws Exception\ApiErrorException */ public function request($method, $url, $params = null, $headers = null) { @@ -134,33 +121,15 @@ public function request($method, $url, $params = null, $headers = null) * @param array $rheaders * @param array $resp * - * @throws Error\InvalidRequest if the error is caused by the user. - * @throws Error\Authentication if the error is caused by a lack of - * permissions. - * @throws Error\Permission if the error is caused by insufficient - * permissions. - * @throws Error\Card if the error is the error code is 402 (payment - * required) - * @throws Error\InvalidRequest if the error is caused by the user. - * @throws Error\Idempotency if the error is caused by an idempotency key. - * @throws Error\OAuth\InvalidClient - * @throws Error\OAuth\InvalidGrant - * @throws Error\OAuth\InvalidRequest - * @throws Error\OAuth\InvalidScope - * @throws Error\OAuth\UnsupportedGrantType - * @throws Error\OAuth\UnsupportedResponseType - * @throws Error\Permission if the error is caused by insufficient - * permissions. - * @throws Error\RateLimit if the error is caused by too many requests - * hitting the API. - * @throws Error\Api otherwise. + * @throws Exception\UnexpectedValueException + * @throws Exception\ApiErrorException */ public function handleErrorResponse($rbody, $rcode, $rheaders, $resp) { if (!is_array($resp) || !isset($resp['error'])) { $msg = "Invalid response object from API: $rbody " . "(HTTP response code was $rcode)"; - throw new Error\Api($msg, $rcode, $rbody, $resp, $rheaders); + throw new Exception\UnexpectedValueException($msg, $rcode, $rbody, $resp, $rheaders); } $errorData = $resp['error']; @@ -185,7 +154,7 @@ public function handleErrorResponse($rbody, $rcode, $rheaders, $resp) * @param array $resp * @param array $errorData * - * @return Error\RateLimit|Error\Idempotency|Error\InvalidRequest|Error\Authentication|Error\Card|Error\Permission|Error\Api + * @return Exception\ApiErrorException */ private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData) { @@ -200,25 +169,25 @@ private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $err // 'rate_limit' code is deprecated, but left here for backwards compatibility // for API versions earlier than 2015-09-08 if ($code == 'rate_limit') { - return new Error\RateLimit($msg, $param, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param); } if ($type == 'idempotency_error') { - return new Error\Idempotency($msg, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\IdempotencyException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code); } // no break case 404: - return new Error\InvalidRequest($msg, $param, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\InvalidRequestException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param); case 401: - return new Error\Authentication($msg, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\AuthenticationException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code); case 402: - return new Error\Card($msg, $param, $code, $rcode, $rbody, $resp, $rheaders, $declineCode); + return Exception\CardException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $declineCode, $param); case 403: - return new Error\Permission($msg, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\PermissionException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code); case 429: - return new Error\RateLimit($msg, $param, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param); default: - return new Error\Api($msg, $rcode, $rbody, $resp, $rheaders, $code); + return Exception\UnknownApiErrorException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code); } } @@ -231,7 +200,7 @@ private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $err * @param array $resp * @param string $errorCode * - * @return null|Error\OAuth\InvalidClient|Error\OAuth\InvalidGrant|Error\OAuth\InvalidRequest|Error\OAuth\InvalidScope|Error\OAuth\UnsupportedGrantType|Error\OAuth\UnsupportedResponseType + * @return Exception\OAuth\OAuthErrorException */ private static function _specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorCode) { @@ -239,20 +208,20 @@ private static function _specificOAuthError($rbody, $rcode, $rheaders, $resp, $e switch ($errorCode) { case 'invalid_client': - return new Error\OAuth\InvalidClient($errorCode, $description, $rcode, $rbody, $resp, $rheaders); + return Exception\OAuth\InvalidClientException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); case 'invalid_grant': - return new Error\OAuth\InvalidGrant($errorCode, $description, $rcode, $rbody, $resp, $rheaders); + return Exception\OAuth\InvalidGrantException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); case 'invalid_request': - return new Error\OAuth\InvalidRequest($errorCode, $description, $rcode, $rbody, $resp, $rheaders); + return Exception\OAuth\InvalidRequestException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); case 'invalid_scope': - return new Error\OAuth\InvalidScope($errorCode, $description, $rcode, $rbody, $resp, $rheaders); + return Exception\OAuth\InvalidScopeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); case 'unsupported_grant_type': - return new Error\OAuth\UnsupportedGrantType($errorCode, $description, $rcode, $rbody, $resp, $rheaders); + return Exception\OAuth\UnsupportedGrantTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); case 'unsupported_response_type': - return new Error\OAuth\UnsupportedResponseType($errorCode, $description, $rcode, $rbody, $resp, $rheaders); + return Exception\OAuth\UnsupportedResponseTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); + default: + return Exception\OAuth\UnknownOAuthErrorException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode); } - - return null; } /** @@ -324,9 +293,8 @@ private static function _defaultHeaders($apiKey, $clientInfo = null) * @param array $headers * * @return array - * @throws Error\Api - * @throws Error\ApiConnection - * @throws Error\Authentication + * + * @throws Exception\AuthenticationException */ private function _requestRaw($method, $url, $params, $headers) { @@ -340,7 +308,7 @@ private function _requestRaw($method, $url, $params, $headers) . '"Stripe::setApiKey()". You can generate API keys from ' . 'the Stripe web interface. See https://stripe.com/api for ' . 'details, or email support@stripe.com if you have any questions.'; - throw new Error\Authentication($msg); + throw new Exception\AuthenticationException($msg); } // Clients can supply arbitrary additional keys to be included in the @@ -413,19 +381,20 @@ private function _requestRaw($method, $url, $params, $headers) * @param resource $resource * * @return \CURLFile|string - * @throws Error\Api + * + * @throws Exception\InvalidArgumentException */ private function _processResourceParam($resource) { if (get_resource_type($resource) !== 'stream') { - throw new Error\Api( + throw new Exception\InvalidArgumentException( 'Attempted to upload a resource that is not a stream' ); } $metaData = stream_get_meta_data($resource); if ($metaData['wrapper_type'] !== 'plainfile') { - throw new Error\Api( + throw new Exception\InvalidArgumentException( 'Only plainfile resource streams are supported' ); } @@ -439,20 +408,10 @@ private function _processResourceParam($resource) * @param int $rcode * @param array $rheaders * - * @return mixed - * @throws Error\Api - * @throws Error\Authentication - * @throws Error\Card - * @throws Error\InvalidRequest - * @throws Error\OAuth\InvalidClient - * @throws Error\OAuth\InvalidGrant - * @throws Error\OAuth\InvalidRequest - * @throws Error\OAuth\InvalidScope - * @throws Error\OAuth\UnsupportedGrantType - * @throws Error\OAuth\UnsupportedResponseType - * @throws Error\Permission - * @throws Error\RateLimit - * @throws Error\Idempotency + * @return array + * + * @throws Exception\UnexpectedValueException + * @throws Exception\ApiErrorException */ private function _interpretResponse($rbody, $rcode, $rheaders) { @@ -461,7 +420,7 @@ private function _interpretResponse($rbody, $rcode, $rheaders) if ($resp === null && $jsonError !== JSON_ERROR_NONE) { $msg = "Invalid response body from API: $rbody " . "(HTTP response code was $rcode, json_last_error() was $jsonError)"; - throw new Error\Api($msg, $rcode, $rbody); + throw new Exception\UnexpectedValueException($msg, $rcode, $rbody); } if ($rcode < 200 || $rcode >= 300) { diff --git a/lib/ApiResource.php b/lib/ApiResource.php index fe5943216..725615aaa 100644 --- a/lib/ApiResource.php +++ b/lib/ApiResource.php @@ -94,7 +94,7 @@ public static function resourceUrl($id) $class = get_called_class(); $message = "Could not determine which URL to request: " . "$class instance has invalid ID: $id"; - throw new Error\InvalidRequest($message, null); + throw new Exception\UnexpectedValueException($message); } $id = Util\Util::utf8($id); $base = static::classUrl(); diff --git a/lib/ApplicationFee.php b/lib/ApplicationFee.php index 78f776c0a..8c1f95708 100644 --- a/lib/ApplicationFee.php +++ b/lib/ApplicationFee.php @@ -37,6 +37,8 @@ class ApplicationFee extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApplicationFeeRefund */ public static function createRefund($id, $params = null, $opts = null) @@ -50,6 +52,8 @@ public static function createRefund($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApplicationFeeRefund */ public static function retrieveRefund($id, $refundId, $params = null, $opts = null) @@ -63,6 +67,8 @@ public static function retrieveRefund($id, $refundId, $params = null, $opts = nu * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApplicationFeeRefund */ public static function updateRefund($id, $refundId, $params = null, $opts = null) @@ -75,6 +81,8 @@ public static function updateRefund($id, $refundId, $params = null, $opts = null * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of refunds. */ public static function allRefunds($id, $params = null, $opts = null) diff --git a/lib/ApplicationFeeRefund.php b/lib/ApplicationFeeRefund.php index b242f2024..77ba0ccd7 100644 --- a/lib/ApplicationFeeRefund.php +++ b/lib/ApplicationFeeRefund.php @@ -32,7 +32,7 @@ public function instanceUrl() $id = $this['id']; $fee = $this['fee']; if (!$id) { - throw new Error\InvalidRequest( + throw new Exception\UnexpectedValueException( "Could not determine which URL to request: " . "class instance has invalid ID: $id", null diff --git a/lib/Balance.php b/lib/Balance.php index b99871adb..dfa1d3aa9 100644 --- a/lib/Balance.php +++ b/lib/Balance.php @@ -20,6 +20,8 @@ class Balance extends SingletonApiResource /** * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Balance */ public static function retrieve($opts = null) diff --git a/lib/BankAccount.php b/lib/BankAccount.php index ca019c2c7..ec34206ed 100644 --- a/lib/BankAccount.php +++ b/lib/BankAccount.php @@ -56,7 +56,7 @@ public function instanceUrl() $path = 'external_accounts'; } else { $msg = "Bank accounts cannot be accessed without a customer ID or account ID."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\UnexpectedValueException($msg, null); } $parentExtn = urlencode(Util\Util::utf8($parent)); $extn = urlencode(Util\Util::utf8($this['id'])); @@ -67,7 +67,7 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function retrieve($_id, $_opts = null) { @@ -76,7 +76,7 @@ public static function retrieve($_id, $_opts = null) "`Customer::retrieveSource('customer_id', " . "'bank_account_id')` or `Account::retrieveExternalAccount(" . "'account_id', 'bank_account_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } /** @@ -84,7 +84,7 @@ public static function retrieve($_id, $_opts = null) * @param array|null $_params * @param array|string|null $_options * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function update($_id, $_params = null, $_options = null) { @@ -93,12 +93,14 @@ public static function update($_id, $_params = null, $_options = null) "`Customer::updateSource('customer_id', 'bank_account_id', " . "\$updateParams)` or `Account::updateExternalAccount(" . "'account_id', 'bank_account_id', \$updateParams)`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } /** * @param array|null $params * @param array|string|null $options + * + * @throws \Stripe\Exception\ApiErrorException if the request fails * * @return BankAccount The verified bank account. */ diff --git a/lib/Capability.php b/lib/Capability.php index 5cb224f9e..86324ad58 100644 --- a/lib/Capability.php +++ b/lib/Capability.php @@ -38,7 +38,7 @@ public function instanceUrl() $id = $this['id']; $account = $this['account']; if (!$id) { - throw new Error\InvalidRequest( + throw new Exception\UnexpectedValueException( "Could not determine which URL to request: " . "class instance has invalid ID: $id", null @@ -57,14 +57,14 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function retrieve($_id, $_opts = null) { $msg = "Capabilities cannot be retrieved without an account ID. " . "Retrieve a capability using `Account::retrieveCapability(" . "'account_id', 'capability_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } /** @@ -72,13 +72,13 @@ public static function retrieve($_id, $_opts = null) * @param array|null $_params * @param array|string|null $_options * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function update($_id, $_params = null, $_options = null) { $msg = "Capabilities cannot be updated without an account ID. " . "Update a capability using `Account::updateCapability(" . "'account_id', 'capability_id', \$updateParams)`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } } diff --git a/lib/Card.php b/lib/Card.php index 98dc70596..a306f4864 100644 --- a/lib/Card.php +++ b/lib/Card.php @@ -89,7 +89,7 @@ public function instanceUrl() $path = 'cards'; } else { $msg = "Cards cannot be accessed without a customer ID, account ID or recipient ID."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\UnexpectedValueException($msg); } $parentExtn = urlencode(Util\Util::utf8($parent)); $extn = urlencode(Util\Util::utf8($this['id'])); @@ -100,7 +100,7 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function retrieve($_id, $_opts = null) { @@ -108,7 +108,7 @@ public static function retrieve($_id, $_opts = null) "account ID. Retrieve a card using " . "`Customer::retrieveSource('customer_id', 'card_id')` or " . "`Account::retrieveExternalAccount('account_id', 'card_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg); } /** @@ -116,7 +116,7 @@ public static function retrieve($_id, $_opts = null) * @param array|null $_params * @param array|string|null $_options * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function update($_id, $_params = null, $_options = null) { @@ -125,6 +125,6 @@ public static function update($_id, $_params = null, $_options = null) "`Customer::updateSource('customer_id', 'card_id', " . "\$updateParams)` or `Account::updateExternalAccount(" . "'account_id', 'card_id', \$updateParams)`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg); } } diff --git a/lib/Charge.php b/lib/Charge.php index 3ca70b1fc..c1adee31c 100644 --- a/lib/Charge.php +++ b/lib/Charge.php @@ -62,7 +62,7 @@ class Charge extends ApiResource /** * Possible string representations of decline codes. - * These strings are applicable to the decline_code property of the \Stripe\Error\Card exception. + * These strings are applicable to the decline_code property of the \Stripe\Exception\CardException exception. * @link https://stripe.com/docs/declines/codes */ const DECLINED_APPROVE_WITH_ID = 'approve_with_id'; @@ -121,6 +121,8 @@ class Charge extends ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Charge The captured charge. */ public function capture($params = null, $options = null) diff --git a/lib/Collection.php b/lib/Collection.php index 07f87bb16..c8955bcc9 100644 --- a/lib/Collection.php +++ b/lib/Collection.php @@ -57,7 +57,7 @@ public function offsetGet($k) "types only support string keys. (HINT: List calls " . "return an object with a `data` (which is the data " . "array). You likely want to call ->data[{$k}])"; - throw new \InvalidArgumentException($msg); + throw new Exception\InvalidArgumentException($msg); } } @@ -69,7 +69,7 @@ public function all($params = null, $opts = null) list($response, $opts) = $this->_request('get', $url, $params, $opts); $obj = Util\Util::convertToStripeObject($response, $opts); if (!($obj instanceof \Stripe\Collection)) { - throw new \Stripe\Error\Api( + throw new \Stripe\Exception\UnexpectedValueException( 'Expected type ' . \Stripe\Collection::class . ', got "' . get_class($obj) . '" instead.' ); } @@ -212,7 +212,7 @@ private function extractPathAndUpdateParams($params) { $url = parse_url($this->url); if (!isset($url['path'])) { - throw new Error\Api("Could not parse list url into parts: $url"); + throw new Exception\UnexpectedValueException("Could not parse list url into parts: $url"); } if (isset($url['query'])) { diff --git a/lib/CreditNote.php b/lib/CreditNote.php index c81d86ee6..1ddd724b8 100644 --- a/lib/CreditNote.php +++ b/lib/CreditNote.php @@ -61,6 +61,8 @@ class CreditNote extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return CreditNote The voided credit note. */ public function voidCreditNote($params = null, $opts = null) diff --git a/lib/Customer.php b/lib/Customer.php index fcc8e5048..c6dcdb10e 100644 --- a/lib/Customer.php +++ b/lib/Customer.php @@ -80,6 +80,8 @@ public function deleteDiscount() * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function createSource($id, $params = null, $opts = null) @@ -93,6 +95,8 @@ public static function createSource($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function retrieveSource($id, $sourceId, $params = null, $opts = null) @@ -106,6 +110,8 @@ public static function retrieveSource($id, $sourceId, $params = null, $opts = nu * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function updateSource($id, $sourceId, $params = null, $opts = null) @@ -119,6 +125,8 @@ public static function updateSource($id, $sourceId, $params = null, $opts = null * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function deleteSource($id, $sourceId, $params = null, $opts = null) @@ -131,6 +139,8 @@ public static function deleteSource($id, $sourceId, $params = null, $opts = null * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of sources. */ public static function allSources($id, $params = null, $opts = null) @@ -143,6 +153,8 @@ public static function allSources($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function createTaxId($id, $params = null, $opts = null) @@ -156,6 +168,8 @@ public static function createTaxId($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function retrieveTaxId($id, $taxIdId, $params = null, $opts = null) @@ -169,6 +183,8 @@ public static function retrieveTaxId($id, $taxIdId, $params = null, $opts = null * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function deleteTaxId($id, $taxIdId, $params = null, $opts = null) @@ -181,6 +197,8 @@ public static function deleteTaxId($id, $taxIdId, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of tax ids. */ public static function allTaxIds($id, $params = null, $opts = null) @@ -206,6 +224,8 @@ public static function createBalanceTransaction($id, $params = null, $opts = nul * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function retrieveBalanceTransaction($id, $balanceTransactionId, $params = null, $opts = null) @@ -219,6 +239,7 @@ public static function retrieveBalanceTransaction($id, $balanceTransactionId, $p * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails * * @return ApiResource */ @@ -232,6 +253,8 @@ public static function updateBalanceTransaction($id, $balanceTransactionId, $par * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of customer balance transactions. */ public static function allBalanceTransactions($id, $params = null, $opts = null) diff --git a/lib/CustomerBalanceTransaction.php b/lib/CustomerBalanceTransaction.php index df1f87902..357b0b83c 100644 --- a/lib/CustomerBalanceTransaction.php +++ b/lib/CustomerBalanceTransaction.php @@ -45,7 +45,7 @@ public function instanceUrl() $id = $this['id']; $customer = $this['customer']; if (!$id) { - throw new Error\InvalidRequest( + throw new Exception\UnexpectedValueException( "Could not determine which URL to request: class instance has invalid ID: $id", null ); @@ -63,7 +63,7 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function retrieve($_id, $_opts = null) { @@ -71,7 +71,7 @@ public static function retrieve($_id, $_opts = null) "customer ID. Retrieve a Customer Balance Transaction using " . "`Customer::retrieveBalanceTransaction('customer_id', " . "'balance_transaction_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } /** @@ -79,7 +79,7 @@ public static function retrieve($_id, $_opts = null) * @param array|null $_params * @param array|string|null $_options * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function update($_id, $_params = null, $_options = null) { @@ -87,6 +87,6 @@ public static function update($_id, $_params = null, $_options = null) "customer ID. Update a Customer Balance Transaction using " . "`Customer::updateBalanceTransaction('customer_id', " . "'balance_transaction_id', \$updateParams)`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } } diff --git a/lib/Dispute.php b/lib/Dispute.php index 8ffc2d4cc..d1c69b82f 100644 --- a/lib/Dispute.php +++ b/lib/Dispute.php @@ -65,6 +65,8 @@ class Dispute extends ApiResource /** * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Dispute The closed dispute. */ public function close($options = null) diff --git a/lib/EphemeralKey.php b/lib/EphemeralKey.php index ea4cc756c..aedc7aed3 100644 --- a/lib/EphemeralKey.php +++ b/lib/EphemeralKey.php @@ -28,12 +28,15 @@ class EphemeralKey extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\InvalidArgumentException if stripe_version is missing + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return EphemeralKey The created key. */ public static function create($params = null, $opts = null) { if (!$opts['stripe_version']) { - throw new \InvalidArgumentException('stripe_version must be specified to create an ephemeral key'); + throw new Exception\InvalidArgumentException('stripe_version must be specified to create an ephemeral key'); } return self::_create($params, $opts); } diff --git a/lib/Error/Api.php b/lib/Error/Api.php deleted file mode 100644 index df97730af..000000000 --- a/lib/Error/Api.php +++ /dev/null @@ -1,14 +0,0 @@ -httpStatus = $httpStatus; - $this->httpBody = $httpBody; - $this->jsonBody = $jsonBody; - $this->httpHeaders = $httpHeaders; - $this->stripeCode = $stripeCode; - - $this->requestId = null; - if ($httpHeaders && isset($httpHeaders['Request-Id'])) { - $this->requestId = $httpHeaders['Request-Id']; - } - - $this->error = $this->constructErrorObject(); - } - - public function getError() - { - return $this->error; - } - - public function getHttpBody() - { - return $this->httpBody; - } - - public function getHttpHeaders() - { - return $this->httpHeaders; - } - - public function getHttpStatus() - { - return $this->httpStatus; - } - - public function getJsonBody() - { - return $this->jsonBody; - } - - public function getRequestId() - { - return $this->requestId; - } - - public function getStripeCode() - { - return $this->stripeCode; - } - - public function __toString() - { - $statusStr = ($this->getHttpStatus() == null) ? "" : "(Status {$this->getHttpStatus()}) "; - $idStr = ($this->getRequestId() == null) ? "" : "(Request {$this->getRequestId()}) "; - return "{$statusStr}{$idStr}{$this->getMessage()}"; - } - - protected function constructErrorObject() - { - if (is_null($this->jsonBody) || !array_key_exists('error', $this->jsonBody)) { - return null; - } - - return \Stripe\ErrorObject::constructFrom($this->jsonBody['error']); - } -} diff --git a/lib/Error/Card.php b/lib/Error/Card.php deleted file mode 100644 index 205f238aa..000000000 --- a/lib/Error/Card.php +++ /dev/null @@ -1,39 +0,0 @@ -declineCode = $declineCode; - $this->stripeParam = $stripeParam; - } - - public function getDeclineCode() - { - return $this->declineCode; - } - - public function getStripeParam() - { - return $this->stripeParam; - } -} diff --git a/lib/Error/Idempotency.php b/lib/Error/Idempotency.php deleted file mode 100644 index 2d7eca3d8..000000000 --- a/lib/Error/Idempotency.php +++ /dev/null @@ -1,12 +0,0 @@ -stripeParam = $stripeParam; - } - - public function getStripeParam() - { - return $this->stripeParam; - } -} diff --git a/lib/Error/OAuth/InvalidClient.php b/lib/Error/OAuth/InvalidClient.php deleted file mode 100644 index 20fc4fce0..000000000 --- a/lib/Error/OAuth/InvalidClient.php +++ /dev/null @@ -1,14 +0,0 @@ -errorCode = $code; - } - - public function getErrorCode() - { - return $this->errorCode; - } - - protected function constructErrorObject() - { - if (is_null($this->jsonBody)) { - return null; - } - - return \Stripe\ErrorObject::constructFrom($this->jsonBody); - } -} diff --git a/lib/Error/OAuth/UnsupportedGrantType.php b/lib/Error/OAuth/UnsupportedGrantType.php deleted file mode 100644 index 4a720b3f9..000000000 --- a/lib/Error/OAuth/UnsupportedGrantType.php +++ /dev/null @@ -1,12 +0,0 @@ -sigHeader = $sigHeader; - } - - public function getSigHeader() - { - return $this->sigHeader; - } -} diff --git a/lib/Exception/ApiConnectionException.php b/lib/Exception/ApiConnectionException.php new file mode 100644 index 000000000..880fc43d2 --- /dev/null +++ b/lib/Exception/ApiConnectionException.php @@ -0,0 +1,14 @@ +setHttpStatus($httpStatus); + $instance->setHttpBody($httpBody); + $instance->setJsonBody($jsonBody); + $instance->setHttpHeaders($httpHeaders); + $instance->setStripeCode($stripeCode); + + $instance->setRequestId(null); + if ($httpHeaders && isset($httpHeaders['Request-Id'])) { + $instance->setRequestId($httpHeaders['Request-Id']); + } + + $instance->setError($instance->constructErrorObject()); + + return $instance; + } + + /** + * Gets the Stripe error object. + * + * @return \Stripe\ErrorObject|null + */ + public function getError() + { + return $this->error; + } + + /** + * Sets the Stripe error object. + * + * @param \Stripe\ErrorObject|null $error + */ + public function setError($error) + { + $this->error = $error; + } + + /** + * Gets the HTTP body as a string. + * + * @return string|null + */ + public function getHttpBody() + { + return $this->httpBody; + } + + /** + * Sets the HTTP body as a string. + * + * @param string|null $httpBody + */ + public function setHttpBody($httpBody) + { + $this->httpBody = $httpBody; + } + + /** + * Gets the HTTP headers array. + * + * @return array|\Stripe\Util\CaseInsensitiveArray|null + */ + public function getHttpHeaders() + { + return $this->httpHeaders; + } + + /** + * Sets the HTTP headers array. + * + * @param array|\Stripe\Util\CaseInsensitiveArray|null $httpHeaders + */ + public function setHttpHeaders($httpHeaders) + { + $this->httpHeaders = $httpHeaders; + } + + /** + * Gets the HTTP status code. + * + * @return int|null + */ + public function getHttpStatus() + { + return $this->httpStatus; + } + + /** + * Sets the HTTP status code. + * + * @param int|null $httpStatus + */ + public function setHttpStatus($httpStatus) + { + $this->httpStatus = $httpStatus; + } + + /** + * Gets the JSON deserialized body. + * + * @return array|null + */ + public function getJsonBody() + { + return $this->jsonBody; + } + + /** + * Sets the JSON deserialized body. + * + * @param array|null $jsonBody + */ + public function setJsonBody($jsonBody) + { + $this->jsonBody = $jsonBody; + } + + /** + * Gets the Stripe request ID. + * + * @return string|null + */ + public function getRequestId() + { + return $this->requestId; + } + + /** + * Sets the Stripe request ID. + * + * @param string|null $requestId + */ + public function setRequestId($requestId) + { + $this->requestId = $requestId; + } + + /** + * Gets the Stripe error code. + * + * @return string|null + */ + public function getStripeCode() + { + return $this->stripeCode; + } + + /** + * Sets the Stripe error code. + * + * @param string|null $stripeCode + */ + public function setStripeCode($stripeCode) + { + $this->stripeCode = $stripeCode; + } + + /** + * Returns the string representation of the exception. + * + * @return string + */ + public function __toString() + { + $statusStr = ($this->getHttpStatus() == null) ? "" : "(Status {$this->getHttpStatus()}) "; + $idStr = ($this->getRequestId() == null) ? "" : "(Request {$this->getRequestId()}) "; + return "{$statusStr}{$idStr}{$this->getMessage()}"; + } + + protected function constructErrorObject() + { + if (is_null($this->jsonBody) || !array_key_exists('error', $this->jsonBody)) { + return null; + } + + return \Stripe\ErrorObject::constructFrom($this->jsonBody['error']); + } +} diff --git a/lib/Exception/AuthenticationException.php b/lib/Exception/AuthenticationException.php new file mode 100644 index 000000000..dd9cbf827 --- /dev/null +++ b/lib/Exception/AuthenticationException.php @@ -0,0 +1,13 @@ +setDeclineCode($declineCode); + $instance->setStripeParam($stripeParam); + + return $instance; + } + + /** + * Gets the decline code. + * + * @return string|null + */ + public function getDeclineCode() + { + return $this->declineCode; + } + + /** + * Sets the decline code. + * + * @param string|null $declineCode + */ + public function setDeclineCode($declineCode) + { + $this->declineCode = $declineCode; + } + + /** + * Gets the parameter related to the error. + * + * @return string|null + */ + public function getStripeParam() + { + return $this->stripeParam; + } + + /** + * Sets the parameter related to the error. + * + * @param string|null $stripeParam + */ + public function setStripeParam($stripeParam) + { + $this->stripeParam = $stripeParam; + } +} diff --git a/lib/Exception/ExceptionInterface.php b/lib/Exception/ExceptionInterface.php new file mode 100644 index 000000000..e411ab3d0 --- /dev/null +++ b/lib/Exception/ExceptionInterface.php @@ -0,0 +1,26 @@ +setStripeParam($stripeParam); + + return $instance; + } + + /** + * Gets the parameter related to the error. + * + * @return string|null + */ + public function getStripeParam() + { + return $this->stripeParam; + } + + /** + * Sets the parameter related to the error. + * + * @param string|null $stripeParam + */ + public function setStripeParam($stripeParam) + { + $this->stripeParam = $stripeParam; + } +} diff --git a/lib/Exception/OAuth/ExceptionInterface.php b/lib/Exception/OAuth/ExceptionInterface.php new file mode 100644 index 000000000..dd4266201 --- /dev/null +++ b/lib/Exception/OAuth/ExceptionInterface.php @@ -0,0 +1,10 @@ +jsonBody)) { + return null; + } + + return \Stripe\OAuthErrorObject::constructFrom($this->jsonBody); + } +} diff --git a/lib/Exception/OAuth/UnknownOAuthErrorException.php b/lib/Exception/OAuth/UnknownOAuthErrorException.php new file mode 100644 index 000000000..90195b4e2 --- /dev/null +++ b/lib/Exception/OAuth/UnknownOAuthErrorException.php @@ -0,0 +1,14 @@ +setHttpBody($httpBody); + $instance->setSigHeader($sigHeader); + + return $instance; + } + + /** + * Gets the HTTP body as a string. + * + * @return string|null + */ + public function getHttpBody() + { + return $this->httpBody; + } + + /** + * Sets the HTTP body as a string. + * + * @param string|null $httpBody + */ + public function setHttpBody($httpBody) + { + $this->httpBody = $httpBody; + } + + /** + * Gets the `Stripe-Signature` HTTP header. + * + * @return string|null + */ + public function getSigHeader() + { + return $this->sigHeader; + } + + /** + * Sets the `Stripe-Signature` HTTP header. + * + * @param string|null $sigHeader + */ + public function setSigHeader($sigHeader) + { + $this->sigHeader = $sigHeader; + } +} diff --git a/lib/Exception/UnexpectedValueException.php b/lib/Exception/UnexpectedValueException.php new file mode 100644 index 000000000..0a629edf7 --- /dev/null +++ b/lib/Exception/UnexpectedValueException.php @@ -0,0 +1,7 @@ +defaultOptions)) { // call defaultOptions callback, set options to return value $opts = call_user_func_array($this->defaultOptions, func_get_args()); if (!is_array($opts)) { - throw new Error\Api("Non-array value returned by defaultOptions CurlClient callback"); + throw new Exception\UnexpectedValueException("Non-array value returned by defaultOptions CurlClient callback"); } } elseif (is_array($this->defaultOptions)) { // set default curlopts from array $opts = $this->defaultOptions; @@ -174,7 +174,7 @@ public function request($method, $absUrl, $headers, $params, $hasFile) if ($method == 'get') { if ($hasFile) { - throw new Error\Api( + throw new Exception\UnexpectedValueException( "Issuing a GET request with a file parameter" ); } @@ -193,7 +193,7 @@ public function request($method, $absUrl, $headers, $params, $hasFile) $absUrl = "$absUrl?$encoded"; } } else { - throw new Error\Api("Unrecognized method $method"); + throw new Exception\UnexpectedValueException("Unrecognized method $method"); } // It is only safe to retry network failures on POST requests if we @@ -299,7 +299,7 @@ private function executeRequestWithRetries($opts, $absUrl) * @param int $errno * @param string $message * @param int $numRetries - * @throws Error\ApiConnection + * @throws Exception\ApiConnectionException */ private function handleCurlError($url, $errno, $message, $numRetries) { @@ -331,7 +331,7 @@ private function handleCurlError($url, $errno, $message, $numRetries) $msg .= "\n\nRequest was retried $numRetries times."; } - throw new Error\ApiConnection($msg); + throw new Exception\ApiConnectionException($msg); } /** diff --git a/lib/Invoice.php b/lib/Invoice.php index a309dd9e4..b05b1848e 100644 --- a/lib/Invoice.php +++ b/lib/Invoice.php @@ -119,6 +119,8 @@ class Invoice extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Invoice The finalized invoice. */ public function finalizeInvoice($params = null, $opts = null) @@ -133,6 +135,8 @@ public function finalizeInvoice($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Invoice The uncollectible invoice. */ public function markUncollectible($params = null, $opts = null) @@ -147,6 +151,8 @@ public function markUncollectible($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Invoice The paid invoice. */ public function pay($params = null, $opts = null) @@ -161,6 +167,8 @@ public function pay($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Invoice The sent invoice. */ public function sendInvoice($params = null, $opts = null) @@ -175,6 +183,8 @@ public function sendInvoice($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Invoice The upcoming invoice. */ public static function upcoming($params = null, $opts = null) @@ -190,6 +200,8 @@ public static function upcoming($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Invoice The voided invoice. */ public function voidInvoice($params = null, $opts = null) diff --git a/lib/Issuing/Authorization.php b/lib/Issuing/Authorization.php index 9a04063d3..c3967194a 100644 --- a/lib/Issuing/Authorization.php +++ b/lib/Issuing/Authorization.php @@ -42,6 +42,8 @@ class Authorization extends \Stripe\ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Authorization The approved authorization. */ public function approve($params = null, $options = null) @@ -56,6 +58,8 @@ public function approve($params = null, $options = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Authorization The declined authorization. */ public function decline($params = null, $options = null) diff --git a/lib/Issuing/Card.php b/lib/Issuing/Card.php index 60cc5b4e1..d81711810 100644 --- a/lib/Issuing/Card.php +++ b/lib/Issuing/Card.php @@ -38,6 +38,8 @@ class Card extends \Stripe\ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return CardDetails The card details associated with that issuing card. */ public function details($params = null, $options = null) diff --git a/lib/OAuth.php b/lib/OAuth.php index e9a82e62a..3c39edaa2 100644 --- a/lib/OAuth.php +++ b/lib/OAuth.php @@ -34,6 +34,8 @@ public static function authorizeUrl($params = null, $opts = null) * @param array|null $params * @param array|null $opts * + * @throws \Stripe\Exception\OAuth\OAuthErrorException if the request fails + * * @return StripeObject Object containing the response from the API. */ public static function token($params = null, $opts = null) @@ -55,6 +57,8 @@ public static function token($params = null, $opts = null) * @param array|null $params * @param array|null $opts * + * @throws \Stripe\Exception\OAuth\OAuthErrorException if the request fails + * * @return StripeObject Object containing the response from the API. */ public static function deauthorize($params = null, $opts = null) @@ -86,7 +90,7 @@ private static function _getClientId($params = null) . 'after registering your account as a platform. See ' . 'https://stripe.com/docs/connect/standard-accounts for details, ' . 'or email support@stripe.com if you have any questions.'; - throw new Error\Authentication($msg); + throw new Exception\AuthenticationException($msg); } return $clientId; } diff --git a/lib/Order.php b/lib/Order.php index 1f2ce2563..46e4da2f4 100644 --- a/lib/Order.php +++ b/lib/Order.php @@ -41,6 +41,8 @@ class Order extends ApiResource use ApiOperations\Update; /** + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Order The paid order. */ public function pay($params = null, $opts = null) @@ -52,6 +54,8 @@ public function pay($params = null, $opts = null) } /** + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return OrderReturn The newly created return. */ public function returnOrder($params = null, $opts = null) diff --git a/lib/PaymentIntent.php b/lib/PaymentIntent.php index b70b15778..b5d507ea8 100644 --- a/lib/PaymentIntent.php +++ b/lib/PaymentIntent.php @@ -66,6 +66,8 @@ class PaymentIntent extends ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return PaymentIntent The canceled payment intent. */ public function cancel($params = null, $options = null) @@ -80,6 +82,8 @@ public function cancel($params = null, $options = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return PaymentIntent The captured payment intent. */ public function capture($params = null, $options = null) @@ -94,6 +98,8 @@ public function capture($params = null, $options = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return PaymentIntent The confirmed payment intent. */ public function confirm($params = null, $options = null) diff --git a/lib/PaymentMethod.php b/lib/PaymentMethod.php index c0557e8c3..846fa07f2 100644 --- a/lib/PaymentMethod.php +++ b/lib/PaymentMethod.php @@ -33,6 +33,8 @@ class PaymentMethod extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return PaymentMethod The attached payment method. */ public function attach($params = null, $opts = null) @@ -47,6 +49,8 @@ public function attach($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return PaymentMethod The detached payment method. */ public function detach($params = null, $opts = null) diff --git a/lib/Payout.php b/lib/Payout.php index 131bd4ae0..23f638175 100644 --- a/lib/Payout.php +++ b/lib/Payout.php @@ -80,6 +80,8 @@ class Payout extends ApiResource const TYPE_CARD = 'card'; /** + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Payout The canceled payout. */ public function cancel() diff --git a/lib/Person.php b/lib/Person.php index 52f920a8e..c100218b2 100644 --- a/lib/Person.php +++ b/lib/Person.php @@ -63,7 +63,7 @@ public function instanceUrl() $id = $this['id']; $account = $this['account']; if (!$id) { - throw new Error\InvalidRequest( + throw new Exception\UnexpectedValueException( "Could not determine which URL to request: " . "class instance has invalid ID: $id", null @@ -82,14 +82,14 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function retrieve($_id, $_opts = null) { $msg = "Persons cannot be retrieved without an account ID. Retrieve " . "a person using `Account::retrievePerson('account_id', " . "'person_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } /** @@ -97,13 +97,13 @@ public static function retrieve($_id, $_opts = null) * @param array|null $_params * @param array|string|null $_options * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function update($_id, $_params = null, $_options = null) { $msg = "Persons cannot be updated without an account ID. Update " . "a person using `Account::updatePerson('account_id', " . "'person_id', \$updateParams)`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg, null); } } diff --git a/lib/Review.php b/lib/Review.php index a2fd5d06d..cf5d513b4 100644 --- a/lib/Review.php +++ b/lib/Review.php @@ -45,6 +45,8 @@ class Review extends ApiResource /** * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Review The approved review. */ public function approve($params = null, $options = null) diff --git a/lib/SetupIntent.php b/lib/SetupIntent.php index 176a411b6..37a7c9fb2 100644 --- a/lib/SetupIntent.php +++ b/lib/SetupIntent.php @@ -48,6 +48,8 @@ class SetupIntent extends ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return SetupIntent The canceled setup intent. */ public function cancel($params = null, $options = null) @@ -62,6 +64,8 @@ public function cancel($params = null, $options = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return SetupIntent The confirmed setup intent. */ public function confirm($params = null, $options = null) diff --git a/lib/Source.php b/lib/Source.php index f5af360d7..0ceab3457 100644 --- a/lib/Source.php +++ b/lib/Source.php @@ -79,6 +79,9 @@ class Source extends ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\UnexpectedValueException if the source is not attached to a customer + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Source The detached source. */ public function detach($params = null, $options = null) @@ -90,7 +93,7 @@ public function detach($params = null, $options = null) $class = get_class($this); $msg = "Could not determine which URL to request: $class instance " . "has invalid ID: $id"; - throw new Error\InvalidRequest($msg, null); + throw new Exception\UnexpectedValueException($msg, null); } if ($this['customer']) { @@ -105,7 +108,7 @@ public function detach($params = null, $options = null) } else { $message = "This source object does not appear to be currently attached " . "to a customer object."; - throw new Error\Api($message); + throw new Exception\UnexpectedValueException($message); } } @@ -113,6 +116,8 @@ public function detach($params = null, $options = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of source transactions. */ public function sourceTransactions($params = null, $options = null) @@ -128,6 +133,8 @@ public function sourceTransactions($params = null, $options = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Source The verified source. */ public function verify($params = null, $options = null) diff --git a/lib/StripeObject.php b/lib/StripeObject.php index ea3f60fbd..635ce546f 100644 --- a/lib/StripeObject.php +++ b/lib/StripeObject.php @@ -116,14 +116,14 @@ public function __construct($id = null, $opts = null) public function __set($k, $v) { if (static::getPermanentAttributes()->includes($k)) { - throw new \InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Cannot set $k on this object. HINT: you can't set: " . join(', ', static::getPermanentAttributes()->toArray()) ); } if ($v === "") { - throw new \InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'You cannot set \''.$k.'\'to an empty string. ' .'We interpret empty strings as NULL in requests. ' .'You may set obj->'.$k.' = NULL to delete the property' @@ -367,7 +367,7 @@ public function serializeParamsValue($value, $original, $unsaved, $force, $key = } elseif (isset($value->id)) { return $value; } else { - throw new \InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Cannot save property `$key` containing an API resource of type " . get_class($value) . ". It doesn't appear to be persisted and is " . "not marked as `saveWithParent`." @@ -508,7 +508,7 @@ public static function emptyValues($obj) } elseif ($obj instanceof StripeObject) { $values = $obj->_values; } else { - throw new \InvalidArgumentException( + throw new Exception\InvalidArgumentException( "empty_values got got unexpected object type: " . get_class($obj) ); } diff --git a/lib/Subscription.php b/lib/Subscription.php index a1087a56a..b24519263 100644 --- a/lib/Subscription.php +++ b/lib/Subscription.php @@ -80,6 +80,8 @@ public static function getSavedNestedResources() /** * @param array|null $params * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Subscription The deleted subscription. */ public function cancel($params = null, $opts = null) @@ -88,6 +90,8 @@ public function cancel($params = null, $opts = null) } /** + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Subscription The updated subscription. */ public function deleteDiscount() diff --git a/lib/SubscriptionItem.php b/lib/SubscriptionItem.php index d0d2dea8f..36a709f8b 100644 --- a/lib/SubscriptionItem.php +++ b/lib/SubscriptionItem.php @@ -35,6 +35,8 @@ class SubscriptionItem extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return ApiResource */ public static function createUsageRecord($id, $params = null, $opts = null) @@ -46,6 +48,8 @@ public static function createUsageRecord($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of usage record summaries. */ public function usageRecordSummaries($params = null, $options = null) diff --git a/lib/SubscriptionSchedule.php b/lib/SubscriptionSchedule.php index e41f279a0..2e88ca155 100644 --- a/lib/SubscriptionSchedule.php +++ b/lib/SubscriptionSchedule.php @@ -42,6 +42,8 @@ class SubscriptionSchedule extends ApiResource * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return SubscriptionSchedule The canceled subscription schedule. */ public function cancel($params = null, $opts = null) @@ -56,6 +58,8 @@ public function cancel($params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return SubscriptionSchedule The released subscription schedule. */ public function release($params = null, $opts = null) diff --git a/lib/TaxId.php b/lib/TaxId.php index 892954e55..163274e36 100644 --- a/lib/TaxId.php +++ b/lib/TaxId.php @@ -51,9 +51,8 @@ public function instanceUrl() $id = $this['id']; $customer = $this['customer']; if (!$id) { - throw new Error\InvalidRequest( - "Could not determine which URL to request: class instance has invalid ID: $id", - null + throw new Exception\UnexpectedValueException( + "Could not determine which URL to request: class instance has invalid ID: $id" ); } $id = Util\Util::utf8($id); @@ -69,13 +68,13 @@ public function instanceUrl() * @param array|string $_id * @param array|string|null $_opts * - * @throws \Stripe\Error\InvalidRequest + * @throws \Stripe\Exception\BadMethodCallException */ public static function retrieve($_id, $_opts = null) { $msg = "Tax IDs cannot be retrieved without a customer ID. Retrieve " . "a tax ID using `Customer::retrieveTaxId('customer_id', " . "'tax_id_id')`."; - throw new Error\InvalidRequest($msg, null); + throw new Exception\BadMethodCallException($msg); } } diff --git a/lib/Topup.php b/lib/Topup.php index 37625a329..233153e5f 100644 --- a/lib/Topup.php +++ b/lib/Topup.php @@ -47,6 +47,8 @@ class Topup extends ApiResource * @param array|null $params * @param array|string|null $options * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Topup The canceled topup. */ public function cancel($params = null, $options = null) diff --git a/lib/Transfer.php b/lib/Transfer.php index 24ae986f7..8cbb2af8a 100644 --- a/lib/Transfer.php +++ b/lib/Transfer.php @@ -62,6 +62,8 @@ public function cancel() * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return TransferReversal */ public static function createReversal($id, $params = null, $opts = null) @@ -75,6 +77,8 @@ public static function createReversal($id, $params = null, $opts = null) * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return TransferReversal */ public static function retrieveReversal($id, $reversalId, $params = null, $opts = null) @@ -88,6 +92,8 @@ public static function retrieveReversal($id, $reversalId, $params = null, $opts * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return TransferReversal */ public static function updateReversal($id, $reversalId, $params = null, $opts = null) @@ -100,6 +106,8 @@ public static function updateReversal($id, $reversalId, $params = null, $opts = * @param array|null $params * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return Collection The list of reversals. */ public static function allReversals($id, $params = null, $opts = null) diff --git a/lib/TransferReversal.php b/lib/TransferReversal.php index a4f94f2fb..7f9d984c2 100644 --- a/lib/TransferReversal.php +++ b/lib/TransferReversal.php @@ -34,7 +34,7 @@ public function instanceUrl() $id = $this['id']; $transfer = $this['transfer']; if (!$id) { - throw new Error\InvalidRequest( + throw new Exception\UnexpectedValueException( "Could not determine which URL to request: " . "class instance has invalid ID: $id", null @@ -52,6 +52,8 @@ public function instanceUrl() /** * @param array|string|null $opts * + * @throws \Stripe\Exception\ApiErrorException if the request fails + * * @return TransferReversal The saved reversal. */ public function save($opts = null) diff --git a/lib/Util/DefaultLogger.php b/lib/Util/DefaultLogger.php index 1a8663699..ce3b0b698 100644 --- a/lib/Util/DefaultLogger.php +++ b/lib/Util/DefaultLogger.php @@ -11,7 +11,7 @@ class DefaultLogger implements LoggerInterface public function error($message, array $context = []) { if (count($context) > 0) { - throw new \Exception('DefaultLogger does not currently implement context. Please implement if you need it.'); + throw new \Stripe\Exception\BadMethodCallException('DefaultLogger does not currently implement context. Please implement if you need it.'); } error_log($message); } diff --git a/lib/Util/RequestOptions.php b/lib/Util/RequestOptions.php index 495236224..711632909 100644 --- a/lib/Util/RequestOptions.php +++ b/lib/Util/RequestOptions.php @@ -2,7 +2,7 @@ namespace Stripe\Util; -use Stripe\Error; +use Stripe\Exception; class RequestOptions { @@ -103,6 +103,6 @@ public static function parse($options) . 'optional per-request apiKey, which must be a string, or ' . 'per-request options, which must be an array. (HINT: you can set ' . 'a global apiKey by "Stripe::setApiKey()")'; - throw new Error\Api($message); + throw new Exception\InvalidArgumentException($message); } } diff --git a/lib/Webhook.php b/lib/Webhook.php index 45c7dc0f3..7f0fd510e 100644 --- a/lib/Webhook.php +++ b/lib/Webhook.php @@ -7,10 +7,10 @@ abstract class Webhook const DEFAULT_TOLERANCE = 300; /** - * Returns an Event instance using the provided JSON payload. Throws a - * \UnexpectedValueException if the payload is not valid JSON, and a - * \Stripe\SignatureVerificationException if the signature verification - * fails for any reason. + * Returns an Event instance using the provided JSON payload. Throws an + * Exception\UnexpectedValueException if the payload is not valid JSON, and + * an Exception\SignatureVerificationException if the signature + * verification fails for any reason. * * @param string $payload the payload sent by Stripe. * @param string $sigHeader the contents of the signature header sent by @@ -18,9 +18,9 @@ abstract class Webhook * @param string $secret secret used to generate the signature. * @param int $tolerance maximum difference allowed between the header's * timestamp and the current time - * @return \Stripe\Event the Event instance - * @throws \UnexpectedValueException if the payload is not valid JSON, - * @throws \Stripe\Error\SignatureVerification if the verification fails. + * @return Event the Event instance + * @throws Exception\UnexpectedValueException if the payload is not valid JSON, + * @throws Exception\SignatureVerification if the verification fails. */ public static function constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE) { @@ -31,7 +31,7 @@ public static function constructEvent($payload, $sigHeader, $secret, $tolerance if ($data === null && $jsonError !== JSON_ERROR_NONE) { $msg = "Invalid payload: $payload " . "(json_last_error() was $jsonError)"; - throw new \UnexpectedValueException($msg); + throw new Exception\UnexpectedValueException($msg); } $event = Event::constructFrom($data); diff --git a/lib/WebhookSignature.php b/lib/WebhookSignature.php index 9f8be8777..e43e2ec65 100644 --- a/lib/WebhookSignature.php +++ b/lib/WebhookSignature.php @@ -7,9 +7,9 @@ abstract class WebhookSignature const EXPECTED_SCHEME = "v1"; /** - * Verifies the signature header sent by Stripe. Throws a - * SignatureVerification exception if the verification fails for any - * reason. + * Verifies the signature header sent by Stripe. Throws an + * Exception\SignatureVerification exception if the verification fails for + * any reason. * * @param string $payload the payload sent by Stripe. * @param string $header the contents of the signature header sent by @@ -17,7 +17,7 @@ abstract class WebhookSignature * @param string $secret secret used to generate the signature. * @param int $tolerance maximum difference allowed between the header's * timestamp and the current time - * @throws \Stripe\Error\SignatureVerification if the verification fails. + * @throws Exception\SignatureVerification if the verification fails. * @return bool */ public static function verifyHeader($payload, $header, $secret, $tolerance = null) @@ -26,17 +26,17 @@ public static function verifyHeader($payload, $header, $secret, $tolerance = nul $timestamp = self::getTimestamp($header); $signatures = self::getSignatures($header, self::EXPECTED_SCHEME); if ($timestamp == -1) { - throw new Error\SignatureVerification( + throw Exception\SignatureVerificationException::factory( "Unable to extract timestamp and signatures from header", - $header, - $payload + $payload, + $header ); } if (empty($signatures)) { - throw new Error\SignatureVerification( + throw Exception\SignatureVerificationException::factory( "No signatures found with expected scheme", - $header, - $payload + $payload, + $header ); } @@ -52,19 +52,19 @@ public static function verifyHeader($payload, $header, $secret, $tolerance = nul } } if (!$signatureFound) { - throw new Error\SignatureVerification( + throw Exception\SignatureVerificationException::factory( "No signatures found matching the expected signature for payload", - $header, - $payload + $payload, + $header ); } // Check if timestamp is within tolerance if (($tolerance > 0) && (abs(time() - $timestamp) > $tolerance)) { - throw new Error\SignatureVerification( + throw Exception\SignatureVerificationException::factory( "Timestamp outside the tolerance zone", - $header, - $payload + $payload, + $header ); } diff --git a/tests/Stripe/AlipayAccountTest.php b/tests/Stripe/AlipayAccountTest.php index cb48a1007..6f1716e44 100644 --- a/tests/Stripe/AlipayAccountTest.php +++ b/tests/Stripe/AlipayAccountTest.php @@ -34,7 +34,7 @@ public function testHasCorrectUrlForCustomer() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyRetrievable() { @@ -54,7 +54,7 @@ public function testIsSaveable() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyUpdatable() { diff --git a/tests/Stripe/ApiRequestorTest.php b/tests/Stripe/ApiRequestorTest.php index 8105af7ff..60ab94a69 100644 --- a/tests/Stripe/ApiRequestorTest.php +++ b/tests/Stripe/ApiRequestorTest.php @@ -80,7 +80,7 @@ public function testDefaultHeaders() } /** - * @expectedException \Stripe\Error\Authentication + * @expectedException \Stripe\Exception\AuthenticationException * @expectedExceptionMessageRegExp #No API key provided# */ public function testRaisesAuthenticationErrorWhenNoApiKey() @@ -110,7 +110,7 @@ public function testRaisesInvalidRequestErrorOn400() try { Charge::create(); $this->fail("Did not raise error"); - } catch (Error\InvalidRequest $e) { + } catch (Exception\InvalidRequestException $e) { $this->assertSame(400, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame('Missing id', $e->getMessage()); @@ -140,7 +140,7 @@ public function testRaisesIdempotencyErrorOn400AndTypeIdempotencyError() try { Charge::create(); $this->fail("Did not raise error"); - } catch (Error\Idempotency $e) { + } catch (Exception\IdempotencyException $e) { $this->assertSame(400, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame("Keys for idempotent requests can only be used with the same parameters they were first used with. Try using a key other than 'abc' if you meant to execute a different request.", $e->getMessage()); @@ -169,7 +169,7 @@ public function testRaisesAuthenticationErrorOn401() try { Charge::create(); $this->fail("Did not raise error"); - } catch (Error\Authentication $e) { + } catch (Exception\AuthenticationException $e) { $this->assertSame(401, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame('You did not provide an API key.', $e->getMessage()); @@ -202,7 +202,7 @@ public function testRaisesCardErrorOn402() try { Charge::create(); $this->fail("Did not raise error"); - } catch (Error\Card $e) { + } catch (Exception\CardException $e) { $this->assertSame(402, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame('Your card was declined.', $e->getMessage()); @@ -234,7 +234,7 @@ public function testRaisesPermissionErrorOn403() try { Account::retrieve('foo'); $this->fail("Did not raise error"); - } catch (Error\Permission $e) { + } catch (Exception\PermissionException $e) { $this->assertSame(403, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame("The provided key 'sk_test_********************1234' does not have access to account 'foo' (or that account does not exist). Application access may have been revoked.", $e->getMessage()); @@ -264,7 +264,7 @@ public function testRaisesInvalidRequestErrorOn404() try { Charge::retrieve('foo'); $this->fail("Did not raise error"); - } catch (Error\InvalidRequest $e) { + } catch (Exception\InvalidRequestException $e) { $this->assertSame(404, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame('No such charge: foo', $e->getMessage()); @@ -293,11 +293,12 @@ public function testRaisesRateLimitErrorOn429() try { Charge::create(); $this->fail("Did not raise error"); - } catch (Error\RateLimit $e) { + } catch (Exception\RateLimitException $e) { $this->assertSame(429, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame('Too many requests', $e->getMessage()); } catch (\Exception $e) { + var_dump($e); $this->fail("Unexpected exception: " . get_class($e)); } } @@ -322,7 +323,7 @@ public function testRaisesRateLimitErrorOn400AndCodeRateLimit() try { Charge::create(); $this->fail("Did not raise error"); - } catch (Error\RateLimit $e) { + } catch (Exception\RateLimitException $e) { $this->assertSame(400, $e->getHttpStatus()); $this->assertTrue(is_array($e->getJsonBody())); $this->assertSame('Too many requests', $e->getMessage()); @@ -350,9 +351,9 @@ public function testRaisesOAuthInvalidRequestError() try { OAuth::token(); $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidRequest $e) { + } catch (Exception\OAuth\InvalidRequestException $e) { $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('invalid_request', $e->getErrorCode()); + $this->assertSame('invalid_request', $e->getStripeCode()); $this->assertSame('No grant type specified', $e->getMessage()); } catch (\Exception $e) { $this->fail("Unexpected exception: " . get_class($e)); @@ -378,9 +379,9 @@ public function testRaisesOAuthInvalidClientError() try { OAuth::token(); $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidClient $e) { + } catch (Exception\OAuth\InvalidClientException $e) { $this->assertSame(401, $e->getHttpStatus()); - $this->assertSame('invalid_client', $e->getErrorCode()); + $this->assertSame('invalid_client', $e->getStripeCode()); $this->assertSame('No authentication was provided. Send your secret API key using the Authorization header, or as a client_secret POST parameter.', $e->getMessage()); } catch (\Exception $e) { $this->fail("Unexpected exception: " . get_class($e)); @@ -406,9 +407,9 @@ public function testRaisesOAuthInvalidGrantError() try { OAuth::token(); $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidGrant $e) { + } catch (Exception\OAuth\InvalidGrantException $e) { $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('invalid_grant', $e->getErrorCode()); + $this->assertSame('invalid_grant', $e->getStripeCode()); $this->assertSame('This authorization code has already been used. All tokens issued with this code have been revoked.', $e->getMessage()); } catch (\Exception $e) { $this->fail("Unexpected exception: " . get_class($e)); @@ -434,9 +435,9 @@ public function testRaisesOAuthInvalidScopeError() try { OAuth::token(); $this->fail("Did not raise error"); - } catch (Error\OAuth\InvalidScope $e) { + } catch (Exception\OAuth\InvalidScopeException $e) { $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('invalid_scope', $e->getErrorCode()); + $this->assertSame('invalid_scope', $e->getStripeCode()); $this->assertSame('Invalid scope provided: invalid_scope.', $e->getMessage()); } catch (\Exception $e) { $this->fail("Unexpected exception: " . get_class($e)); @@ -461,9 +462,9 @@ public function testRaisesOAuthUnsupportedGrantTypeError() try { OAuth::token(); $this->fail("Did not raise error"); - } catch (Error\OAuth\UnsupportedGrantType $e) { + } catch (Exception\OAuth\UnsupportedGrantTypeException $e) { $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('unsupported_grant_type', $e->getErrorCode()); + $this->assertSame('unsupported_grant_type', $e->getStripeCode()); } catch (\Exception $e) { $this->fail("Unexpected exception: " . get_class($e)); } @@ -488,9 +489,9 @@ public function testRaisesOAuthUnsupportedResponseTypeError() try { OAuth::token(); $this->fail("Did not raise error"); - } catch (Error\OAuth\UnsupportedResponseType $e) { + } catch (Exception\OAuth\UnsupportedResponseTypeException $e) { $this->assertSame(400, $e->getHttpStatus()); - $this->assertSame('unsupported_response_type', $e->getErrorCode()); + $this->assertSame('unsupported_response_type', $e->getStripeCode()); $this->assertSame("Only 'code' response_type is supported, but 'unsupported_response_type' was provided", $e->getMessage()); } catch (\Exception $e) { $this->fail("Unexpected exception: " . get_class($e)); diff --git a/tests/Stripe/BankAccountTest.php b/tests/Stripe/BankAccountTest.php index 33ab4f792..70d200dad 100644 --- a/tests/Stripe/BankAccountTest.php +++ b/tests/Stripe/BankAccountTest.php @@ -43,7 +43,7 @@ public function testHasCorrectUrlForAccount() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyRetrievable() { @@ -63,7 +63,7 @@ public function testIsSaveable() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyUpdatable() { diff --git a/tests/Stripe/CapabilityTest.php b/tests/Stripe/CapabilityTest.php index 1d0b80717..1e20a9196 100644 --- a/tests/Stripe/CapabilityTest.php +++ b/tests/Stripe/CapabilityTest.php @@ -17,7 +17,7 @@ public function testHasCorrectUrl() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyRetrievable() { @@ -37,7 +37,7 @@ public function testIsSaveable() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyUpdatable() { diff --git a/tests/Stripe/CardTest.php b/tests/Stripe/CardTest.php index ec19558f1..59aa4334b 100644 --- a/tests/Stripe/CardTest.php +++ b/tests/Stripe/CardTest.php @@ -52,7 +52,7 @@ public function testHasCorrectUrlForRecipient() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyRetrievable() { @@ -72,7 +72,7 @@ public function testIsSaveable() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyUpdatable() { diff --git a/tests/Stripe/CollectionTest.php b/tests/Stripe/CollectionTest.php index 890c6537c..7279fdfb9 100644 --- a/tests/Stripe/CollectionTest.php +++ b/tests/Stripe/CollectionTest.php @@ -17,7 +17,7 @@ public function setUpFixture() } /** - * @expectedException \InvalidArgumentException + * @expectedException \Stripe\Exception\InvalidArgumentException * @expectedExceptionMessageRegExp /You tried to access the \d index/ */ public function testOffsetGetNumericIndex() diff --git a/tests/Stripe/Error/SignatureVerificationTest.php b/tests/Stripe/Error/SignatureVerificationTest.php deleted file mode 100644 index 020a41f8f..000000000 --- a/tests/Stripe/Error/SignatureVerificationTest.php +++ /dev/null @@ -1,12 +0,0 @@ -assertSame('sig_header', $e->getSigHeader()); - } -} diff --git a/tests/Stripe/Error/BaseTest.php b/tests/Stripe/Exception/ApiErrorExceptionTest.php similarity index 76% rename from tests/Stripe/Error/BaseTest.php rename to tests/Stripe/Exception/ApiErrorExceptionTest.php index e1c1ba183..758bc60c4 100644 --- a/tests/Stripe/Error/BaseTest.php +++ b/tests/Stripe/Exception/ApiErrorExceptionTest.php @@ -1,12 +1,13 @@ getMockForAbstractClass(\Stripe\Error\Base::class, [ + $mock = $this->getMockForAbstractClass(ApiErrorException::class); + $instance = $mock::factory( 'message', 200, '{"error": {"code": "some_code"}}', @@ -15,7 +16,9 @@ public function createFixture() 'Some-Header' => 'Some Value', 'Request-Id' => 'req_test', ], - ]); + 'some_code' + ); + return $instance; } public function testGetters() @@ -26,6 +29,7 @@ public function testGetters() $this->assertSame(['error' => ['code' => 'some_code']], $e->getJsonBody()); $this->assertSame('Some Value', $e->getHttpHeaders()['Some-Header']); $this->assertSame('req_test', $e->getRequestId()); + $this->assertSame('some_code', $e->getStripeCode()); $this->assertNotNull($e->getError()); $this->assertSame('some_code', $e->getError()->code); } diff --git a/tests/Stripe/Error/OAuth/OAuthBaseTest.php b/tests/Stripe/Exception/OAuth/OAuthErrorExceptionTest.php similarity index 78% rename from tests/Stripe/Error/OAuth/OAuthBaseTest.php rename to tests/Stripe/Exception/OAuth/OAuthErrorExceptionTest.php index 6489e8dc1..ae8fe5200 100644 --- a/tests/Stripe/Error/OAuth/OAuthBaseTest.php +++ b/tests/Stripe/Exception/OAuth/OAuthErrorExceptionTest.php @@ -1,13 +1,13 @@ getMockForAbstractClass(\Stripe\Error\OAuth\OAuthBase::class, [ - 'code', + $mock = $this->getMockForAbstractClass(OAuthErrorException::class); + $instance = $mock::factory( 'description', 200, '{"error": "code", "error_description": "description"}', @@ -16,7 +16,9 @@ public function createFixture() 'Some-Header' => 'Some Value', 'Request-Id' => 'req_test', ], - ]); + 'code' + ); + return $instance; } public function testGetters() @@ -27,6 +29,7 @@ public function testGetters() $this->assertSame(['error' => 'code', 'error_description' => 'description'], $e->getJsonBody()); $this->assertSame('Some Value', $e->getHttpHeaders()['Some-Header']); $this->assertSame('req_test', $e->getRequestId()); + $this->assertSame('code', $e->getStripeCode()); $this->assertNotNull($e->getError()); $this->assertSame('code', $e->getError()->error); $this->assertSame('description', $e->getError()->error_description); diff --git a/tests/Stripe/Exception/SignatureVerificationExceptionTest.php b/tests/Stripe/Exception/SignatureVerificationExceptionTest.php new file mode 100644 index 000000000..a3ea273a2 --- /dev/null +++ b/tests/Stripe/Exception/SignatureVerificationExceptionTest.php @@ -0,0 +1,14 @@ +assertSame('message', $e->getMessage()); + $this->assertSame('payload', $e->getHttpBody()); + $this->assertSame('sig_header', $e->getSigHeader()); + } +} diff --git a/tests/Stripe/HttpClient/CurlClientTest.php b/tests/Stripe/HttpClient/CurlClientTest.php index 0900e3c18..d0827ced4 100644 --- a/tests/Stripe/HttpClient/CurlClientTest.php +++ b/tests/Stripe/HttpClient/CurlClientTest.php @@ -112,7 +112,7 @@ public function testDefaultOptions() $withBadClosure = new CurlClient(function () { return 'thisShouldNotWork'; }); - $this->setExpectedException('Stripe\Error\Api', "Non-array value returned by defaultOptions CurlClient callback"); + $this->setExpectedException('Stripe\Exception\UnexpectedValueException', "Non-array value returned by defaultOptions CurlClient callback"); $withBadClosure->request('get', 'https://httpbin.org/status/200', [], [], false); } diff --git a/tests/Stripe/OAuthTest.php b/tests/Stripe/OAuthTest.php index b4e43a881..aa9e5b045 100644 --- a/tests/Stripe/OAuthTest.php +++ b/tests/Stripe/OAuthTest.php @@ -31,7 +31,7 @@ public function testAuthorizeUrl() } /** - * @expectedException \Stripe\Error\Authentication + * @expectedException \Stripe\Exception\AuthenticationException * @expectedExceptionMessageRegExp #No client_id provided# */ public function testRaisesAuthenticationErrorWhenNoClientId() diff --git a/tests/Stripe/PersonTest.php b/tests/Stripe/PersonTest.php index fa5a10356..d91f2bfad 100644 --- a/tests/Stripe/PersonTest.php +++ b/tests/Stripe/PersonTest.php @@ -17,7 +17,7 @@ public function testHasCorrectUrl() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyRetrievable() { @@ -37,7 +37,7 @@ public function testIsSaveable() } /** - * @expectedException \Stripe\Error\InvalidRequest + * @expectedException \Stripe\Exception\BadMethodCallException */ public function testIsNotDirectlyUpdatable() { diff --git a/tests/Stripe/SourceTest.php b/tests/Stripe/SourceTest.php index 49ec9ea47..e8ce769e0 100644 --- a/tests/Stripe/SourceTest.php +++ b/tests/Stripe/SourceTest.php @@ -101,7 +101,7 @@ public function testIsDetachableWhenAttached() } /** - * @expectedException \Stripe\Error\Api + * @expectedException \Stripe\Exception\UnexpectedValueException */ public function testIsNotDetachableWhenUnattached() { diff --git a/tests/Stripe/Util/RequestOptionsTest.php b/tests/Stripe/Util/RequestOptionsTest.php index 558f73982..4175b0545 100644 --- a/tests/Stripe/Util/RequestOptionsTest.php +++ b/tests/Stripe/Util/RequestOptionsTest.php @@ -60,7 +60,7 @@ public function testKeyArray() } /** - * @expectedException Stripe\Error\Api + * @expectedException Stripe\Exception\InvalidArgumentException */ public function testWrongType() { diff --git a/tests/Stripe/WebhookTest.php b/tests/Stripe/WebhookTest.php index 395d7e8f2..e08d0579a 100644 --- a/tests/Stripe/WebhookTest.php +++ b/tests/Stripe/WebhookTest.php @@ -32,7 +32,7 @@ public function testValidJsonAndHeader() } /** - * @expectedException \UnexpectedValueException + * @expectedException \Stripe\Exception\UnexpectedValueException */ public function testInvalidJson() { @@ -42,7 +42,7 @@ public function testInvalidJson() } /** - * @expectedException \Stripe\Error\SignatureVerification + * @expectedException \Stripe\Exception\SignatureVerificationException */ public function testValidJsonAndInvalidHeader() { @@ -51,7 +51,7 @@ public function testValidJsonAndInvalidHeader() } /** - * @expectedException \Stripe\Error\SignatureVerification + * @expectedException \Stripe\Exception\SignatureVerificationException * @expectedExceptionMessage Unable to extract timestamp and signatures from header */ public function testMalformedHeader() @@ -61,7 +61,7 @@ public function testMalformedHeader() } /** - * @expectedException \Stripe\Error\SignatureVerification + * @expectedException \Stripe\Exception\SignatureVerificationException * @expectedExceptionMessage No signatures found with expected scheme */ public function testNoSignaturesWithExpectedScheme() @@ -71,7 +71,7 @@ public function testNoSignaturesWithExpectedScheme() } /** - * @expectedException \Stripe\Error\SignatureVerification + * @expectedException \Stripe\Exception\SignatureVerificationException * @expectedExceptionMessage No signatures found matching the expected signature for payload */ public function testNoValidSignatureForPayload() @@ -81,7 +81,7 @@ public function testNoValidSignatureForPayload() } /** - * @expectedException \Stripe\Error\SignatureVerification + * @expectedException \Stripe\Exception\SignatureVerificationException * @expectedExceptionMessage Timestamp outside the tolerance zone */ public function testTimestampTooOld() @@ -91,7 +91,7 @@ public function testTimestampTooOld() } /** - * @expectedException \Stripe\Error\SignatureVerification + * @expectedException \Stripe\Exception\SignatureVerificationException * @expectedExceptionMessage Timestamp outside the tolerance zone */ public function testTimestampTooRecent()