diff --git a/Readme.md b/Readme.md index 9bad344..1840fa0 100644 --- a/Readme.md +++ b/Readme.md @@ -99,16 +99,31 @@ to extract the below array from the thrown exception `status`, `code` and `type` must be checked on a failure. -**NOTE**: if code is T001 then this is a request flood error: +## Other Errors from exceptions + +### T001 + +if code is T001 then this is a request flood error: In this case the request has to be resend after a certain waiting period. -**NOTE**: if code is E999 some other critical error has happened +### E9999 -**NOTE**: if code is E001 if the return create/cancel/check calls is not an array +if code is E999 some other critical error has happened -**NOTE**: if code is C001 a curl error has happened +### E001 -**NOTE**: any other NON amazon error will have only 'message' set if run through decode +if code is E001 if the return create/cancel/check calls is not an array + +### C001 + +fif code is C001 curl failed to init +### C002 + +if code is C002 a curl error has happened + +### empty error code + +any other NON amazon error will have only 'message' set if run through decode ## Debugging diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..fe0a316 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,22 @@ +# PHP Stan Config + +parameters: + tmpDir: /tmp/phpstan-codeblocks-amazon-incentives + level: max + paths: + - %currentWorkingDirectory% + excludes_analyse: + # ignore composer + - vendor + # ignore errores with + ignoreErrors: + - + message: '#Strict comparison using === between false and true will always evaluate to false.#' + path: %currentWorkingDirectory%/test/aws_gift_card_tests.php + #- 'error regex' + #- + # message: 'error regex' + # path: %currentWorkingDirectory%/www/some/* + # paths: + # - ... + # - ... diff --git a/src/AWS/AWS.php b/src/AWS/AWS.php index 89a5b55..427c026 100644 --- a/src/AWS/AWS.php +++ b/src/AWS/AWS.php @@ -26,6 +26,9 @@ class AWS public const CANCEL_GIFT_CARD_SERVICE = 'CancelGiftCard'; public const GET_AVAILABLE_FUNDS_SERVICE = 'GetAvailableFunds'; + /** + * @var Config + */ private $config; /** @@ -162,7 +165,7 @@ class AWS * @param string $authorization_value * @param string $date_time_string * @param string $service_target - * @return array + * @return array */ public function buildHeaders( string $payload, @@ -323,7 +326,6 @@ class AWS */ public function getGiftCardPayload(float $amount, ?string $creation_id = null): string { - $amount = trim($amount); $payload = [ 'creationRequestId' => $creation_id ?: uniqid($this->config->getPartner() . '_'), 'partnerId' => $this->config->getPartner(), @@ -333,7 +335,7 @@ class AWS 'amount' => (float)$amount ] ]; - return json_encode($payload); + return (json_encode($payload)) ?: ''; } /** @@ -343,13 +345,12 @@ class AWS */ public function getCancelGiftCardPayload(string $creation_request_id, string $gift_card_id): string { - $gift_card_response_id = trim($gift_card_id); $payload = [ 'creationRequestId' => $creation_request_id, 'partnerId' => $this->config->getPartner(), - 'gcId' => $gift_card_response_id + 'gcId' => $gift_card_id ]; - return json_encode($payload); + return (json_encode($payload)) ?: ''; } /** @@ -360,7 +361,7 @@ class AWS $payload = [ 'partnerId' => $this->config->getPartner(), ]; - return json_encode($payload); + return (json_encode($payload)) ?: ''; } /** @@ -394,7 +395,7 @@ class AWS } /** - * @return false|string + * @return string */ public function getTimestamp() { @@ -413,7 +414,7 @@ class AWS } /** - * @return bool|string + * @return string */ public function getDateString() { diff --git a/src/AmazonIncentives.php b/src/AmazonIncentives.php index 92b733b..3e5d44e 100644 --- a/src/AmazonIncentives.php +++ b/src/AmazonIncentives.php @@ -2,36 +2,7 @@ /* * Amazon Incentive Code - * - * # settings: - * aws endpoint (also sets region) - * aws key - * aws secret - * aws partner id - * money type (set as default, override in call) - * money value (set as default, override in call) - * - * # checks - * endpoint + region must match - * - * # calls: - * create gift card: CreateGiftCard - * cancel gift card: CancelGiftCard - * - * activate gift card: ActivateGiftCard - * deactivate gift card: DeactivateGiftCard - * - * gift card status: ActivationStatusCheck - * - * check available funds: GetAvailablefunds - * - * api server health check - * - * # sub classes - * config reader/checker - * API v4 encrypter - * submitter/data getter - * error handler/retry + * Amazon Gift Code on Demand */ namespace gullevek\AmazonIncentives; @@ -41,8 +12,11 @@ use gullevek\AmazonIncentives\Config\Config; use gullevek\AmazonIncentives\Exceptions\AmazonErrors; use gullevek\AmazonIncentives\Debug\AmazonDebug; -class AmazonIncentives +final class AmazonIncentives { + /** + * @var Config + */ private $config; /** @@ -112,7 +86,7 @@ class AmazonIncentives } /** - * AmazonGiftCode make own client. + * AmazonIncentives make own client. * * @param string|null $key * @param string|null $secret @@ -120,7 +94,7 @@ class AmazonIncentives * @param string|null $endpoint * @param string|null $currency * @param bool|null $debug - * @return AmazonGiftCode + * @return AmazonIncentives */ public static function make( string $key = null, @@ -139,7 +113,7 @@ class AmazonIncentives * message (Amazon returned error message string) * * @param string $message Exception message json string - * @return array Decoded with code, type, message fields + * @return array Decoded with code, type, message fields */ public static function decodeExceptionMessage(string $message): array { @@ -162,6 +136,9 @@ class AmazonIncentives // PUBLIC TEST METHODS // ********************************************************************* + /** + * @return array + */ public function checkMe(): array { $data = []; diff --git a/src/Client/Client.php b/src/Client/Client.php index 4126a08..c82463e 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -13,15 +13,25 @@ class Client implements ClientInterface /** * * @param string $url The URL being requested, including domain and protocol - * @param array $headers Headers to be used in the request - * @param array|string $params Can be nested for arrays and hashes + * @param array $headers Headers to be used in the request + * @param array|string $params Can be nested for arrays and hashes * * - * @return String + * @return string */ public function request(string $url, array $headers, $params): string { $handle = curl_init($url); + if ($handle === false) { + // throw Error here with all codes + throw AmazonErrors::getError( + 'FAILURE', + 'C001', + 'CurlInitError', + 'Failed to init curl with url: ' . $url, + 0 + ); + } curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); // curl_setopt($handle, CURLOPT_FAILONERROR, true); @@ -39,7 +49,7 @@ class Client implements ClientInterface $err = curl_errno($handle); AmazonDebug::writeLog(['CURL_REQUEST_RESULT' => $result]); // extract all the error codes from Amazon - $result_ar = json_decode($result, true); + $result_ar = json_decode((string)$result, true); // if message is 'Rate exceeded', set different error if (($result_ar['message'] ?? '') == 'Rate exceeded') { $error_status = 'RESEND'; @@ -62,14 +72,14 @@ class Client implements ClientInterface $err ); } - return $result; + return (string)$result; } /** * Undocumented function * * @param string $url - * @param string $errno + * @param int $errno * @param string $message * @return void */ @@ -97,7 +107,7 @@ class Client implements ClientInterface // throw an error like in the normal reqeust, but set to CURL error throw AmazonErrors::getError( 'FAILURE', - 'C001', + 'C002', 'CurlError', $message, $errno diff --git a/src/Client/ClientInterface.php b/src/Client/ClientInterface.php index 39e8dbc..ef0b66a 100644 --- a/src/Client/ClientInterface.php +++ b/src/Client/ClientInterface.php @@ -5,9 +5,10 @@ namespace gullevek\AmazonIncentives\Client; interface ClientInterface { /** - * @param string $url The URL being requested, including domain and protocol - * @param array $headers Headers to be used in the request - * @param array|string $params Can be nested for arrays and hashes + * @param string $url The URL being requested, + * including domain and protocol + * @param array $headers Headers to be used in the request + * @param array|string $params Can be nested for arrays and hashes * * @return String */ diff --git a/src/Config/Config.php b/src/Config/Config.php index ee8029b..00e8ed5 100644 --- a/src/Config/Config.php +++ b/src/Config/Config.php @@ -44,12 +44,12 @@ class Config implements ConfigInterface ?string $currency, ?bool $debug, ) { - $this->setAccessKey($key ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); - $this->setSecret($secret ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); - $this->setPartner($partner ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); - $this->setEndpoint($endpoint ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); - $this->setCurrency($currency ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); - $this->setDebug($debug ?: $this->parseEnv('AWS_DEBUG')); + $this->setAccessKey(($key) ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); /** @phpstan-ignore-line */ + $this->setSecret(($secret) ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); /** @phpstan-ignore-line */ + $this->setPartner(($partner) ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); /** @phpstan-ignore-line */ + $this->setEndpoint(($endpoint) ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); /** @phpstan-ignore-line */ + $this->setCurrency(($currency) ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); /** @phpstan-ignore-line */ + $this->setDebug(($debug) ?: $this->parseEnv('AWS_DEBUG')); /** @phpstan-ignore-line */ } /** @@ -94,7 +94,7 @@ class Config implements ConfigInterface public function setEndpoint(string $endpoint): ConfigInterface { // TODO: check valid endpoint + set region - $this->endpoint = parse_url($endpoint, PHP_URL_HOST); + $this->endpoint = (parse_url($endpoint, PHP_URL_HOST)) ?: ''; return $this; } @@ -177,9 +177,9 @@ class Config implements ConfigInterface } /** - * @return bool|null + * @return bool */ - public function getDebug(): ?bool + public function getDebug(): bool { return $this->debug; } diff --git a/src/Debug/AmazonDebug.php b/src/Debug/AmazonDebug.php index f3ad48e..2d767bc 100644 --- a/src/Debug/AmazonDebug.php +++ b/src/Debug/AmazonDebug.php @@ -7,8 +7,17 @@ namespace gullevek\AmazonIncentives\Debug; class AmazonDebug { + /** + * @var array + */ private static $log = []; + /** + * @var bool + */ private static $debug = false; + /** + * @var string|null; + */ private static $id = null; /** @@ -74,7 +83,7 @@ class AmazonDebug * Will be pushed as new array entry int log * Main key is the set Id for this run * - * @param array $data Any array data to store in the log + * @param array $data Any array data to store in the log * @return void */ public static function writeLog(array $data): void @@ -91,7 +100,7 @@ class AmazonDebug * * @param string|null $id If set returns only this id logs * or empty array if not found - * @return array Always array, empty if not data or not found + * @return array Always array, empty if not data or not found */ public static function getLog(?string $id = null): array { diff --git a/src/Exceptions/AmazonErrors.php b/src/Exceptions/AmazonErrors.php index e0fa74a..d09e0f2 100644 --- a/src/Exceptions/AmazonErrors.php +++ b/src/Exceptions/AmazonErrors.php @@ -5,14 +5,14 @@ namespace gullevek\AmazonIncentives\Exceptions; use RuntimeException; use gullevek\AmazonIncentives\Debug\AmazonDebug; -class AmazonErrors extends RuntimeException +final class AmazonErrors extends RuntimeException { /** * @param string $error_status agcodResponse->status from Amazon * @param string $error_code errorCode from Amazon * @param string $error_type errorType from Amazon * @param string $message - * @param string $_error_code + * @param int $_error_code * @return AmazonErrors */ public static function getError( @@ -20,11 +20,11 @@ class AmazonErrors extends RuntimeException string $error_code, string $error_type, string $message, - string $_error_code + int $_error_code ): self { // NOTE: if xdebug.show_exception_trace is set to 1 this will print ERRORS return new static( - json_encode([ + (json_encode([ 'status' => $error_status, 'code' => $error_code, 'type' => $error_type, @@ -32,7 +32,7 @@ class AmazonErrors extends RuntimeException // atach log data if exists 'log_id' => AmazonDebug::getId(), 'log' => AmazonDebug::getLog(), - ]), + ])) ?: 'AmazonErrors: json encode problem: ' . $message, $_error_code ); } diff --git a/src/Response/CancelResponse.php b/src/Response/CancelResponse.php index 1e20073..1b179a0 100644 --- a/src/Response/CancelResponse.php +++ b/src/Response/CancelResponse.php @@ -28,31 +28,26 @@ class CancelResponse /** * Amazon Gift Card Raw JSON * - * @var string + * @var array */ protected $raw_json; - /** - * @var array - */ - protected $log; /** * Response constructor. - * @param array $json_response + * @param array $json_response */ public function __construct(array $json_response) { $this->raw_json = $json_response; - $this->log = AmazonDebug::getLog(AmazonDebug::getId()); $this->parseJsonResponse($json_response); } /** - * @return array + * @return array */ public function getLog(): array { - return $this->log; + return AmazonDebug::getLog(AmazonDebug::getId()); } /** @@ -84,11 +79,11 @@ class CancelResponse */ public function getRawJson(): string { - return json_encode($this->raw_json); + return (json_encode($this->raw_json)) ?: ''; } /** - * @param array $json_response + * @param array $json_response * @return CancelResponse */ public function parseJsonResponse(array $json_response): self diff --git a/src/Response/CreateBalanceResponse.php b/src/Response/CreateBalanceResponse.php index a0888cb..ef10719 100644 --- a/src/Response/CreateBalanceResponse.php +++ b/src/Response/CreateBalanceResponse.php @@ -34,32 +34,27 @@ class CreateBalanceResponse /** * Amazon Gift Card Raw JSON * - * @var string + * @var array */ protected $raw_json; - /** - * @var array - */ - protected $log; /** * Response constructor. * - * @param array $json_response + * @param array $json_response */ public function __construct(array $json_response) { $this->raw_json = $json_response; - $this->log = AmazonDebug::getLog(AmazonDebug::getId()); $this->parseJsonResponse($json_response); } /** - * @return array + * @return array */ public function getLog(): array { - return $this->log; + return AmazonDebug::getLog(AmazonDebug::getId()); } /** @@ -99,13 +94,13 @@ class CreateBalanceResponse */ public function getRawJson(): string { - return json_encode($this->raw_json); + return (json_encode($this->raw_json)) ?: ''; } /** * Undocumented function * - * @param array $json_response + * @param array $json_response * @return CreateBalanceResponse */ public function parseJsonResponse(array $json_response): self diff --git a/src/Response/CreateResponse.php b/src/Response/CreateResponse.php index 15b1525..a1085ea 100644 --- a/src/Response/CreateResponse.php +++ b/src/Response/CreateResponse.php @@ -62,31 +62,26 @@ class CreateResponse /** * Amazon Gift Card Raw JSON * - * @var string + * @var array */ protected $raw_json; - /** - * @var array - */ - protected $log; /** * Response constructor. - * @param array $json_response + * @param array $json_response */ public function __construct(array $json_response) { $this->raw_json = $json_response; - $this->log = AmazonDebug::getLog(AmazonDebug::getId()); $this->parseJsonResponse($json_response); } /** - * @return array + * @return array */ public function getLog(): array { - return $this->log; + return AmazonDebug::getLog(AmazonDebug::getId()); } /** @@ -114,9 +109,9 @@ class CreateResponse } /** - * @return string + * @return float */ - public function getValue(): string + public function getValue(): float { return $this->value; } @@ -159,11 +154,11 @@ class CreateResponse */ public function getRawJson(): string { - return json_encode($this->raw_json); + return (json_encode($this->raw_json)) ?: ''; } /** - * @param array $json_response + * @param array $json_response * @return CreateResponse */ public function parseJsonResponse(array $json_response): self diff --git a/test/aws_gift_card_tests.php b/test/aws_gift_card_tests.php index f660d36..c51eaeb 100644 --- a/test/aws_gift_card_tests.php +++ b/test/aws_gift_card_tests.php @@ -6,7 +6,7 @@ * write log as string from array data * includes timestamp * - * @param array $data Debug log array data to add to the json string + * @param array $data Debug log array data to add to the json string * @return string */ function writeLog(array $data): string @@ -25,16 +25,16 @@ function writeLog(array $data): string */ function dateTr(string $date): string { - return date('Y-m-d H:i:s', strtotime($date)); + return date('Y-m-d H:i:s', (strtotime($date)) ?: null); } /** * print exception string * - * @param string $call_request Call request, eg buyGiftCard - * @param integer $error_code $e Exception error code - * @param array $error Array from the Exception message json string - * @param boolean $debug_print If we should show the debug log + * @param string $call_request Call request, eg buyGiftCard + * @param integer $error_code $e Exception error code + * @param array $error Array from the Exception message json string + * @param boolean $debug_print If we should show the debug log * @return void */ function printException( @@ -93,6 +93,9 @@ foreach ( // open debug file output $fp = fopen('log/debug.' . date('YmdHis') . '.log', 'w'); +if (!is_resource($fp)) { + die("Cannot open log debug file"); +} // run info test (prints ENV vars) $run_info_test = false; @@ -221,6 +224,7 @@ if ($run_gift_tests === true) { $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value, $creation_request_id); $request_status = $aws_test->getStatus(); // same? + $claim_code = $aws_test->getClaimCode(); $expiration_date = $aws_test->getExpirationDate(); print "AWS: buyGiftCard: SAME CODE A AGAIN: " . $request_status . ": " . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " @@ -241,7 +245,7 @@ if ($run_gift_tests === true) { } // MOCK TEST -if ($mock_debug === true) { +if ($run_mocks === true) { $mock_ok = 'MOCK OK'; $mock_failure = 'MOCK FAILURE'; $mock_value = 500;