diff --git a/.gitignore b/.gitignore index 51714f6..f661f50 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ vendor composer.lock **/.env **/.target +.phpunit.cache/ +tools/ diff --git a/.phive/phars.xml b/.phive/phars.xml new file mode 100644 index 0000000..592ec5c --- /dev/null +++ b/.phive/phars.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Readme.md b/README.md similarity index 95% rename from Readme.md rename to README.md index 20e976e..48c55c7 100644 --- a/Readme.md +++ b/README.md @@ -152,3 +152,19 @@ New entries can be written with On sucessful run the log data is accessable with `$aws->getLog()` On exception the log data is in the error message json (see exceptions) + +## Development + +### Phan + +`vendor/bin/phan --analyze-twice` + +### PHPstan + +`vendor/bin/phpstan` + +### PHPUnit + +Unit tests have to be run from base folder with + +`vendor/bin/phpunit test/phpUnitTests/` diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..cfc7a3d --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,18 @@ + + + PSR12 override rules (strict, standard). Switch spaces indent to tab. + + + + + + + + + + + + + + + diff --git a/src/AWS/AWS.php b/src/AWS/AWS.php index f6340e8..ee6bcf6 100644 --- a/src/AWS/AWS.php +++ b/src/AWS/AWS.php @@ -15,528 +15,528 @@ use gullevek\AmazonIncentives\Handle\Json; class AWS { - /** @var string What AWS Service to use: Gift Card on Demand (GCOD) */ - public const SERVICE_NAME = 'AGCODService'; - /** @var string */ - public const ACCEPT_HEADER = 'accept'; - /** @var string content-type */ - public const CONTENT_HEADER = 'content-type'; - /** @var string */ - public const HOST_HEADER = 'host'; - /** @var string */ - public const X_AMZ_DATE_HEADER = 'x-amz-date'; - /** @var string */ - public const X_AMZ_TARGET_HEADER = 'x-amz-target'; - /** @var string */ - public const AUTHORIZATION_HEADER = 'Authorization'; - /** @var string type of encryption type */ - public const AWS_SHA256_ALGORITHM = 'AWS4-HMAC-SHA256'; - /** @var string key type to use */ - public const KEY_QUALIFIER = 'AWS4'; - /** @var string */ - public const TERMINATION_STRING = 'aws4_request'; - /** @var string Service to use: Create Gift Card */ - public const CREATE_GIFT_CARD_SERVICE = 'CreateGiftCard'; - /** @var string Service to use: Cancle Gift Card */ - public const CANCEL_GIFT_CARD_SERVICE = 'CancelGiftCard'; - /** @var string Service to use: Get Available Funds */ - public const GET_AVAILABLE_FUNDS_SERVICE = 'GetAvailableFunds'; + /** @var string What AWS Service to use: Gift Card on Demand (GCOD) */ + public const SERVICE_NAME = 'AGCODService'; + /** @var string */ + public const ACCEPT_HEADER = 'accept'; + /** @var string content-type */ + public const CONTENT_HEADER = 'content-type'; + /** @var string */ + public const HOST_HEADER = 'host'; + /** @var string */ + public const X_AMZ_DATE_HEADER = 'x-amz-date'; + /** @var string */ + public const X_AMZ_TARGET_HEADER = 'x-amz-target'; + /** @var string */ + public const AUTHORIZATION_HEADER = 'Authorization'; + /** @var string type of encryption type */ + public const AWS_SHA256_ALGORITHM = 'AWS4-HMAC-SHA256'; + /** @var string key type to use */ + public const KEY_QUALIFIER = 'AWS4'; + /** @var string */ + public const TERMINATION_STRING = 'aws4_request'; + /** @var string Service to use: Create Gift Card */ + public const CREATE_GIFT_CARD_SERVICE = 'CreateGiftCard'; + /** @var string Service to use: Cancle Gift Card */ + public const CANCEL_GIFT_CARD_SERVICE = 'CancelGiftCard'; + /** @var string Service to use: Get Available Funds */ + public const GET_AVAILABLE_FUNDS_SERVICE = 'GetAvailableFunds'; - /** @var Config Configuration class with all settings */ - private $config; + /** @var Config Configuration class with all settings */ + private $config; - /** - * Initialize the main AWS class. This class prepares and sends all the actions - * and returns reponses as defined in in the CreateResponse class - * - * @param Config $config - */ - public function __construct(Config $config) - { - $this->config = $config; - AmazonDebug::writeLog([__METHOD__ => date('Y-m-d H:m:s.u')]); - } + /** + * Initialize the main AWS class. This class prepares and sends all the actions + * and returns reponses as defined in in the CreateResponse class + * + * @param Config $config + */ + public function __construct(Config $config) + { + $this->config = $config; + AmazonDebug::writeLog([__METHOD__ => date('Y-m-d H:m:s.u')]); + } - /** - * Bug a gift card - * - * @param float $amount Amount to buy a gifr card in set currencty - * @param string|null $creation_id Override creation id, if not set will - * be created automatically. If not valid error - * will be thrown - * @return CreateResponse Object with AWS response data - * - * @throws AmazonErrors - */ - public function getCode(float $amount, ?string $creation_id = null): CreateResponse - { - $service_operation = self::CREATE_GIFT_CARD_SERVICE; - $payload = $this->getGiftCardPayload($amount, $creation_id); - $canonical_request = $this->getCanonicalRequest($service_operation, $payload); - $date_time_string = $this->getTimestamp(); - AmazonDebug::writeLog(['call' => __METHOD__]); - $result = Json::jsonDecode($this->makeRequest( - $payload, - $canonical_request, - $service_operation, - $date_time_string - )); - return new CreateResponse($result); - } + /** + * Bug a gift card + * + * @param float $amount Amount to buy a gifr card in set currencty + * @param string|null $creation_id Override creation id, if not set will + * be created automatically. If not valid error + * will be thrown + * @return CreateResponse Object with AWS response data + * + * @throws AmazonErrors + */ + public function getCode(float $amount, ?string $creation_id = null): CreateResponse + { + $service_operation = self::CREATE_GIFT_CARD_SERVICE; + $payload = $this->getGiftCardPayload($amount, $creation_id); + $canonical_request = $this->getCanonicalRequest($service_operation, $payload); + $date_time_string = $this->getTimestamp(); + AmazonDebug::writeLog(['call' => __METHOD__]); + $result = Json::jsonDecode($this->makeRequest( + $payload, + $canonical_request, + $service_operation, + $date_time_string + )); + return new CreateResponse($result); + } - /** - * Cancle an ordered gift card, only possible within the the time limit - * - * @param string $creation_request_id Previously created creation request id - * @param string $gift_card_id Previously created gift card id - * @return CancelResponse Object with AWS response data - * - * @throws AmazonErrors - */ - public function cancelCode(string $creation_request_id, string $gift_card_id): CancelResponse - { - $service_operation = self::CANCEL_GIFT_CARD_SERVICE; - $payload = $this->getCancelGiftCardPayload($creation_request_id, $gift_card_id); - $canonical_request = $this->getCanonicalRequest($service_operation, $payload); - $date_time_string = $this->getTimestamp(); - AmazonDebug::writeLog(['call' => __METHOD__]); - $result = Json::jsonDecode($this->makeRequest( - $payload, - $canonical_request, - $service_operation, - $date_time_string - )); - return new CancelResponse($result); - } + /** + * Cancle an ordered gift card, only possible within the the time limit + * + * @param string $creation_request_id Previously created creation request id + * @param string $gift_card_id Previously created gift card id + * @return CancelResponse Object with AWS response data + * + * @throws AmazonErrors + */ + public function cancelCode(string $creation_request_id, string $gift_card_id): CancelResponse + { + $service_operation = self::CANCEL_GIFT_CARD_SERVICE; + $payload = $this->getCancelGiftCardPayload($creation_request_id, $gift_card_id); + $canonical_request = $this->getCanonicalRequest($service_operation, $payload); + $date_time_string = $this->getTimestamp(); + AmazonDebug::writeLog(['call' => __METHOD__]); + $result = Json::jsonDecode($this->makeRequest( + $payload, + $canonical_request, + $service_operation, + $date_time_string + )); + return new CancelResponse($result); + } - /** - * Get current account funds - * - * @return CreateBalanceResponse Object with AWS response data - * - * @throws AmazonErrors - */ - public function getBalance(): CreateBalanceResponse - { - $service_operation = self::GET_AVAILABLE_FUNDS_SERVICE; - $payload = $this->getAvailableFundsPayload(); - $canonical_request = $this->getCanonicalRequest($service_operation, $payload); - $date_time_string = $this->getTimestamp(); - AmazonDebug::writeLog(['call' => __METHOD__]); - $result = Json::jsonDecode($this->makeRequest( - $payload, - $canonical_request, - $service_operation, - $date_time_string - )); - return new CreateBalanceResponse($result); - } + /** + * Get current account funds + * + * @return CreateBalanceResponse Object with AWS response data + * + * @throws AmazonErrors + */ + public function getBalance(): CreateBalanceResponse + { + $service_operation = self::GET_AVAILABLE_FUNDS_SERVICE; + $payload = $this->getAvailableFundsPayload(); + $canonical_request = $this->getCanonicalRequest($service_operation, $payload); + $date_time_string = $this->getTimestamp(); + AmazonDebug::writeLog(['call' => __METHOD__]); + $result = Json::jsonDecode($this->makeRequest( + $payload, + $canonical_request, + $service_operation, + $date_time_string + )); + return new CreateBalanceResponse($result); + } - /** - * return a new curl connection client class - * - * @return Client Curl connection Client - */ - public function newClient(): Client - { - return new Client(); - } + /** + * return a new curl connection client class + * + * @return Client Curl connection Client + */ + public function newClient(): Client + { + return new Client(); + } - /** - * General request method for all actions - * Calls the Client class that actually runs the json request - * For service_operation valid data see AWS GCOD documentation - * - * @param string $payload The data needed for this request - * @param string $canonical_request Header data to send for this request - * @param string $service_operation Service operation. CREATE_GIFT_CARD_SERVICE, - * CANCEL_GIFT_CARD_SERVICE or - * GET_AVAILABLE_FUNDS_SERVICE constant values - * @param string $date_time_string Ymd\THis\Z encoded timestamp, getTimestamp() - * @return string Request result as string, json data - */ - public function makeRequest( - string $payload, - string $canonical_request, - string $service_operation, - string $date_time_string - ): string { - // debug - AmazonDebug::writeLog([__METHOD__ => [ - 'Operation' => $service_operation, - 'Payload' => $payload, - 'Cannonical Request' => $canonical_request, - 'Date Time String' => $date_time_string + /** + * General request method for all actions + * Calls the Client class that actually runs the json request + * For service_operation valid data see AWS GCOD documentation + * + * @param string $payload The data needed for this request + * @param string $canonical_request Header data to send for this request + * @param string $service_operation Service operation. CREATE_GIFT_CARD_SERVICE, + * CANCEL_GIFT_CARD_SERVICE or + * GET_AVAILABLE_FUNDS_SERVICE constant values + * @param string $date_time_string Ymd\THis\Z encoded timestamp, getTimestamp() + * @return string Request result as string, json data + */ + public function makeRequest( + string $payload, + string $canonical_request, + string $service_operation, + string $date_time_string + ): string { + // debug + AmazonDebug::writeLog([__METHOD__ => [ + 'Operation' => $service_operation, + 'Payload' => $payload, + 'Cannonical Request' => $canonical_request, + 'Date Time String' => $date_time_string - ]]); - $KEY_QUALIFIER = self::KEY_QUALIFIER; - $canonical_request_hash = $this->buildHash($canonical_request); - $string_to_sign = $this->buildStringToSign($canonical_request_hash); - $authorization_value = $this->buildAuthSignature($string_to_sign); + ]]); + $KEY_QUALIFIER = self::KEY_QUALIFIER; + $canonical_request_hash = $this->buildHash($canonical_request); + $string_to_sign = $this->buildStringToSign($canonical_request_hash); + $authorization_value = $this->buildAuthSignature($string_to_sign); - $secret_key = $this->config->getSecret(); - $endpoint = $this->config->getEndpoint(); - $region_name = $this->getRegion(); + $secret_key = $this->config->getSecret(); + $endpoint = $this->config->getEndpoint(); + $region_name = $this->getRegion(); - $SERVICE_NAME = 'AGCODService'; - $service_target = 'com.amazonaws.agcod.' . $SERVICE_NAME . '.' . $service_operation; - $date_string = $this->getDateString(); + $SERVICE_NAME = 'AGCODService'; + $service_target = 'com.amazonaws.agcod.' . $SERVICE_NAME . '.' . $service_operation; + $date_string = $this->getDateString(); - $signature_aws_key = $KEY_QUALIFIER . $secret_key; + $signature_aws_key = $KEY_QUALIFIER . $secret_key; - $k_date = $this->hmac($date_string, $signature_aws_key); - $k_date_hexis = $this->hmac($date_string, $signature_aws_key, false); - $k_region = $this->hmac($region_name, $k_date); - $k_region_hexis = $this->hmac($region_name, $k_date, false); - $k_service_hexis = $this->hmac($SERVICE_NAME, $k_region, false); + $k_date = $this->hmac($date_string, $signature_aws_key); + $k_date_hexis = $this->hmac($date_string, $signature_aws_key, false); + $k_region = $this->hmac($region_name, $k_date); + $k_region_hexis = $this->hmac($region_name, $k_date, false); + $k_service_hexis = $this->hmac($SERVICE_NAME, $k_region, false); - AmazonDebug::writeLog([__METHOD__ => [ - 'Date' => $k_date_hexis, - 'Region' => $k_region_hexis, - 'Service' => $k_service_hexis, - ]]); + AmazonDebug::writeLog([__METHOD__ => [ + 'Date' => $k_date_hexis, + 'Region' => $k_region_hexis, + 'Service' => $k_service_hexis, + ]]); - $url = 'https://' . $endpoint . '/' . $service_operation; - $headers = $this->buildHeaders( - $payload, - $authorization_value, - $date_time_string, - $service_target - ); - return ($this->newClient())->request($url, $headers, $payload); - } + $url = 'https://' . $endpoint . '/' . $service_operation; + $headers = $this->buildHeaders( + $payload, + $authorization_value, + $date_time_string, + $service_target + ); + return ($this->newClient())->request($url, $headers, $payload); + } - /** - * Build the headers used in the makeRequest method. - * These are the HTML headers used with curl - * - * @param string $payload Paylout to create this header for - * @param string $authorization_value Auth string - * @param string $date_time_string Ymd\THis\Z encoded timestamp, getTimestamp() - * @param string $service_target Target service in the agcod string: - * Value like com.amazonaws.agcod.. - * @return array Header data as array for curl request - */ - public function buildHeaders( - string $payload, - string $authorization_value, - string $date_time_string, - string $service_target - ): array { - $ACCEPT_HEADER = self::ACCEPT_HEADER; - $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; - $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; - $AUTHORIZATION_HEADER = self::AUTHORIZATION_HEADER; - return [ - 'Content-Type:' . $this->getContentType(), - 'Content-Length: ' . strlen($payload), - $AUTHORIZATION_HEADER . ':' . $authorization_value, - $X_AMZ_DATE_HEADER . ':' . $date_time_string, - $X_AMZ_TARGET_HEADER . ':' . $service_target, - $ACCEPT_HEADER . ':' . $this->getContentType() - ]; - } + /** + * Build the headers used in the makeRequest method. + * These are the HTML headers used with curl + * + * @param string $payload Paylout to create this header for + * @param string $authorization_value Auth string + * @param string $date_time_string Ymd\THis\Z encoded timestamp, getTimestamp() + * @param string $service_target Target service in the agcod string: + * Value like com.amazonaws.agcod.. + * @return array Header data as array for curl request + */ + public function buildHeaders( + string $payload, + string $authorization_value, + string $date_time_string, + string $service_target + ): array { + $ACCEPT_HEADER = self::ACCEPT_HEADER; + $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; + $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; + $AUTHORIZATION_HEADER = self::AUTHORIZATION_HEADER; + return [ + 'Content-Type:' . $this->getContentType(), + 'Content-Length: ' . strlen($payload), + $AUTHORIZATION_HEADER . ':' . $authorization_value, + $X_AMZ_DATE_HEADER . ':' . $date_time_string, + $X_AMZ_TARGET_HEADER . ':' . $service_target, + $ACCEPT_HEADER . ':' . $this->getContentType() + ]; + } - /** - * The request string build with the actauly request data created by - * getCanonicalRequest(). This string is used in the auth signature call - * - * @param string $canonical_request_hash sha256 hash to build from - * @return string String to send to buildAuthSignature() - */ - public function buildStringToSign($canonical_request_hash): string - { - $AWS_SHA256_ALGORITHM = self::AWS_SHA256_ALGORITHM; - $TERMINATION_STRING = self::TERMINATION_STRING; - $SERVICE_NAME = self::SERVICE_NAME; - $region_name = $this->getRegion(); - $date_time_string = $this->getTimestamp(); - $date_string = $this->getDateString(); - $string_to_sign = "$AWS_SHA256_ALGORITHM\n" - . "$date_time_string\n" - . "$date_string/$region_name/$SERVICE_NAME/$TERMINATION_STRING\n" - . "$canonical_request_hash"; + /** + * The request string build with the actauly request data created by + * getCanonicalRequest(). This string is used in the auth signature call + * + * @param string $canonical_request_hash sha256 hash to build from + * @return string String to send to buildAuthSignature() + */ + public function buildStringToSign($canonical_request_hash): string + { + $AWS_SHA256_ALGORITHM = self::AWS_SHA256_ALGORITHM; + $TERMINATION_STRING = self::TERMINATION_STRING; + $SERVICE_NAME = self::SERVICE_NAME; + $region_name = $this->getRegion(); + $date_time_string = $this->getTimestamp(); + $date_string = $this->getDateString(); + $string_to_sign = "$AWS_SHA256_ALGORITHM\n" + . "$date_time_string\n" + . "$date_string/$region_name/$SERVICE_NAME/$TERMINATION_STRING\n" + . "$canonical_request_hash"; - return $string_to_sign; - } + return $string_to_sign; + } - /** - * Build the authentication signature used in the buildHeaders method - * - * @param string $string_to_sign Data to sign, buildStringToSign() - * @return string Authorized value as string - */ - public function buildAuthSignature(string $string_to_sign): string - { - $AWS_SHA256_ALGORITHM = self::AWS_SHA256_ALGORITHM; - $SERVICE_NAME = self::SERVICE_NAME; - $TERMINATION_STRING = self::TERMINATION_STRING; - $ACCEPT_HEADER = self::ACCEPT_HEADER; - $HOST_HEADER = self::HOST_HEADER; - $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; - $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; + /** + * Build the authentication signature used in the buildHeaders method + * + * @param string $string_to_sign Data to sign, buildStringToSign() + * @return string Authorized value as string + */ + public function buildAuthSignature(string $string_to_sign): string + { + $AWS_SHA256_ALGORITHM = self::AWS_SHA256_ALGORITHM; + $SERVICE_NAME = self::SERVICE_NAME; + $TERMINATION_STRING = self::TERMINATION_STRING; + $ACCEPT_HEADER = self::ACCEPT_HEADER; + $HOST_HEADER = self::HOST_HEADER; + $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; + $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; - $aws_key_id = $this->config->getAccessKey(); - $region_name = $this->getRegion(); + $aws_key_id = $this->config->getAccessKey(); + $region_name = $this->getRegion(); - $date_string = $this->getDateString(); - $derived_key = $this->buildDerivedKey(); - // Calculate signature per http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html - $final_signature = $this->hmac($string_to_sign, $derived_key, false); + $date_string = $this->getDateString(); + $derived_key = $this->buildDerivedKey(); + // Calculate signature per http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + $final_signature = $this->hmac($string_to_sign, $derived_key, false); - // Assemble Authorization Header with signing information - // per http://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html - $authorization_value = - $AWS_SHA256_ALGORITHM - . ' Credential=' . $aws_key_id - . '/' . $date_string . '/' . $region_name . '/' . $SERVICE_NAME . '/' . $TERMINATION_STRING . ',' - . ' SignedHeaders=' - . $ACCEPT_HEADER . ';' . $HOST_HEADER . ';' . $X_AMZ_DATE_HEADER . ';' . $X_AMZ_TARGET_HEADER . ',' - . ' Signature=' - . $final_signature; + // Assemble Authorization Header with signing information + // per http://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html + $authorization_value = + $AWS_SHA256_ALGORITHM + . ' Credential=' . $aws_key_id + . '/' . $date_string . '/' . $region_name . '/' . $SERVICE_NAME . '/' . $TERMINATION_STRING . ',' + . ' SignedHeaders=' + . $ACCEPT_HEADER . ';' . $HOST_HEADER . ';' . $X_AMZ_DATE_HEADER . ';' . $X_AMZ_TARGET_HEADER . ',' + . ' Signature=' + . $final_signature; - return $authorization_value; - } + return $authorization_value; + } - /** - * Build the derived key to build the final hmac signature string - * - * @param bool $rawOutput Set to true to create the hash based message - * authenticator string as normal text string or - * lowercase hexbits - * @return string Derived key (hmac type) - */ - public function buildDerivedKey(bool $rawOutput = true): string - { - $KEY_QUALIFIER = self::KEY_QUALIFIER; - $TERMINATION_STRING = self::TERMINATION_STRING; - $SERVICE_NAME = self::SERVICE_NAME; + /** + * Build the derived key to build the final hmac signature string + * + * @param bool $rawOutput Set to true to create the hash based message + * authenticator string as normal text string or + * lowercase hexbits + * @return string Derived key (hmac type) + */ + public function buildDerivedKey(bool $rawOutput = true): string + { + $KEY_QUALIFIER = self::KEY_QUALIFIER; + $TERMINATION_STRING = self::TERMINATION_STRING; + $SERVICE_NAME = self::SERVICE_NAME; - $aws_secret_key = $this->config->getSecret(); - // Append Key Qualifier, "AWS4", to secret key per - // shttp://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html - $signature_aws_key = $KEY_QUALIFIER . $aws_secret_key; - $region_name = $this->getRegion(); - $date_string = $this->getDateString(); + $aws_secret_key = $this->config->getSecret(); + // Append Key Qualifier, "AWS4", to secret key per + // shttp://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html + $signature_aws_key = $KEY_QUALIFIER . $aws_secret_key; + $region_name = $this->getRegion(); + $date_string = $this->getDateString(); - $k_date = $this->hmac($date_string, $signature_aws_key); - $k_region = $this->hmac($region_name, $k_date); - $k_service = $this->hmac($SERVICE_NAME, $k_region); + $k_date = $this->hmac($date_string, $signature_aws_key); + $k_region = $this->hmac($region_name, $k_date); + $k_service = $this->hmac($SERVICE_NAME, $k_region); - // Derived the Signing key (derivedKey aka kSigning) - return $this->hmac($TERMINATION_STRING, $k_service, $rawOutput); - } + // Derived the Signing key (derivedKey aka kSigning) + return $this->hmac($TERMINATION_STRING, $k_service, $rawOutput); + } - /** - * get the region based on endpoint - * list as of 2021/10/20 - * WHERE URL REGION - * North America https://agcod-v2-gamma.amazon.com us-east-1 - * https://agcod-v2.amazon.com - * (US, CA, MX) - * Europe and Asia https://agcod-v2-eu-gamma.amazon.com eu-west-1 - * https://agcod-v2-eu.amazon.com - * (IT, ES, DE, FR, UK, TR, UAE, KSA, PL, NL, SE) - * Far East https://agcod-v2-fe-gamma.amazon.com us-west-2 - * https://agcod-v2-fe.amazon.com - * (JP, AU, SG) - * - * CURRENCY - * USD for US - * EUR for EU (IT, ES, DE, FR, PL, NL, SE) - * JPY for JP - * CAD for CA - * AUD for AU - * TRY for TR - * AED for UAE - * MXN for MX - * GBP for UK - * - * @return string Region string depending on given endpoint url - */ - public function getRegion(): string - { - $endpoint = $this->config->getEndpoint(); - // default region - $region_name = 'us-east-1'; + /** + * get the region based on endpoint + * list as of 2021/10/20 + * WHERE URL REGION + * North America https://agcod-v2-gamma.amazon.com us-east-1 + * https://agcod-v2.amazon.com + * (US, CA, MX) + * Europe and Asia https://agcod-v2-eu-gamma.amazon.com eu-west-1 + * https://agcod-v2-eu.amazon.com + * (IT, ES, DE, FR, UK, TR, UAE, KSA, PL, NL, SE) + * Far East https://agcod-v2-fe-gamma.amazon.com us-west-2 + * https://agcod-v2-fe.amazon.com + * (JP, AU, SG) + * + * CURRENCY + * USD for US + * EUR for EU (IT, ES, DE, FR, PL, NL, SE) + * JPY for JP + * CAD for CA + * AUD for AU + * TRY for TR + * AED for UAE + * MXN for MX + * GBP for UK + * + * @return string Region string depending on given endpoint url + */ + public function getRegion(): string + { + $endpoint = $this->config->getEndpoint(); + // default region + $region_name = 'us-east-1'; - switch ($endpoint) { - case 'agcod-v2.amazon.com': - case 'agcod-v2-gamma.amazon.com': - $region_name = 'us-east-1'; - break; - case 'agcod-v2-eu.amazon.com': - case 'agcod-v2-eu-gamma.amazon.com': - $region_name = 'eu-west-1'; - break; - case 'agcod-v2-fe.amazon.com': - case 'agcod-v2-fe-gamma.amazon.com': - $region_name = 'us-west-2'; - break; - } - return $region_name; - } + switch ($endpoint) { + case 'agcod-v2.amazon.com': + case 'agcod-v2-gamma.amazon.com': + $region_name = 'us-east-1'; + break; + case 'agcod-v2-eu.amazon.com': + case 'agcod-v2-eu-gamma.amazon.com': + $region_name = 'eu-west-1'; + break; + case 'agcod-v2-fe.amazon.com': + case 'agcod-v2-fe-gamma.amazon.com': + $region_name = 'us-west-2'; + break; + } + return $region_name; + } - /** - * The actual data to send as json encoded string for creating a gift card. - * The creation request id must be in the format: - * _ - * - * @param float $amount Amount of currencty to create the gift card - * request for - * @param string|null $creation_id The creation id, if not set will be created here - * @return string JSON encoded array to be used as payload - * in get gift card call - */ - public function getGiftCardPayload(float $amount, ?string $creation_id = null): string - { - $payload = [ - 'creationRequestId' => $creation_id ?: uniqid($this->config->getPartner() . '_'), - 'partnerId' => $this->config->getPartner(), - 'value' => - [ - 'currencyCode' => $this->config->getCurrency(), - 'amount' => $amount - ] - ]; - return (json_encode($payload)) ?: ''; - } + /** + * The actual data to send as json encoded string for creating a gift card. + * The creation request id must be in the format: + * _ + * + * @param float $amount Amount of currencty to create the gift card + * request for + * @param string|null $creation_id The creation id, if not set will be created here + * @return string JSON encoded array to be used as payload + * in get gift card call + */ + public function getGiftCardPayload(float $amount, ?string $creation_id = null): string + { + $payload = [ + 'creationRequestId' => $creation_id ?: uniqid($this->config->getPartner() . '_'), + 'partnerId' => $this->config->getPartner(), + 'value' => + [ + 'currencyCode' => $this->config->getCurrency(), + 'amount' => $amount + ] + ]; + return (json_encode($payload)) ?: ''; + } - /** - * The actual data to send as json encoded string to cancel a created gift card - * - * @param string $creation_request_id Creation request id from previous get gift card - * @param string $gift_card_id Gift card id from previous get gift card - * @return string JSON encoded array to be used as payload - * in cancle gift card call - */ - public function getCancelGiftCardPayload(string $creation_request_id, string $gift_card_id): string - { - $payload = [ - 'creationRequestId' => $creation_request_id, - 'partnerId' => $this->config->getPartner(), - 'gcId' => $gift_card_id - ]; - return (json_encode($payload)) ?: ''; - } + /** + * The actual data to send as json encoded string to cancel a created gift card + * + * @param string $creation_request_id Creation request id from previous get gift card + * @param string $gift_card_id Gift card id from previous get gift card + * @return string JSON encoded array to be used as payload + * in cancle gift card call + */ + public function getCancelGiftCardPayload(string $creation_request_id, string $gift_card_id): string + { + $payload = [ + 'creationRequestId' => $creation_request_id, + 'partnerId' => $this->config->getPartner(), + 'gcId' => $gift_card_id + ]; + return (json_encode($payload)) ?: ''; + } - /** - * The actualy data to send as json encoded string for getting the current - * account funds - * - * @return string JSON encoded array to be used as payload in funds call - */ - public function getAvailableFundsPayload(): string - { - $payload = [ - 'partnerId' => $this->config->getPartner(), - ]; - return (json_encode($payload)) ?: ''; - } + /** + * The actualy data to send as json encoded string for getting the current + * account funds + * + * @return string JSON encoded array to be used as payload in funds call + */ + public function getAvailableFundsPayload(): string + { + $payload = [ + 'partnerId' => $this->config->getPartner(), + ]; + return (json_encode($payload)) ?: ''; + } - /** - * Heeders used in the getCanonicalRequest() - * - * @param string $service_operation Service operation code in the service string request - * Value is: com.amazonaws.agcod.AGCODService. - * @return string Header string to be used - */ - public function buildCanonicalHeaders(string $service_operation): string - { - $ACCEPT_HEADER = self::ACCEPT_HEADER; - $HOST_HEADER = self::HOST_HEADER; - $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; - $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; - $date_time_string = $this->getTimestamp(); - $endpoint = $this->config->getEndpoint(); - $content_type = $this->getContentType(); - return "$ACCEPT_HEADER:$content_type\n" - . "$HOST_HEADER:$endpoint\n" - . "$X_AMZ_DATE_HEADER:$date_time_string\n" - . "$X_AMZ_TARGET_HEADER:com.amazonaws.agcod.AGCODService.$service_operation"; - } + /** + * Heeders used in the getCanonicalRequest() + * + * @param string $service_operation Service operation code in the service string request + * Value is: com.amazonaws.agcod.AGCODService. + * @return string Header string to be used + */ + public function buildCanonicalHeaders(string $service_operation): string + { + $ACCEPT_HEADER = self::ACCEPT_HEADER; + $HOST_HEADER = self::HOST_HEADER; + $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; + $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; + $date_time_string = $this->getTimestamp(); + $endpoint = $this->config->getEndpoint(); + $content_type = $this->getContentType(); + return "$ACCEPT_HEADER:$content_type\n" + . "$HOST_HEADER:$endpoint\n" + . "$X_AMZ_DATE_HEADER:$date_time_string\n" + . "$X_AMZ_TARGET_HEADER:com.amazonaws.agcod.AGCODService.$service_operation"; + } - /** - * Headers used in the get/cancel/funds requests - * - * @param string $service_operation Service operation code to be used in header request - * and main request call - * @param string $payload Payload from get/cancle Code or funds call - * @return string Full POST service request code - */ - public function getCanonicalRequest(string $service_operation, string $payload): string - { - $HOST_HEADER = self::HOST_HEADER; - $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; - $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; - $ACCEPT_HEADER = self::ACCEPT_HEADER; - $payload_hash = $this->buildHash($payload); - $canonical_headers = $this->buildCanonicalHeaders($service_operation); - $canonical_request = "POST\n" - . "/$service_operation\n\n" - . "$canonical_headers\n\n" - . "$ACCEPT_HEADER;$HOST_HEADER;$X_AMZ_DATE_HEADER;$X_AMZ_TARGET_HEADER\n" - . "$payload_hash"; - return $canonical_request; - } + /** + * Headers used in the get/cancel/funds requests + * + * @param string $service_operation Service operation code to be used in header request + * and main request call + * @param string $payload Payload from get/cancle Code or funds call + * @return string Full POST service request code + */ + public function getCanonicalRequest(string $service_operation, string $payload): string + { + $HOST_HEADER = self::HOST_HEADER; + $X_AMZ_DATE_HEADER = self::X_AMZ_DATE_HEADER; + $X_AMZ_TARGET_HEADER = self::X_AMZ_TARGET_HEADER; + $ACCEPT_HEADER = self::ACCEPT_HEADER; + $payload_hash = $this->buildHash($payload); + $canonical_headers = $this->buildCanonicalHeaders($service_operation); + $canonical_request = "POST\n" + . "/$service_operation\n\n" + . "$canonical_headers\n\n" + . "$ACCEPT_HEADER;$HOST_HEADER;$X_AMZ_DATE_HEADER;$X_AMZ_TARGET_HEADER\n" + . "$payload_hash"; + return $canonical_request; + } - /** - * Build sha256 hash from given data - * - * @param string $data Data to be hashed with sha256 - * @return string sha256 hash - */ - public function buildHash(string $data): string - { - return hash('sha256', $data); - } + /** + * Build sha256 hash from given data + * + * @param string $data Data to be hashed with sha256 + * @return string sha256 hash + */ + public function buildHash(string $data): string + { + return hash('sha256', $data); + } - /** - * Create a sha256 based Hash-Based Message Authentication Code - * with the given key and data - * - * @param string $data Data to be hashed with key below - * @param string $key Key to be used for creating the hash - * @param bool $raw Returning data as ascii string or hexibits - * @return string Hash-Based Message Authentication Code - */ - public function hmac(string $data, string $key, bool $raw = true): string - { - return hash_hmac('sha256', $data, $key, $raw); - } + /** + * Create a sha256 based Hash-Based Message Authentication Code + * with the given key and data + * + * @param string $data Data to be hashed with key below + * @param string $key Key to be used for creating the hash + * @param bool $raw Returning data as ascii string or hexibits + * @return string Hash-Based Message Authentication Code + */ + public function hmac(string $data, string $key, bool $raw = true): string + { + return hash_hmac('sha256', $data, $key, $raw); + } - /** - * Build timestamp in the format used by AWS services - * eg 20211009\T102030\Z - * - * @return string date string based on current time. Ymd\THis\Z - */ - public function getTimestamp() - { - return gmdate('Ymd\THis\Z'); - } + /** + * Build timestamp in the format used by AWS services + * eg 20211009\T102030\Z + * + * @return string date string based on current time. Ymd\THis\Z + */ + public function getTimestamp() + { + return gmdate('Ymd\THis\Z'); + } - /** - * Get only the date string from the getTimestamp - * eg 20211009 - * - * @return string Date string YYYYmmdd extracted from getTimestamp() - */ - public function getDateString() - { - return substr($this->getTimestamp(), 0, 8); - } + /** + * Get only the date string from the getTimestamp + * eg 20211009 + * + * @return string Date string YYYYmmdd extracted from getTimestamp() + */ + public function getDateString() + { + return substr($this->getTimestamp(), 0, 8); + } - /** - * Fixed content type for submission, is json - * - * @return string 'application/json' string - */ - public function getContentType(): string - { - return 'application/json'; - } + /** + * Fixed content type for submission, is json + * + * @return string 'application/json' string + */ + public function getContentType(): string + { + return 'application/json'; + } } // __END__ diff --git a/src/AmazonIncentives.php b/src/AmazonIncentives.php index 848956b..deb79ad 100644 --- a/src/AmazonIncentives.php +++ b/src/AmazonIncentives.php @@ -14,158 +14,158 @@ use gullevek\AmazonIncentives\Debug\AmazonDebug; final class AmazonIncentives { - /** - * @var Config - */ - private $config; + /** + * @var Config + */ + private $config; - /** - * AmazonGiftCode constructor. - * - * @param string|null $key Account key - * @param string|null $secret Secret key - * @param string|null $partner Partner ID - * @param string|null $endpoint Endpoint URL including https:// - * @param string|null $currency Currency type. Eg USD, JPY, etc - * @param bool|null $debug Debug flag - */ - public function __construct( - ?string $key = null, - ?string $secret = null, - ?string $partner = null, - ?string $endpoint = null, - ?string $currency = null, - ?bool $debug = null - ) { - // load AWS settings - // fail here if settings missing - $this->config = new Config($key, $secret, $partner, $endpoint, $currency, $debug); - // init debug - AmazonDebug::setDebug($this->config->getDebug()); - } + /** + * AmazonGiftCode constructor. + * + * @param string|null $key Account key + * @param string|null $secret Secret key + * @param string|null $partner Partner ID + * @param string|null $endpoint Endpoint URL including https:// + * @param string|null $currency Currency type. Eg USD, JPY, etc + * @param bool|null $debug Debug flag + */ + public function __construct( + ?string $key = null, + ?string $secret = null, + ?string $partner = null, + ?string $endpoint = null, + ?string $currency = null, + ?bool $debug = null + ) { + // load AWS settings + // fail here if settings missing + $this->config = new Config($key, $secret, $partner, $endpoint, $currency, $debug); + // init debug + AmazonDebug::setDebug($this->config->getDebug()); + } - // ********************************************************************* - // PRIVATE HELPER METHODS - // ********************************************************************* + // ********************************************************************* + // PRIVATE HELPER METHODS + // ********************************************************************* - // ********************************************************************* - // PUBLIC METHODS - // ********************************************************************* + // ********************************************************************* + // PUBLIC METHODS + // ********************************************************************* - /** - * Buy a gift card - * - * @param float $value Amount to purchase a gift card - * in currency value - * @param string|null $creation_request_id Override automatically created request id - * If not set will create a new one, or - * return data for created one - * @return Response\CreateResponse Returns new created response object or - * previous created if creation_request_id was used - * - * @throws AmazonErrors - */ - public function buyGiftCard(float $value, ?string $creation_request_id = null): Response\CreateResponse - { - return ($this->newAWS())->getCode($value, $creation_request_id); - } + /** + * Buy a gift card + * + * @param float $value Amount to purchase a gift card + * in currency value + * @param string|null $creation_request_id Override automatically created request id + * If not set will create a new one, or + * return data for created one + * @return Response\CreateResponse Returns new created response object or + * previous created if creation_request_id was used + * + * @throws AmazonErrors + */ + public function buyGiftCard(float $value, ?string $creation_request_id = null): Response\CreateResponse + { + return ($this->newAWS())->getCode($value, $creation_request_id); + } - /** - * Cancel a previous created gift card, if within the time frame - * - * @param string $creation_request_id Previous created request id from buyGiftCard - * @param string $gift_card_id Previous gift card id from buyGiftCard (gcId) - * @return Response\CancelResponse Returns the cancled request object - * - * @throws AmazonErrors - */ - public function cancelGiftCard(string $creation_request_id, string $gift_card_id): Response\CancelResponse - { - return ($this->newAWS())->cancelCode($creation_request_id, $gift_card_id); - } + /** + * Cancel a previous created gift card, if within the time frame + * + * @param string $creation_request_id Previous created request id from buyGiftCard + * @param string $gift_card_id Previous gift card id from buyGiftCard (gcId) + * @return Response\CancelResponse Returns the cancled request object + * + * @throws AmazonErrors + */ + public function cancelGiftCard(string $creation_request_id, string $gift_card_id): Response\CancelResponse + { + return ($this->newAWS())->cancelCode($creation_request_id, $gift_card_id); + } - /** - * Gets the current funds in this account - * - * @return Response\CreateBalanceResponse Returns the account funds object - * - * @throws AmazonErrors - */ - public function getAvailableFunds(): Response\CreateBalanceResponse - { - return ($this->newAWS())->getBalance(); - } + /** + * Gets the current funds in this account + * + * @return Response\CreateBalanceResponse Returns the account funds object + * + * @throws AmazonErrors + */ + public function getAvailableFunds(): Response\CreateBalanceResponse + { + return ($this->newAWS())->getBalance(); + } - /** - * AmazonIncentives creates own client and returns it as static object - * - * @param string|null $key Account key - * @param string|null $secret Secret key - * @param string|null $partner Partner ID - * @param string|null $endpoint Endpoint URL including https:// - * @param string|null $currency Currency type. Eg USD, JPY, etc - * @param bool|null $debug Debug flag - * @return AmazonIncentives self class - */ - public static function make( - ?string $key = null, - ?string $secret = null, - ?string $partner = null, - ?string $endpoint = null, - ?string $currency = null, - ?bool $debug = null - ): AmazonIncentives { - return new static($key, $secret, $partner, $endpoint, $currency, $debug); - } + /** + * AmazonIncentives creates own client and returns it as static object + * + * @param string|null $key Account key + * @param string|null $secret Secret key + * @param string|null $partner Partner ID + * @param string|null $endpoint Endpoint URL including https:// + * @param string|null $currency Currency type. Eg USD, JPY, etc + * @param bool|null $debug Debug flag + * @return AmazonIncentives self class + */ + public static function make( + ?string $key = null, + ?string $secret = null, + ?string $partner = null, + ?string $endpoint = null, + ?string $currency = null, + ?bool $debug = null + ): AmazonIncentives { + return new static($key, $secret, $partner, $endpoint, $currency, $debug); + } - /** - * wrapper to create new AWS class. - * used in all buy/cancel/get calss - * - * @return AWS Main AWS worker class - */ - public function newAWS(): AWS - { - return new AWS($this->config); - } + /** + * wrapper to create new AWS class. + * used in all buy/cancel/get calss + * + * @return AWS Main AWS worker class + */ + public function newAWS(): AWS + { + return new AWS($this->config); + } - /** - * Decodes the Exception message body - * Returns an array with code (Amazon error codes), type (Amazon error info) - * message (Amazon returned error message string) - * - * @param string $message Exception message json string - * @return array Decoded with code, type, message fields - * - * @deprecated use \gullevek\AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage() - */ - public static function decodeExceptionMessage(string $message): array - { - return AmazonErrors::decodeExceptionMessage($message); - } + /** + * Decodes the Exception message body + * Returns an array with code (Amazon error codes), type (Amazon error info) + * message (Amazon returned error message string) + * + * @param string $message Exception message json string + * @return array Decoded with code, type, message fields + * + * @deprecated use \gullevek\AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage() + */ + public static function decodeExceptionMessage(string $message): array + { + return AmazonErrors::decodeExceptionMessage($message); + } - // ********************************************************************* - // PUBLIC TEST METHODS - // ********************************************************************* + // ********************************************************************* + // PUBLIC TEST METHODS + // ********************************************************************* - /** - * Prints out ENV, CONFIG and KEY data - * This is for debug only, this will print out secrets. - * Use with care - * - * @return array - */ - public function checkMe(): array - { - $data = []; + /** + * Prints out ENV, CONFIG and KEY data + * This is for debug only, this will print out secrets. + * Use with care + * + * @return array + */ + public function checkMe(): array + { + $data = []; - $data['ENV'] = $_ENV; - $data['CONFIG'] = $this->config; - $data['KEY'] = $this->config->getAccessKey(); + $data['ENV'] = $_ENV; + $data['CONFIG'] = $this->config; + $data['KEY'] = $this->config->getAccessKey(); - return $data; - } + return $data; + } } // __END__ diff --git a/src/Client/Client.php b/src/Client/Client.php index 1fa02b1..faaa8ef 100644 --- a/src/Client/Client.php +++ b/src/Client/Client.php @@ -10,118 +10,118 @@ use gullevek\AmazonIncentives\Handle\Json; class Client implements ClientInterface { - /** @var int instead of JsonResponse::HTTP_OK */ - private const HTTP_OK = 200; + /** @var int instead of JsonResponse::HTTP_OK */ + private const HTTP_OK = 200; - /** - * Makes an request to the target url via curl - * Returns result as string (json) - * - * @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 Result as json 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); - curl_setopt($handle, CURLOPT_POSTFIELDS, $params); - curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); - $result = curl_exec($handle); + /** + * Makes an request to the target url via curl + * Returns result as string (json) + * + * @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 Result as json 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); + curl_setopt($handle, CURLOPT_POSTFIELDS, $params); + curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); + $result = curl_exec($handle); - if ($result === false) { - $err = curl_errno($handle); - $message = curl_error($handle); - $this->handleCurlError($url, $err, $message); - } + if ($result === false) { + $err = curl_errno($handle); + $message = curl_error($handle); + $this->handleCurlError($url, $err, $message); + } - if (curl_getinfo($handle, CURLINFO_HTTP_CODE) !== self::HTTP_OK) { - $err = curl_errno($handle); - AmazonDebug::writeLog(['CURL_REQUEST_RESULT' => $result]); - // extract all the error codes from Amazon - // note we do not care about result errors here, if json decode fails, just set to empty - try { - $result_ar = Json::jsonDecode((string)$result); - } catch (AmazonErrors $e) { - $result_ar = []; - } - // if message is 'Rate exceeded', set different error - if (($result_ar['message'] ?? '') == 'Rate exceeded') { - $error_status = 'RESEND'; - $error_code = 'T001'; - $error_type = 'RateExceeded'; - $message = $result_ar['message'] ?? 'Rate exceeded'; - } else { - // for all other error messages - $error_status = $result_ar['agcodResponse']['status'] ?? 'FAILURE'; - $error_code = $result_ar['errorCode'] ?? 'E999'; - $error_type = $result_ar['errorType'] ?? 'OtherUnknownError'; - $message = $result_ar['message'] ?? 'Unknown error occured'; - } - // throw Error here with all codes - throw AmazonErrors::getError( - $error_status, - $error_code, - $error_type, - $message, - $err - ); - } - return (string)$result; - } + if (curl_getinfo($handle, CURLINFO_HTTP_CODE) !== self::HTTP_OK) { + $err = curl_errno($handle); + AmazonDebug::writeLog(['CURL_REQUEST_RESULT' => $result]); + // extract all the error codes from Amazon + // note we do not care about result errors here, if json decode fails, just set to empty + try { + $result_ar = Json::jsonDecode((string)$result); + } catch (AmazonErrors $e) { + $result_ar = []; + } + // if message is 'Rate exceeded', set different error + if (($result_ar['message'] ?? '') == 'Rate exceeded') { + $error_status = 'RESEND'; + $error_code = 'T001'; + $error_type = 'RateExceeded'; + $message = $result_ar['message'] ?? 'Rate exceeded'; + } else { + // for all other error messages + $error_status = $result_ar['agcodResponse']['status'] ?? 'FAILURE'; + $error_code = $result_ar['errorCode'] ?? 'E999'; + $error_type = $result_ar['errorType'] ?? 'OtherUnknownError'; + $message = $result_ar['message'] ?? 'Unknown error occured'; + } + // throw Error here with all codes + throw AmazonErrors::getError( + $error_status, + $error_code, + $error_type, + $message, + $err + ); + } + return (string)$result; + } - /** - * handles any CURL errors and throws an error with the correct - * error message - * - * @param string $url The url that was originaly used - * @param int $errno Error number from curl handler - * @param string $message The error message string from curl - * @return void - */ - private function handleCurlError(string $url, int $errno, string $message): void - { - switch ($errno) { - case CURLE_COULDNT_CONNECT: - case CURLE_COULDNT_RESOLVE_HOST: - case CURLE_OPERATION_TIMEOUTED: - $message = 'Could not connect to AWS (' . $url . '). Please check your ' - . 'internet connection and try again. [' . $message . ']'; - break; - case CURLE_SSL_PEER_CERTIFICATE: - $message = 'Could not verify AWS SSL certificate. Please make sure ' - . 'that your network is not intercepting certificates. ' - . '(Try going to ' . $url . 'in your browser.) ' - . '[' . $message . ']'; - break; - case 0: - default: - $message = 'Unexpected error communicating with AWS: ' . $message; - } + /** + * handles any CURL errors and throws an error with the correct + * error message + * + * @param string $url The url that was originaly used + * @param int $errno Error number from curl handler + * @param string $message The error message string from curl + * @return void + */ + private function handleCurlError(string $url, int $errno, string $message): void + { + switch ($errno) { + case CURLE_COULDNT_CONNECT: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_OPERATION_TIMEOUTED: + $message = 'Could not connect to AWS (' . $url . '). Please check your ' + . 'internet connection and try again. [' . $message . ']'; + break; + case CURLE_SSL_PEER_CERTIFICATE: + $message = 'Could not verify AWS SSL certificate. Please make sure ' + . 'that your network is not intercepting certificates. ' + . '(Try going to ' . $url . 'in your browser.) ' + . '[' . $message . ']'; + break; + case 0: + default: + $message = 'Unexpected error communicating with AWS: ' . $message; + } - // throw an error like in the normal reqeust, but set to CURL error - throw AmazonErrors::getError( - 'FAILURE', - 'C002', - 'CurlError', - $message, - $errno - ); - } + // throw an error like in the normal reqeust, but set to CURL error + throw AmazonErrors::getError( + 'FAILURE', + 'C002', + 'CurlError', + $message, + $errno + ); + } } // __END__ diff --git a/src/Client/ClientInterface.php b/src/Client/ClientInterface.php index c0c1425..e09010b 100644 --- a/src/Client/ClientInterface.php +++ b/src/Client/ClientInterface.php @@ -6,15 +6,15 @@ 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 - * - * @return String - */ - public function request(string $url, array $headers, $params): string; + /** + * @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 + */ + public function request(string $url, array $headers, $params): string; } // __END__ diff --git a/src/Config/Config.php b/src/Config/Config.php index 161293c..adbba01 100644 --- a/src/Config/Config.php +++ b/src/Config/Config.php @@ -6,211 +6,211 @@ namespace gullevek\AmazonIncentives\Config; class Config implements ConfigInterface { - /** @var string Endpoint URL without https:// */ - private $endpoint = ''; - /** @var string Access Key */ - private $access_key = ''; - /** @var string Secret Key */ - private $secret_key = ''; - /** @var string Partner ID */ - private $partner_id = ''; - /** @var string Currency type as USD, JPY, etc */ - private $currency = ''; - /** @var bool Debug flag on or off */ - private $debug = false; + /** @var string Endpoint URL without https:// */ + private $endpoint = ''; + /** @var string Access Key */ + private $access_key = ''; + /** @var string Secret Key */ + private $secret_key = ''; + /** @var string Partner ID */ + private $partner_id = ''; + /** @var string Currency type as USD, JPY, etc */ + private $currency = ''; + /** @var bool Debug flag on or off */ + private $debug = false; - /** - * @param string|null $key Access key - * @param string|null $secret Secret Key - * @param string|null $partner Partner ID - * @param string|null $endpoint Endpoing URL including https:// - * @param string|null $currency Currency to use, see valid list on AWS documentation. - * valid names are like USD, JPY, etc - * @param bool|null $debug Debug flag - */ - public function __construct( - ?string $key, - ?string $secret, - ?string $partner, - ?string $endpoint, - ?string $currency, - ?bool $debug - ) { - /** - * @psalm-suppress InvalidScalarArgument - * @phpstan-ignore-next-line - */ - $this->setAccessKey(($key) ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); - /** - * @psalm-suppress InvalidScalarArgument - * @phpstan-ignore-next-line - */ - $this->setSecret(($secret) ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); - /** - * @psalm-suppress InvalidScalarArgument - * @phpstan-ignore-next-line - */ - $this->setPartner(($partner) ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); - /** - * @psalm-suppress InvalidScalarArgument - * @phpstan-ignore-next-line - */ - $this->setEndpoint(($endpoint) ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); - /** - * @psalm-suppress InvalidScalarArgument - * @phpstan-ignore-next-line - */ - $this->setCurrency(($currency) ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); - /** - * @psalm-suppress InvalidScalarArgument - * @phpstan-ignore-next-line - */ - $this->setDebug(($debug) ?: $this->parseEnv('AWS_DEBUG')); - } + /** + * @param string|null $key Access key + * @param string|null $secret Secret Key + * @param string|null $partner Partner ID + * @param string|null $endpoint Endpoing URL including https:// + * @param string|null $currency Currency to use, see valid list on AWS documentation. + * valid names are like USD, JPY, etc + * @param bool|null $debug Debug flag + */ + public function __construct( + ?string $key, + ?string $secret, + ?string $partner, + ?string $endpoint, + ?string $currency, + ?bool $debug + ) { + /** + * @psalm-suppress InvalidScalarArgument + * @phpstan-ignore-next-line + */ + $this->setAccessKey(($key) ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); + /** + * @psalm-suppress InvalidScalarArgument + * @phpstan-ignore-next-line + */ + $this->setSecret(($secret) ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); + /** + * @psalm-suppress InvalidScalarArgument + * @phpstan-ignore-next-line + */ + $this->setPartner(($partner) ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); + /** + * @psalm-suppress InvalidScalarArgument + * @phpstan-ignore-next-line + */ + $this->setEndpoint(($endpoint) ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); + /** + * @psalm-suppress InvalidScalarArgument + * @phpstan-ignore-next-line + */ + $this->setCurrency(($currency) ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); + /** + * @psalm-suppress InvalidScalarArgument + * @phpstan-ignore-next-line + */ + $this->setDebug(($debug) ?: $this->parseEnv('AWS_DEBUG')); + } - /** - * string key to search, returns entry from _ENV - * if not matchin key, returns empty - * - * @param string $key To search in _ENV array - * @return string|bool Returns either string or true/false (DEBUG flag) - */ - private function parseEnv(string $key) - { - $return = ''; - switch ($key) { - case 'AWS_DEBUG': - $return = !empty($_ENV['AWS_DEBUG']) ? true : false; - break; - case 'AWS_GIFT_CARD_KEY': - case 'AWS_GIFT_CARD_SECRET': - case 'AWS_GIFT_CARD_PARTNER_ID': - case 'AWS_GIFT_CARD_ENDPOINT': - case 'AWS_GIFT_CARD_CURRENCY': - $return = !empty($_ENV[$key]) && is_string($_ENV[$key]) ? - $_ENV[$key] : ''; - break; - default: - break; - } - return $return; - } + /** + * string key to search, returns entry from _ENV + * if not matchin key, returns empty + * + * @param string $key To search in _ENV array + * @return string|bool Returns either string or true/false (DEBUG flag) + */ + private function parseEnv(string $key) + { + $return = ''; + switch ($key) { + case 'AWS_DEBUG': + $return = !empty($_ENV['AWS_DEBUG']) ? true : false; + break; + case 'AWS_GIFT_CARD_KEY': + case 'AWS_GIFT_CARD_SECRET': + case 'AWS_GIFT_CARD_PARTNER_ID': + case 'AWS_GIFT_CARD_ENDPOINT': + case 'AWS_GIFT_CARD_CURRENCY': + $return = !empty($_ENV[$key]) && is_string($_ENV[$key]) ? + $_ENV[$key] : ''; + break; + default: + break; + } + return $return; + } - /** - * @return string Returns current set endpoint, without https:// - */ - public function getEndpoint(): string - { - return $this->endpoint; - } + /** + * @return string Returns current set endpoint, without https:// + */ + public function getEndpoint(): string + { + return $this->endpoint; + } - /** - * @param string $endpoint Full endpoint url with https:// - * @return ConfigInterface Class interface (self) - */ - public function setEndpoint(string $endpoint): ConfigInterface - { - // TODO: check valid endpoint + set region - $this->endpoint = (parse_url($endpoint, PHP_URL_HOST)) ?: ''; + /** + * @param string $endpoint Full endpoint url with https:// + * @return ConfigInterface Class interface (self) + */ + public function setEndpoint(string $endpoint): ConfigInterface + { + // TODO: check valid endpoint + set region + $this->endpoint = (parse_url($endpoint, PHP_URL_HOST)) ?: ''; - return $this; - } + return $this; + } - /** - * @return string Current access key - */ - public function getAccessKey(): string - { - return $this->access_key; - } + /** + * @return string Current access key + */ + public function getAccessKey(): string + { + return $this->access_key; + } - /** - * @param string $key Access Key to set - * @return ConfigInterface Class interface (self) - */ - public function setAccessKey(string $key): ConfigInterface - { - $this->access_key = $key; + /** + * @param string $key Access Key to set + * @return ConfigInterface Class interface (self) + */ + public function setAccessKey(string $key): ConfigInterface + { + $this->access_key = $key; - return $this; - } + return $this; + } - /** - * @return string Current secret key - */ - public function getSecret(): string - { - return $this->secret_key; - } + /** + * @return string Current secret key + */ + public function getSecret(): string + { + return $this->secret_key; + } - /** - * @param string $secret Secret key to set - * @return ConfigInterface Class interface (self) - */ - public function setSecret(string $secret): ConfigInterface - { - $this->secret_key = $secret; + /** + * @param string $secret Secret key to set + * @return ConfigInterface Class interface (self) + */ + public function setSecret(string $secret): ConfigInterface + { + $this->secret_key = $secret; - return $this; - } + return $this; + } - /** - * @return string Current set currency - */ - public function getCurrency(): string - { - return $this->currency; - } + /** + * @return string Current set currency + */ + public function getCurrency(): string + { + return $this->currency; + } - /** - * @param string $currency Currency to set (eg USD, JPY, etc) - * @return ConfigInterface Class interface (self) - */ - public function setCurrency(string $currency): ConfigInterface - { - // TODO: check currency valid + currenc valid for region - $this->currency = $currency; + /** + * @param string $currency Currency to set (eg USD, JPY, etc) + * @return ConfigInterface Class interface (self) + */ + public function setCurrency(string $currency): ConfigInterface + { + // TODO: check currency valid + currenc valid for region + $this->currency = $currency; - return $this; - } + return $this; + } - /** - * @return string Current set partner id - */ - public function getPartner(): string - { - return $this->partner_id; - } + /** + * @return string Current set partner id + */ + public function getPartner(): string + { + return $this->partner_id; + } - /** - * @param string $partner Partner id to set - * @return ConfigInterface Class interface (self) - */ - public function setPartner(string $partner): ConfigInterface - { - $this->partner_id = $partner; + /** + * @param string $partner Partner id to set + * @return ConfigInterface Class interface (self) + */ + public function setPartner(string $partner): ConfigInterface + { + $this->partner_id = $partner; - return $this; - } + return $this; + } - /** - * @return bool Current set debug flag as bool - */ - public function getDebug(): bool - { - return $this->debug; - } + /** + * @return bool Current set debug flag as bool + */ + public function getDebug(): bool + { + return $this->debug; + } - /** - * @param bool $debug Set debug flag as bool - * @return ConfigInterface Class interface (self) - */ - public function setDebug(bool $debug): ConfigInterface - { - $this->debug = $debug; + /** + * @param bool $debug Set debug flag as bool + * @return ConfigInterface Class interface (self) + */ + public function setDebug(bool $debug): ConfigInterface + { + $this->debug = $debug; - return $this; - } + return $this; + } } // __END__ diff --git a/src/Config/ConfigInterface.php b/src/Config/ConfigInterface.php index 16707a5..f52e4de 100644 --- a/src/Config/ConfigInterface.php +++ b/src/Config/ConfigInterface.php @@ -6,71 +6,71 @@ namespace gullevek\AmazonIncentives\Config; interface ConfigInterface { - /** - * @return string Returns current set endpoint, without https:// - */ - public function getEndpoint(): string; + /** + * @return string Returns current set endpoint, without https:// + */ + public function getEndpoint(): string; - /** - * @param string $endpoint Full endpoint url with https:// - * @return ConfigInterface Class interface (self) - */ - public function setEndpoint(string $endpoint): ConfigInterface; + /** + * @param string $endpoint Full endpoint url with https:// + * @return ConfigInterface Class interface (self) + */ + public function setEndpoint(string $endpoint): ConfigInterface; - /** - * @return string Current access key - */ - public function getAccessKey(): string; + /** + * @return string Current access key + */ + public function getAccessKey(): string; - /** - * @param string $key Access Key to set - * @return ConfigInterface Class interface (self) - */ - public function setAccessKey(string $key): ConfigInterface; + /** + * @param string $key Access Key to set + * @return ConfigInterface Class interface (self) + */ + public function setAccessKey(string $key): ConfigInterface; - /** - * @return string Current secret key - */ - public function getSecret(): string; + /** + * @return string Current secret key + */ + public function getSecret(): string; - /** - * @param string $secret Secret key to set - * @return ConfigInterface Class interface (self) - */ - public function setSecret(string $secret): ConfigInterface; + /** + * @param string $secret Secret key to set + * @return ConfigInterface Class interface (self) + */ + public function setSecret(string $secret): ConfigInterface; - /** - * @return string Current set currency - */ - public function getCurrency(): string; + /** + * @return string Current set currency + */ + public function getCurrency(): string; - /** - * @param string $currency Currency to set (eg USD, JPY, etc) - * @return ConfigInterface Class interface (self) - */ - public function setCurrency(string $currency): ConfigInterface; + /** + * @param string $currency Currency to set (eg USD, JPY, etc) + * @return ConfigInterface Class interface (self) + */ + public function setCurrency(string $currency): ConfigInterface; - /** - * @return string Current set partner id - */ - public function getPartner(): string; + /** + * @return string Current set partner id + */ + public function getPartner(): string; - /** - * @param string $partner Partner id to set - * @return ConfigInterface Class interface (self) - */ - public function setPartner(string $partner): ConfigInterface; + /** + * @param string $partner Partner id to set + * @return ConfigInterface Class interface (self) + */ + public function setPartner(string $partner): ConfigInterface; - /** - * @return bool Current set debug flag as bool - */ - public function getDebug(): bool; + /** + * @return bool Current set debug flag as bool + */ + public function getDebug(): bool; - /** - * @param bool $debug Set debug flag as bool - * @return ConfigInterface Class interface (self) - */ - public function setDebug(bool $debug): ConfigInterface; + /** + * @param bool $debug Set debug flag as bool + * @return ConfigInterface Class interface (self) + */ + public function setDebug(bool $debug): ConfigInterface; } // __END__ diff --git a/src/Debug/AmazonDebug.php b/src/Debug/AmazonDebug.php index f6c7c7c..f1ff5be 100644 --- a/src/Debug/AmazonDebug.php +++ b/src/Debug/AmazonDebug.php @@ -9,103 +9,103 @@ namespace gullevek\AmazonIncentives\Debug; class AmazonDebug { - /** @var array>> Log data array log id -> array of log entries */ - private static $log = []; - /** @var bool debug flag */ - private static $debug = false; - /** @var string|null Last set internal log array id */ - private static $id = null; + /** @var array>> Log data array log id -> array of log entries */ + private static $log = []; + /** @var bool debug flag */ + private static $debug = false; + /** @var string|null Last set internal log array id */ + private static $id = null; - /** - * set the ID for current run - * if debug is off, nothing will be set and id is null - * This is run on setFlag, if debug is true - * - * @param string|null $id If not set, will default to uniqid() call - * @return void - */ - private static function setId(?string $id = null): void - { - if (self::$debug === false) { - return; - } - if ($id === null) { - $id = uniqid(); - } - self::$id = $id; - } + /** + * set the ID for current run + * if debug is off, nothing will be set and id is null + * This is run on setFlag, if debug is true + * + * @param string|null $id If not set, will default to uniqid() call + * @return void + */ + private static function setId(?string $id = null): void + { + if (self::$debug === false) { + return; + } + if ($id === null) { + $id = uniqid(); + } + self::$id = $id; + } - /** - * set the debug flag. - * This is automatically run in gullevek\AmazonIncentives\AmazonIncentives::__construct - * No need to run manuall - * - * @param boolean $debug Can only be True or False - * @param string|null $id If not set, will default to uniqid() call - * @return void - */ - public static function setDebug(bool $debug, ?string $id = null): void - { - self::$debug = $debug; - if (self::$debug === false) { - return; - } - self::setId($id); - } + /** + * set the debug flag. + * This is automatically run in gullevek\AmazonIncentives\AmazonIncentives::__construct + * No need to run manuall + * + * @param boolean $debug Can only be True or False + * @param string|null $id If not set, will default to uniqid() call + * @return void + */ + public static function setDebug(bool $debug, ?string $id = null): void + { + self::$debug = $debug; + if (self::$debug === false) { + return; + } + self::setId($id); + } - /** - * returns current debug flag status - * - * @return boolean True if debug is on, False if debug is off - */ - public static function getDebug(): bool - { - return self::$debug; - } + /** + * returns current debug flag status + * + * @return boolean True if debug is on, False if debug is off + */ + public static function getDebug(): bool + { + return self::$debug; + } - /** - * get the current set ID, can return null if debug is off - * - * @return string|null Current set ID for this log run - */ - public static function getId(): ?string - { - return self::$id; - } + /** + * get the current set ID, can return null if debug is off + * + * @return string|null Current set ID for this log run + */ + public static function getId(): ?string + { + return self::$id; + } - /** - * write a log entry - * Data is as array key -> value - * 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 - * @return void - */ - public static function writeLog(array $data): void - { - if (self::$debug === false) { - return; - } - self::$log[self::getId() ?? ''][] = $data; - } + /** + * write a log entry + * Data is as array key -> value + * 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 + * @return void + */ + public static function writeLog(array $data): void + { + if (self::$debug === false) { + return; + } + self::$log[self::getId() ?? ''][] = $data; + } - /** - * get all logs written since first class run - * or get all log entries for given ID - * - * @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 - */ - public static function getLog(?string $id = null): array - { - if ($id === null) { - return self::$log; - } else { - return self::$log[$id] ?? []; - } - } + /** + * get all logs written since first class run + * or get all log entries for given ID + * + * @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 + */ + public static function getLog(?string $id = null): array + { + if ($id === null) { + return self::$log; + } else { + return self::$log[$id] ?? []; + } + } } // __END__ diff --git a/src/Exceptions/AmazonErrors.php b/src/Exceptions/AmazonErrors.php index aa4baec..b151470 100644 --- a/src/Exceptions/AmazonErrors.php +++ b/src/Exceptions/AmazonErrors.php @@ -9,63 +9,63 @@ use gullevek\AmazonIncentives\Debug\AmazonDebug; final class AmazonErrors extends RuntimeException { - /** - * Returns an Runtime exception including a json encoded string with all - * parameters including last log id and log - * - * @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 Message string to ad - * @param int $_error_code Error code to set - * @return AmazonErrors Exception Class - */ - public static function getError( - string $error_status, - string $error_code, - string $error_type, - string $message, - int $_error_code - ): self { - // NOTE: if xdebug.show_exception_trace is set to 1 this will print ERRORS - return new static( - (json_encode([ - 'status' => $error_status, - 'code' => $error_code, - 'type' => $error_type, - 'message' => $message, - // attach log data if exists - 'log_id' => AmazonDebug::getId(), - 'log' => AmazonDebug::getLog(), - ])) ?: 'AmazonErrors: json encode problem: ' . $message, - $_error_code - ); - } + /** + * Returns an Runtime exception including a json encoded string with all + * parameters including last log id and log + * + * @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 Message string to ad + * @param int $_error_code Error code to set + * @return AmazonErrors Exception Class + */ + public static function getError( + string $error_status, + string $error_code, + string $error_type, + string $message, + int $_error_code + ): self { + // NOTE: if xdebug.show_exception_trace is set to 1 this will print ERRORS + return new static( + (json_encode([ + 'status' => $error_status, + 'code' => $error_code, + 'type' => $error_type, + 'message' => $message, + // attach log data if exists + 'log_id' => AmazonDebug::getId(), + 'log' => AmazonDebug::getLog(), + ])) ?: 'AmazonErrors: json encode problem: ' . $message, + $_error_code + ); + } - /** - * Decodes the Exception message body - * Returns an array with code (Amazon error codes), type (Amazon error info) - * message (Amazon returned error message string) - * - * @param string $message Exception message json string - * @return array Decoded with code, type, message fields - */ - public static function decodeExceptionMessage(string $message): array - { - $message_ar = json_decode($message, true); - // if we have an error, build empty block and only fill message - if (json_last_error() || $message_ar === null || !is_array($message_ar)) { - $message_ar = [ - 'status' => '', - 'code' => '', - 'type' => '', - 'message' => $message, - 'log_id' => '', - 'log' => [] - ]; - } - return $message_ar; - } + /** + * Decodes the Exception message body + * Returns an array with code (Amazon error codes), type (Amazon error info) + * message (Amazon returned error message string) + * + * @param string $message Exception message json string + * @return array Decoded with code, type, message fields + */ + public static function decodeExceptionMessage(string $message): array + { + $message_ar = json_decode($message, true); + // if we have an error, build empty block and only fill message + if (json_last_error() || $message_ar === null || !is_array($message_ar)) { + $message_ar = [ + 'status' => '', + 'code' => '', + 'type' => '', + 'message' => $message, + 'log_id' => '', + 'log' => [] + ]; + } + return $message_ar; + } } // __END__ diff --git a/src/Handle/Json.php b/src/Handle/Json.php index c8eea53..223d067 100644 --- a/src/Handle/Json.php +++ b/src/Handle/Json.php @@ -12,31 +12,31 @@ use gullevek\AmazonIncentives\Exceptions\AmazonErrors; class Json { - /** - * decode json string - * - * @param string $json - * @return array - * @throws AmazonErrors - */ - public static function jsonDecode(string $json): array - { - $result = json_decode($json, true); - if ( - ($json_last_error = json_last_error()) || - $result === null || - !is_array($result) - ) { - throw AmazonErrors::getError( - 'FAILURE', - 'J-' . $json_last_error, - 'jsonDecoreError', - 'Failed to decode json data', - 0 - ); - } - return $result; - } + /** + * decode json string + * + * @param string $json + * @return array + * @throws AmazonErrors + */ + public static function jsonDecode(string $json): array + { + $result = json_decode($json, true); + if ( + ($json_last_error = json_last_error()) || + $result === null || + !is_array($result) + ) { + throw AmazonErrors::getError( + 'FAILURE', + 'J-' . $json_last_error, + 'jsonDecoreError', + 'Failed to decode json data', + 0 + ); + } + return $result; + } } // __END__ diff --git a/src/Response/CancelResponse.php b/src/Response/CancelResponse.php index 49b3309..39d040e 100644 --- a/src/Response/CancelResponse.php +++ b/src/Response/CancelResponse.php @@ -8,98 +8,98 @@ use gullevek\AmazonIncentives\Debug\AmazonDebug; class CancelResponse { - /** @var string Amazon Gift Card gcId (gift card id). */ - protected $id = ''; - /** @var string Amazon Gift Card creationRequestId (creation request id) */ - protected $creation_request_id = ''; - /** @var string Amazon Gift Card status */ - protected $status = ''; - /** @var array Amazon Gift Card Raw JSON */ - protected $raw_json = []; + /** @var string Amazon Gift Card gcId (gift card id). */ + protected $id = ''; + /** @var string Amazon Gift Card creationRequestId (creation request id) */ + protected $creation_request_id = ''; + /** @var string Amazon Gift Card status */ + protected $status = ''; + /** @var array Amazon Gift Card Raw JSON */ + protected $raw_json = []; - /** - * Response constructor for canceling gitf cards - * - * @param array $json_response JSON response from web request to AWS - */ - public function __construct(array $json_response) - { - $this->raw_json = $json_response; - $this->parseJsonResponse($json_response); - } + /** + * Response constructor for canceling gitf cards + * + * @param array $json_response JSON response from web request to AWS + */ + public function __construct(array $json_response) + { + $this->raw_json = $json_response; + $this->parseJsonResponse($json_response); + } - /** - * Get log entry with current set log id - * - * @return array Log array - */ - public function getLog(): array - { - return AmazonDebug::getLog(AmazonDebug::getId()); - } + /** + * Get log entry with current set log id + * + * @return array Log array + */ + public function getLog(): array + { + return AmazonDebug::getLog(AmazonDebug::getId()); + } - /** - * The gift card id as created by the previous get code call - * - * @return string Gift card id - */ - public function getId(): string - { - return $this->id; - } + /** + * The gift card id as created by the previous get code call + * + * @return string Gift card id + */ + public function getId(): string + { + return $this->id; + } - /** - * Creation Request id from original get code call - * - * @return string Creation request id - */ - public function getCreationRequestId(): string - { - return $this->creation_request_id; - } + /** + * Creation Request id from original get code call + * + * @return string Creation request id + */ + public function getCreationRequestId(): string + { + return $this->creation_request_id; + } - /** - * Request status - * - * @return string Request status as string: SUCCESS, FAILURE, RESEND - */ - public function getStatus(): string - { - return $this->status; - } + /** + * Request status + * + * @return string Request status as string: SUCCESS, FAILURE, RESEND + */ + public function getStatus(): string + { + return $this->status; + } - /** - * Returns the request data as json string. This is a re-encode from decoded - * makeRequest call - * - * @return string JSON encoded string from the return values - */ - public function getRawJson(): string - { - return (json_encode($this->raw_json)) ?: ''; - } + /** + * Returns the request data as json string. This is a re-encode from decoded + * makeRequest call + * + * @return string JSON encoded string from the return values + */ + public function getRawJson(): string + { + return (json_encode($this->raw_json)) ?: ''; + } - /** - * Set class variables with response data from makeRequest and return self - * - * @param array $json_response JSON response as array - * @return CancelResponse Return self object - */ - public function parseJsonResponse(array $json_response): self - { - if (array_key_exists('gcId', $json_response)) { - $this->id = $json_response['gcId']; - } - if (array_key_exists('creationRequestId', $json_response)) { - $this->creation_request_id = $json_response['creationRequestId']; - } - // SUCCESS, FAILURE, RESEND - if (array_key_exists('status', $json_response)) { - $this->status = $json_response['status']; - } + /** + * Set class variables with response data from makeRequest and return self + * + * @param array $json_response JSON response as array + * @return CancelResponse Return self object + */ + public function parseJsonResponse(array $json_response): self + { + if (array_key_exists('gcId', $json_response)) { + $this->id = $json_response['gcId']; + } + if (array_key_exists('creationRequestId', $json_response)) { + $this->creation_request_id = $json_response['creationRequestId']; + } + // SUCCESS, FAILURE, RESEND + if (array_key_exists('status', $json_response)) { + $this->status = $json_response['status']; + } - return $this; - } + return $this; + } } // __END__ diff --git a/src/Response/CreateBalanceResponse.php b/src/Response/CreateBalanceResponse.php index 4a3baac..b1fc464 100644 --- a/src/Response/CreateBalanceResponse.php +++ b/src/Response/CreateBalanceResponse.php @@ -8,120 +8,120 @@ use gullevek\AmazonIncentives\Debug\AmazonDebug; class CreateBalanceResponse { - /** @var float Amazon Gift Card Balance Amount */ - protected $amount = 0; - /** @var string Amazon Gift Card Balance Currency */ - protected $currency = ''; - /** @var string Amazon Gift Card Balance Status */ - protected $status = ''; - /** @var string Amazon Gift Card Balance Timestamp */ - protected $timestamp = ''; - /** @var array Amazon Gift Card Raw JSON */ - protected $raw_json = []; + /** @var float Amazon Gift Card Balance Amount */ + protected $amount = 0; + /** @var string Amazon Gift Card Balance Currency */ + protected $currency = ''; + /** @var string Amazon Gift Card Balance Status */ + protected $status = ''; + /** @var string Amazon Gift Card Balance Timestamp */ + protected $timestamp = ''; + /** @var array Amazon Gift Card Raw JSON */ + protected $raw_json = []; - /** - * Response constructor for requesting account funds status - * - * @param array $json_response JSON response from web request to AWS - */ - public function __construct(array $json_response) - { - $this->raw_json = $json_response; - $this->parseJsonResponse($json_response); - } + /** + * Response constructor for requesting account funds status + * + * @param array $json_response JSON response from web request to AWS + */ + public function __construct(array $json_response) + { + $this->raw_json = $json_response; + $this->parseJsonResponse($json_response); + } - /** - * Get log entry with current set log id - * - * @return array Log array - */ - public function getLog(): array - { - return AmazonDebug::getLog(AmazonDebug::getId()); - } + /** + * Get log entry with current set log id + * + * @return array Log array + */ + public function getLog(): array + { + return AmazonDebug::getLog(AmazonDebug::getId()); + } - /** - * Return the current available funds amount - * - * @return float Funds amount in set currency - */ - public function getAmount(): float - { - return $this->amount; - } + /** + * Return the current available funds amount + * + * @return float Funds amount in set currency + */ + public function getAmount(): float + { + return $this->amount; + } - /** - * Get the set currency type - * - * @return string Currency type. Eg USD, JPY, etc - */ - public function getCurrency(): string - { - return $this->currency; - } + /** + * Get the set currency type + * + * @return string Currency type. Eg USD, JPY, etc + */ + public function getCurrency(): string + { + return $this->currency; + } - /** - * Get timestamp as set. - * eg 20220609T061446Z - * - * @return string Timestamp string. Ymd\THis\Z - */ - public function getTimestamp(): string - { - return $this->timestamp; - } + /** + * Get timestamp as set. + * eg 20220609T061446Z + * + * @return string Timestamp string. Ymd\THis\Z + */ + public function getTimestamp(): string + { + return $this->timestamp; + } - /** - * Request status - * - * @return string Request status as string: SUCCESS, FAILURE, RESEND - */ - public function getStatus(): string - { - return $this->status; - } + /** + * Request status + * + * @return string Request status as string: SUCCESS, FAILURE, RESEND + */ + public function getStatus(): string + { + return $this->status; + } - /** - * Returns the request data as json string. This is a re-encode from decoded - * makeRequest call - * - * @return string JSON encoded string from the return values - */ - public function getRawJson(): string - { - return (json_encode($this->raw_json)) ?: ''; - } + /** + * Returns the request data as json string. This is a re-encode from decoded + * makeRequest call + * + * @return string JSON encoded string from the return values + */ + public function getRawJson(): string + { + return (json_encode($this->raw_json)) ?: ''; + } - /** - * Set class variables with response data from makeRequest and return self - * - * @param array $json_response JSON response as array - * @return CreateBalanceResponse Return self object - */ - public function parseJsonResponse(array $json_response): self - { - if ( - is_array($json_response['availableFunds']) && - array_key_exists('amount', $json_response['availableFunds']) && - is_numeric($json_response['availableFunds']['amount']) - ) { - $this->amount = (float)$json_response['availableFunds']['amount']; - } - if ( - is_array($json_response['availableFunds']) && - array_key_exists('currencyCode', $json_response['availableFunds']) && - is_string($json_response['availableFunds']['currencyCode']) - ) { - $this->currency = $json_response['availableFunds']['currencyCode']; - } - // SUCCESS, FAILURE, RESEND - if (array_key_exists('status', $json_response)) { - $this->status = $json_response['status']; - } - if (array_key_exists('timestamp', $json_response)) { - $this->timestamp = $json_response['timestamp']; - } + /** + * Set class variables with response data from makeRequest and return self + * + * @param array $json_response JSON response as array + * @return CreateBalanceResponse Return self object + */ + public function parseJsonResponse(array $json_response): self + { + if ( + is_array($json_response['availableFunds']) && + array_key_exists('amount', $json_response['availableFunds']) && + is_numeric($json_response['availableFunds']['amount']) + ) { + $this->amount = (float)$json_response['availableFunds']['amount']; + } + if ( + is_array($json_response['availableFunds']) && + array_key_exists('currencyCode', $json_response['availableFunds']) && + is_string($json_response['availableFunds']['currencyCode']) + ) { + $this->currency = $json_response['availableFunds']['currencyCode']; + } + // SUCCESS, FAILURE, RESEND + if (array_key_exists('status', $json_response)) { + $this->status = $json_response['status']; + } + if (array_key_exists('timestamp', $json_response)) { + $this->timestamp = $json_response['timestamp']; + } - return $this; - } + return $this; + } } diff --git a/src/Response/CreateResponse.php b/src/Response/CreateResponse.php index f85029c..f56b62d 100644 --- a/src/Response/CreateResponse.php +++ b/src/Response/CreateResponse.php @@ -8,177 +8,177 @@ use gullevek\AmazonIncentives\Debug\AmazonDebug; class CreateResponse { - /** @var string Amazon Gift Card gcId */ - protected $id = ''; - /** @var string Amazon Gift Card creationRequestId */ - protected $creation_request_id = ''; - /** @var string Amazon Gift Card gcClaimCode */ - protected $claim_code = ''; - /** @var float Amazon Gift Card amount */ - protected $value = 0; - /** @var string Amazon Gift Card currency */ - protected $currency = ''; - /** @var string Amazon Gift Card status */ - protected $status = ''; - /** @var string Amazon Gift Card Expiration Date */ - protected $expiration_date = ''; - /** @var string Amazon Gift Card Expiration Date */ - protected $card_status = ''; - /** @var array Amazon Gift Card Raw JSON as array */ - protected $raw_json = []; + /** @var string Amazon Gift Card gcId */ + protected $id = ''; + /** @var string Amazon Gift Card creationRequestId */ + protected $creation_request_id = ''; + /** @var string Amazon Gift Card gcClaimCode */ + protected $claim_code = ''; + /** @var float Amazon Gift Card amount */ + protected $value = 0; + /** @var string Amazon Gift Card currency */ + protected $currency = ''; + /** @var string Amazon Gift Card status */ + protected $status = ''; + /** @var string Amazon Gift Card Expiration Date */ + protected $expiration_date = ''; + /** @var string Amazon Gift Card Expiration Date */ + protected $card_status = ''; + /** @var array Amazon Gift Card Raw JSON as array */ + protected $raw_json = []; - /** - * Response constructor for creating gift cards - * - * @param array $json_response JSON response from web request to AWS - */ - public function __construct(array $json_response) - { - $this->raw_json = $json_response; - $this->parseJsonResponse($json_response); - } + /** + * Response constructor for creating gift cards + * + * @param array $json_response JSON response from web request to AWS + */ + public function __construct(array $json_response) + { + $this->raw_json = $json_response; + $this->parseJsonResponse($json_response); + } - /** - * Get log entry with current set log id - * - * @return array Log array - */ - public function getLog(): array - { - return AmazonDebug::getLog(AmazonDebug::getId()); - } + /** + * Get log entry with current set log id + * + * @return array Log array + */ + public function getLog(): array + { + return AmazonDebug::getLog(AmazonDebug::getId()); + } - /** - * Gift Card ID returned from AWS. Can be used in the cancel request - * - * @return string Gift card id - */ - public function getId(): string - { - return $this->id; - } + /** + * Gift Card ID returned from AWS. Can be used in the cancel request + * + * @return string Gift card id + */ + public function getId(): string + { + return $this->id; + } - /** - * Either the one set with the method parameter, or automatically created - * during get code request - * - * @return string Creation request id - */ - public function getCreationRequestId(): string - { - return $this->creation_request_id; - } + /** + * Either the one set with the method parameter, or automatically created + * during get code request + * + * @return string Creation request id + */ + public function getCreationRequestId(): string + { + return $this->creation_request_id; + } - /** - * The actual gift code, recommended not to be stored anywhere and only shown - * to user - * - * @return string Gift order claim code on AWS - */ - public function getClaimCode(): string - { - return $this->claim_code; - } + /** + * The actual gift code, recommended not to be stored anywhere and only shown + * to user + * + * @return string Gift order claim code on AWS + */ + public function getClaimCode(): string + { + return $this->claim_code; + } - /** - * The ordered gift code value in given currency - * - * @return float Gift order value in currency - */ - public function getValue(): float - { - return $this->value; - } + /** + * The ordered gift code value in given currency + * + * @return float Gift order value in currency + */ + public function getValue(): float + { + return $this->value; + } - /** - * The currently set currency - * - * @return string Currency type. Eg USD, JPY, etc - */ - public function getCurrency(): string - { - return $this->currency; - } + /** + * The currently set currency + * + * @return string Currency type. Eg USD, JPY, etc + */ + public function getCurrency(): string + { + return $this->currency; + } - /** - * Expiration date for the ordered gift code. - * eg 20220609T061446Z - * - * @return string Timestamp until when the gift code is valid. Ymd\THis\Z - */ - public function getExpirationDate(): string - { - return $this->expiration_date; - } + /** + * Expiration date for the ordered gift code. + * eg 20220609T061446Z + * + * @return string Timestamp until when the gift code is valid. Ymd\THis\Z + */ + public function getExpirationDate(): string + { + return $this->expiration_date; + } - /** - * Gift card status. If the same creation request id is sent again and the - * gift card got cancled, this is reflected here - * - * @return string Gift card status - */ - public function getCardStatus(): string - { - return $this->card_status; - } + /** + * Gift card status. If the same creation request id is sent again and the + * gift card got cancled, this is reflected here + * + * @return string Gift card status + */ + public function getCardStatus(): string + { + return $this->card_status; + } - /** - * Request status - * - * @return string Request status as string: SUCCESS, FAILURE, RESEND - */ - public function getStatus(): string - { - return $this->status; - } + /** + * Request status + * + * @return string Request status as string: SUCCESS, FAILURE, RESEND + */ + public function getStatus(): string + { + return $this->status; + } - /** - * @Returns the request data as json string. This is a re-encode from decoded - * makeRequest call - * - * @return string JSON encoded string from the return values - */ - public function getRawJson(): string - { - return (json_encode($this->raw_json)) ?: ''; - } + /** + * @Returns the request data as json string. This is a re-encode from decoded + * makeRequest call + * + * @return string JSON encoded string from the return values + */ + public function getRawJson(): string + { + return (json_encode($this->raw_json)) ?: ''; + } - /** - * Set class variables with response data from makeRequest and return self - * - * @param array $json_response JSON response as array - * @return CreateResponse Return self object - */ - public function parseJsonResponse(array $json_response): self - { - if (array_key_exists('gcId', $json_response)) { - $this->id = $json_response['gcId']; - } - if (array_key_exists('creationRequestId', $json_response)) { - $this->creation_request_id = $json_response['creationRequestId']; - } - if (array_key_exists('gcClaimCode', $json_response)) { - $this->claim_code = $json_response['gcClaimCode']; - } - if (array_key_exists('amount', $json_response['cardInfo']['value'])) { - $this->value = $json_response['cardInfo']['value']['amount']; - } - if (array_key_exists('currencyCode', $json_response['cardInfo']['value'])) { - $this->currency = $json_response['cardInfo']['value']['currencyCode']; - } - if (array_key_exists('gcExpirationDate', $json_response)) { - $this->expiration_date = $json_response['gcExpirationDate']; - } - if (array_key_exists('cardStatus', $json_response['cardInfo'])) { - $this->card_status = $json_response['cardInfo']['cardStatus']; - } - // SUCCESS, FAILURE, RESEND - if (array_key_exists('status', $json_response)) { - $this->status = $json_response['status']; - } + /** + * Set class variables with response data from makeRequest and return self + * + * @param array $json_response JSON response as array + * @return CreateResponse Return self object + */ + public function parseJsonResponse(array $json_response): self + { + if (array_key_exists('gcId', $json_response)) { + $this->id = $json_response['gcId']; + } + if (array_key_exists('creationRequestId', $json_response)) { + $this->creation_request_id = $json_response['creationRequestId']; + } + if (array_key_exists('gcClaimCode', $json_response)) { + $this->claim_code = $json_response['gcClaimCode']; + } + if (array_key_exists('amount', $json_response['cardInfo']['value'])) { + $this->value = $json_response['cardInfo']['value']['amount']; + } + if (array_key_exists('currencyCode', $json_response['cardInfo']['value'])) { + $this->currency = $json_response['cardInfo']['value']['currencyCode']; + } + if (array_key_exists('gcExpirationDate', $json_response)) { + $this->expiration_date = $json_response['gcExpirationDate']; + } + if (array_key_exists('cardStatus', $json_response['cardInfo'])) { + $this->card_status = $json_response['cardInfo']['cardStatus']; + } + // SUCCESS, FAILURE, RESEND + if (array_key_exists('status', $json_response)) { + $this->status = $json_response['status']; + } - return $this; - } + return $this; + } } // __END__ diff --git a/test/aws_gift_card_tests.php b/test/aws_gift_card_tests.php index 7de6087..8f7b640 100644 --- a/test/aws_gift_card_tests.php +++ b/test/aws_gift_card_tests.php @@ -11,10 +11,10 @@ */ function writeLog(array $data): string { - return json_encode([ - 'date' => date('Y-m-d H:i:s'), - 'log' => $data - ]) . "\n"; + return json_encode([ + 'date' => date('Y-m-d H:i:s'), + 'log' => $data + ]) . "\n"; } /** @@ -25,7 +25,7 @@ function writeLog(array $data): string */ function dateTr(string $date): string { - return date('Y-m-d H:i:s', (strtotime($date)) ?: null); + return date('Y-m-d H:i:s', (strtotime($date)) ?: null); } /** @@ -38,18 +38,18 @@ function dateTr(string $date): string * @return void */ function printException( - string $call_request, - int $error_code, - array $error, - bool $debug_print + string $call_request, + int $error_code, + array $error, + bool $debug_print ): void { - print "AWS: " . $call_request . ": " . $error['status'] - . " [" . $error_code . "]: " - . $error['code'] . " | " . $error['type'] - . " | " . $error['message']; - if ($debug_print === true) { - print "
" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "
"; - } + print "AWS: " . $call_request . ": " . $error['status'] + . " [" . $error_code . "]: " + . $error['code'] . " | " . $error['type'] + . " | " . $error['message']; + if ($debug_print === true) { + print "
" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "
"; + } } // composer auto loader @@ -95,234 +95,234 @@ $mock_debug = !empty($_GET['debug_mock']) ? true : false; $mock_wait = 2; if (empty($_GET)) { - print "Use _GET parameters to start tests"; + print "Use _GET parameters to start tests"; } // open debug file output $fp = fopen('log/debug.' . date('YmdHis') . '.log', 'w'); if (!is_resource($fp)) { - die("Cannot open log debug file"); + die("Cannot open log debug file"); } if ($run_info_test === true) { - $aws = new AmazonIncentives(); - $aws_check_me = $aws->checkMe(); - print "checkMe:
" . print_r($aws_check_me, true) . "
"; - fwrite($fp, writeLog($aws_check_me)); - print "
"; + $aws = new AmazonIncentives(); + $aws_check_me = $aws->checkMe(); + print "checkMe:
" . print_r($aws_check_me, true) . "
"; + fwrite($fp, writeLog($aws_check_me)); + print "
"; } // check balance if ($run_fund_test === true) { - try { - $aws_test = AmazonIncentives::make()->getAvailableFunds(); - print "AWS: getAvailableFunds: " . $aws_test->getStatus() . ": " - . "Amount: " . $aws_test->getAmount() . ", " - . "Currency: " . $aws_test->getCurrency() . ", " - . "Timestamp: " . $aws_test->getTimestamp(); - if ($debug_print === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - printException('getAvailableFunds', $e->getCode(), $error, $debug_print); - fwrite($fp, writeLog($error)); - }; - print "
"; - sleep($debug_wait); - // print "LOG:
" . print_r($aws_test->getLog(), true) . "

"; - print "
"; + try { + $aws_test = AmazonIncentives::make()->getAvailableFunds(); + print "AWS: getAvailableFunds: " . $aws_test->getStatus() . ": " + . "Amount: " . $aws_test->getAmount() . ", " + . "Currency: " . $aws_test->getCurrency() . ", " + . "Timestamp: " . $aws_test->getTimestamp(); + if ($debug_print === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + printException('getAvailableFunds', $e->getCode(), $error, $debug_print); + fwrite($fp, writeLog($error)); + }; + print "
"; + sleep($debug_wait); + // print "LOG:
" . print_r($aws_test->getLog(), true) . "

"; + print "
"; } if ($run_gift_tests === true) { - // create card - $value = 1000; - $creation_request_id = ''; - $gift_card_id = ''; - try { - // we must be sure we pass FLOAT there - $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value); - $creation_request_id = $aws_test->getCreationRequestId(); - $gift_card_id = $aws_test->getId(); - $claim_code = $aws_test->getClaimCode(); - $expiration_date = $aws_test->getExpirationDate(); - $request_status = $aws_test->getStatus(); - print "AWS: buyGiftCard: " . $request_status . ": " - . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " - . "EXPIRE DATE: " . dateTr($expiration_date) . ", " - . "CLAIM CODE: " . $claim_code . ""; - if ($debug_print === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (\Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - printException('buyGiftCard', $e->getCode(), $error, $debug_print); - fwrite($fp, writeLog($error)); - } - print "
"; - sleep($debug_wait); - try { - // cancel above created card card - $aws_test = AmazonIncentives::make()->cancelGiftCard($creation_request_id, $gift_card_id); - $request_status = $aws_test->getStatus(); - print "AWS: cancelGiftCard: " . $request_status . ": " - . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id; - if ($debug_print === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (\Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - print "AWS: cancelGiftCard: " . $error['status'] - . " [" . $e->getCode() . "]: " - . $error['code'] . " | " . $error['type'] - . " | " . $error['message']; - if ($debug_print === true) { - print "
" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "
"; - } - fwrite($fp, writeLog($error)); - } - print "
"; - sleep($debug_wait); - // request same card again and get error - try { - $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: CANCLED SAME CODE AGAIN: " . $request_status . ": " - . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " - . "EXPIRE DATE: " . dateTr($expiration_date) . ", " - . "CLAIM CODE: " . $claim_code . ""; - if ($debug_print === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (\Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - printException('buyGiftCard', $e->getCode(), $error, $debug_print); - fwrite($fp, writeLog($error)); - } - print "
"; - sleep($debug_wait); + // create card + $value = 1000; + $creation_request_id = ''; + $gift_card_id = ''; + try { + // we must be sure we pass FLOAT there + $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value); + $creation_request_id = $aws_test->getCreationRequestId(); + $gift_card_id = $aws_test->getId(); + $claim_code = $aws_test->getClaimCode(); + $expiration_date = $aws_test->getExpirationDate(); + $request_status = $aws_test->getStatus(); + print "AWS: buyGiftCard: " . $request_status . ": " + . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " + . "EXPIRE DATE: " . dateTr($expiration_date) . ", " + . "CLAIM CODE: " . $claim_code . ""; + if ($debug_print === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (\Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + printException('buyGiftCard', $e->getCode(), $error, $debug_print); + fwrite($fp, writeLog($error)); + } + print "
"; + sleep($debug_wait); + try { + // cancel above created card card + $aws_test = AmazonIncentives::make()->cancelGiftCard($creation_request_id, $gift_card_id); + $request_status = $aws_test->getStatus(); + print "AWS: cancelGiftCard: " . $request_status . ": " + . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id; + if ($debug_print === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (\Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + print "AWS: cancelGiftCard: " . $error['status'] + . " [" . $e->getCode() . "]: " + . $error['code'] . " | " . $error['type'] + . " | " . $error['message']; + if ($debug_print === true) { + print "
" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "
"; + } + fwrite($fp, writeLog($error)); + } + print "
"; + sleep($debug_wait); + // request same card again and get error + try { + $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: CANCLED SAME CODE AGAIN: " . $request_status . ": " + . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " + . "EXPIRE DATE: " . dateTr($expiration_date) . ", " + . "CLAIM CODE: " . $claim_code . ""; + if ($debug_print === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (\Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + printException('buyGiftCard', $e->getCode(), $error, $debug_print); + fwrite($fp, writeLog($error)); + } + print "
"; + sleep($debug_wait); - // set same request ID twice to get same response test - try { - $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value); - $creation_request_id = $aws_test->getCreationRequestId(); - $gift_card_id = $aws_test->getId(); - $claim_code = $aws_test->getClaimCode(); - $expiration_date = $aws_test->getExpirationDate(); - $request_status = $aws_test->getStatus(); - print "AWS: buyGiftCard: CODE A: " . $request_status . ": " - . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " - . "EXPIRE DATE: " . dateTr($expiration_date) . ", " - . "CLAIM CODE: " . $claim_code . ""; - if ($debug_print === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (\Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - printException('cancelGiftCard', $e->getCode(), $error, $debug_print); - fwrite($fp, writeLog($error)); - } - print "
"; - sleep($debug_wait); - try { - $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 . ", " - . "EXPIRE DATE: " . dateTr($expiration_date) . ", " - . "CLAIM CODE: " . $claim_code . ""; - if ($debug_print === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (\Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - printException('buyGiftCard', $e->getCode(), $error, $debug_print); - fwrite($fp, writeLog($error)); - } - print "
"; - print "
"; - sleep($debug_wait); + // set same request ID twice to get same response test + try { + $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value); + $creation_request_id = $aws_test->getCreationRequestId(); + $gift_card_id = $aws_test->getId(); + $claim_code = $aws_test->getClaimCode(); + $expiration_date = $aws_test->getExpirationDate(); + $request_status = $aws_test->getStatus(); + print "AWS: buyGiftCard: CODE A: " . $request_status . ": " + . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " + . "EXPIRE DATE: " . dateTr($expiration_date) . ", " + . "CLAIM CODE: " . $claim_code . ""; + if ($debug_print === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (\Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + printException('cancelGiftCard', $e->getCode(), $error, $debug_print); + fwrite($fp, writeLog($error)); + } + print "
"; + sleep($debug_wait); + try { + $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 . ", " + . "EXPIRE DATE: " . dateTr($expiration_date) . ", " + . "CLAIM CODE: " . $claim_code . ""; + if ($debug_print === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (\Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + printException('buyGiftCard', $e->getCode(), $error, $debug_print); + fwrite($fp, writeLog($error)); + } + print "
"; + print "
"; + sleep($debug_wait); } // MOCK TEST if ($run_mocks === true) { - $mock_ok = 'MOCK OK'; - $mock_failure = 'MOCK FAILURE'; - $mock_value = 500; - $mock = []; + $mock_ok = 'MOCK OK'; + $mock_failure = 'MOCK FAILURE'; + $mock_value = 500; + $mock = []; - $mock['F0000'] = [ 'ret' => '', 'st' => 'SUCCESS']; // success mock - $mock['F1000'] = [ 'ret' => 'F100', 'st' => 'FAILURE']; // SimpleAmountIsNull, etc - $mock['F2003'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountInput - $mock['F2004'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountValue - $mock['F2005'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidCurrencyCodeInput - $mock['F2010'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CardActivatedWithDifferentRequestId - $mock['F2015'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // MaxAmountExceeded - $mock['F2016'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CurrencyCodeMismatch - $mock['F2017'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // FractionalAmountNotAllowed - $mock['F2047'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CancelRequestArrivedAfterTimeLimit - $mock['F3003'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // InsufficientFunds - $mock['F3005'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // AccountHasProblems - $mock['F3010'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // CustomerSurpassedDailyVelocityLimit - $mock['F4000'] = [ 'ret' => 'F400', 'st' => 'RESEND']; // SystemTemporarilyUnavailable - $mock['F5000'] = [ 'ret' => 'F500', 'st' => 'FAILURE']; // UnknownError + $mock['F0000'] = [ 'ret' => '', 'st' => 'SUCCESS']; // success mock + $mock['F1000'] = [ 'ret' => 'F100', 'st' => 'FAILURE']; // SimpleAmountIsNull, etc + $mock['F2003'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountInput + $mock['F2004'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountValue + $mock['F2005'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidCurrencyCodeInput + $mock['F2010'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CardActivatedWithDifferentRequestId + $mock['F2015'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // MaxAmountExceeded + $mock['F2016'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CurrencyCodeMismatch + $mock['F2017'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // FractionalAmountNotAllowed + $mock['F2047'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CancelRequestArrivedAfterTimeLimit + $mock['F3003'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // InsufficientFunds + $mock['F3005'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // AccountHasProblems + $mock['F3010'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // CustomerSurpassedDailyVelocityLimit + $mock['F4000'] = [ 'ret' => 'F400', 'st' => 'RESEND']; // SystemTemporarilyUnavailable + $mock['F5000'] = [ 'ret' => 'F500', 'st' => 'FAILURE']; // UnknownError - foreach ($mock as $creation_id => $mock_return) { - print "TS: " . microtime() . ": "; - try { - $aws_test = AmazonIncentives::make()->buyGiftCard((float)$mock_value, $creation_id); - $creation_request_id = $aws_test->getCreationRequestId(); - $gift_card_id = $aws_test->getId(); - $claim_code = $aws_test->getClaimCode(); - $request_status = $aws_test->getStatus(); - print "AWS: MOCK: " . $creation_id . ": buyGiftCard: " . $request_status . ": " - . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " - . "CLAIM CODE: " . $claim_code . ": "; - if ($mock_return['st'] == $request_status) { - print $mock_ok; - } else { - print $mock_failure; - } - if ($mock_debug === true) { - print "
" . print_r($aws_test, true) . "
"; - } - fwrite($fp, writeLog((array)$aws_test)); - } catch (Exception $e) { - $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); - print "AWS: MOCK: " . $creation_id . ": buyGiftCard: " . $error['status'] - . " [" . $e->getCode() . "]: " - . $error['code'] . " | " . $error['type'] - . " | " . $error['message'] . ": "; - if ( - $mock_return['ret'] == $error['code'] && - $mock_return['st'] == $error['status'] - ) { - print $mock_ok; - } else { - print $mock_failure; - } - if ($mock_debug === true) { - print "
" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "
"; - } - fwrite($fp, writeLog($error)); - } - print "
"; - // Waiting a moment, so we don't flood - sleep($mock_wait); - } - print "
"; + foreach ($mock as $creation_id => $mock_return) { + print "TS: " . microtime() . ": "; + try { + $aws_test = AmazonIncentives::make()->buyGiftCard((float)$mock_value, $creation_id); + $creation_request_id = $aws_test->getCreationRequestId(); + $gift_card_id = $aws_test->getId(); + $claim_code = $aws_test->getClaimCode(); + $request_status = $aws_test->getStatus(); + print "AWS: MOCK: " . $creation_id . ": buyGiftCard: " . $request_status . ": " + . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " + . "CLAIM CODE: " . $claim_code . ": "; + if ($mock_return['st'] == $request_status) { + print $mock_ok; + } else { + print $mock_failure; + } + if ($mock_debug === true) { + print "
" . print_r($aws_test, true) . "
"; + } + fwrite($fp, writeLog((array)$aws_test)); + } catch (Exception $e) { + $error = AmazonErrors::decodeExceptionMessage($e->getMessage()); + print "AWS: MOCK: " . $creation_id . ": buyGiftCard: " . $error['status'] + . " [" . $e->getCode() . "]: " + . $error['code'] . " | " . $error['type'] + . " | " . $error['message'] . ": "; + if ( + $mock_return['ret'] == $error['code'] && + $mock_return['st'] == $error['status'] + ) { + print $mock_ok; + } else { + print $mock_failure; + } + if ($mock_debug === true) { + print "
" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "
"; + } + fwrite($fp, writeLog($error)); + } + print "
"; + // Waiting a moment, so we don't flood + sleep($mock_wait); + } + print "
"; } fclose($fp); diff --git a/test/phpUnit/AmazonIncentivesTest.php b/test/phpUnit/AmazonIncentivesTest.php index 401954f..ed94a44 100644 --- a/test/phpUnit/AmazonIncentivesTest.php +++ b/test/phpUnit/AmazonIncentivesTest.php @@ -16,1087 +16,1087 @@ use gullevek\dotEnv\DotEnv; */ final class AmazonIncentivesTest extends TestCase { - /** @var int wait tme in seconds between AWS side mock calls */ - private $mock_wait = 1; + /** @var int wait tme in seconds between AWS side mock calls */ + private $mock_wait = 1; - /** - * Client curl exception testing - * - * @testdox AWS Incentives curl exception handling - * - * @return void - */ - public function testAwsIncentivesCurlException(): void - { - // this is the exceptio we want - $this->expectException(AmazonIncentives\Exceptions\AmazonErrors::class); - // we don't need a class here, we just need client - $client = new AmazonIncentives\Client\Client(); - // produce any error - $client->request('invalid', [], ''); - } + /** + * Client curl exception testing + * + * @testdox AWS Incentives curl exception handling + * + * @return void + */ + public function testAwsIncentivesCurlException(): void + { + // this is the exceptio we want + $this->expectException(AmazonIncentives\Exceptions\AmazonErrors::class); + // we don't need a class here, we just need client + $client = new AmazonIncentives\Client\Client(); + // produce any error + $client->request('invalid', [], ''); + } - /** - * curl/connection error checks - * - * @return array - */ - public function amazonIncentivesProviderErrors(): array - { - // parameter data only for this - // 0: url - // 1: expected status - // 2: expected code - // 3: expected type - return [ - // C001 - 'C002 error' => [ - 'url' => 'invalid', - 'expected_status' => 'FAILURE', - 'expected_error' => 'C002', - 'expected_type' => 'CurlError' - ], - // T001 timeout - // 'T001 error' => [ - // 'url' => 'https://timeout.teq.jp', - // 'expected_status' => 'RESEND', - // 'expected_error' => 'T001', - // 'expected_type' => 'RateExceeded' - // ], - // other error - 'E999 error' => [ - 'url' => 'https://www.yahoo.co.jp', - 'expected_status' => 'FAILURE', - 'expected_error' => 'E999', - 'expected_type' => 'OtherUnknownError' - ] - ]; - } + /** + * curl/connection error checks + * + * @return array + */ + public function amazonIncentivesProviderErrors(): array + { + // parameter data only for this + // 0: url + // 1: expected status + // 2: expected code + // 3: expected type + return [ + // C001 + 'C002 error' => [ + 'url' => 'invalid', + 'expected_status' => 'FAILURE', + 'expected_error' => 'C002', + 'expected_type' => 'CurlError' + ], + // T001 timeout + // 'T001 error' => [ + // 'url' => 'https://timeout.teq.jp', + // 'expected_status' => 'RESEND', + // 'expected_error' => 'T001', + // 'expected_type' => 'RateExceeded' + // ], + // other error + 'E999 error' => [ + 'url' => 'https://www.yahoo.co.jp', + 'expected_status' => 'FAILURE', + 'expected_error' => 'E999', + 'expected_type' => 'OtherUnknownError' + ] + ]; + } - /** - * Test errors thrown in Client class - * - * @dataProvider amazonIncentivesProviderErrors - * @testdox AWS Incentives error handling [$_dataName] - * - * @param string $url - * @return void - */ - public function testAwsIncentivesCurlErrors( - string $url, - string $expected_status, - string $expected_error, - string $expected_type - ): void { - // HANDLE: - // * Init error - // - C001/Curl init error - // * Client errors (C002)/false: - // - CURLE_COULDNT_CONNECT - // - CURLE_COULDNT_RESOLVE_HOST - // - CURLE_OPERATION_TIMEOUTED - // - CURLE_SSL_PEER_CERTIFICATE - // - 0/OTHER - // * Client errors other - // - T001/Rate exceeded - // - E999/Other error + /** + * Test errors thrown in Client class + * + * @dataProvider amazonIncentivesProviderErrors + * @testdox AWS Incentives error handling [$_dataName] + * + * @param string $url + * @return void + */ + public function testAwsIncentivesCurlErrors( + string $url, + string $expected_status, + string $expected_error, + string $expected_type + ): void { + // HANDLE: + // * Init error + // - C001/Curl init error + // * Client errors (C002)/false: + // - CURLE_COULDNT_CONNECT + // - CURLE_COULDNT_RESOLVE_HOST + // - CURLE_OPERATION_TIMEOUTED + // - CURLE_SSL_PEER_CERTIFICATE + // - 0/OTHER + // * Client errors other + // - T001/Rate exceeded + // - E999/Other error - // try/catch - // -decodeExceptionMessage (static) + // try/catch + // -decodeExceptionMessage (static) - // we don't need the full interface here, we just need client class - $client = new AmazonIncentives\Client\Client(); - try { - // set expected throw error - $result = $client->request($url, [], ''); - $this->assertTrue(true, 'Successful client request'); - } catch (AmazonIncentives\Exceptions\AmazonErrors $e) { - $curl_error = AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage($e->getMessage()); - // print "E-B: " . print_r($curl_error, true) . "\n"; - $this->assertEquals( - $expected_status, - $curl_error['status'], - 'Assert error status' - ); - $this->assertEquals( - $expected_error, - $curl_error['code'], - 'Assert error code' - ); - $this->assertEquals( - $expected_type, - $curl_error['type'], - 'Assert error type' - ); - } - } + // we don't need the full interface here, we just need client class + $client = new AmazonIncentives\Client\Client(); + try { + // set expected throw error + $result = $client->request($url, [], ''); + $this->assertTrue(true, 'Successful client request'); + } catch (AmazonIncentives\Exceptions\AmazonErrors $e) { + $curl_error = AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage($e->getMessage()); + // print "E-B: " . print_r($curl_error, true) . "\n"; + $this->assertEquals( + $expected_status, + $curl_error['status'], + 'Assert error status' + ); + $this->assertEquals( + $expected_error, + $curl_error['code'], + 'Assert error code' + ); + $this->assertEquals( + $expected_type, + $curl_error['type'], + 'Assert error type' + ); + } + } - /** - * init amazon incentive interface - * - * @param array $connect - * @param bool $mock - * @param array|null $mock_response - * @return AmazonIncentives\AmazonIncentives - */ - private function awsIncentivesStartUp( - array $connect, - bool $mock, - ?array $mock_response, - ): AmazonIncentives\AmazonIncentives { - $env_folder = $connect['env_folder'] ?? ''; - $env_file = $connect['env_file'] ?? ''; - $parameters = $connect['parameters'] ?? []; - // reset _ENV always - $_ENV = []; - // env file read status - $status = null; - if (!empty($env_folder)) { - if (!empty($env_file)) { - $status = DotEnv::readEnvFile($env_folder, $env_file); - } else { - $status = DotEnv::readEnvFile($env_folder); - } - } + /** + * init amazon incentive interface + * + * @param array $connect + * @param bool $mock + * @param array|null $mock_response + * @return AmazonIncentives\AmazonIncentives + */ + private function awsIncentivesStartUp( + array $connect, + bool $mock, + ?array $mock_response, + ): AmazonIncentives\AmazonIncentives { + $env_folder = $connect['env_folder'] ?? ''; + $env_file = $connect['env_file'] ?? ''; + $parameters = $connect['parameters'] ?? []; + // reset _ENV always + $_ENV = []; + // env file read status + $status = null; + if (!empty($env_folder)) { + if (!empty($env_file)) { + $status = DotEnv::readEnvFile($env_folder, $env_file); + } else { + $status = DotEnv::readEnvFile($env_folder); + } + } - // ENV must match _ENV vars if set - if (!empty($env_folder) && $status != 0) { - // abort with error - $this->markTestSkipped( - 'Cannot read .env file needed for AWS tests: ' . $status - ); - } + // ENV must match _ENV vars if set + if (!empty($env_folder) && $status != 0) { + // abort with error + $this->markTestSkipped( + 'Cannot read .env file needed for AWS tests: ' . $status + ); + } - // MOCK: - // - for all buyGiftCard|cancelGiftCard|getAvailableFunds - // WHAT: - // \AWS->getCode|cancelCode|getBalance - // -> \AWS->makeReqeust - // -> NEW Client->request <= MOCK this - // NOT MOCK: - // any error calls in Client->request or exceptions + // MOCK: + // - for all buyGiftCard|cancelGiftCard|getAvailableFunds + // WHAT: + // \AWS->getCode|cancelCode|getBalance + // -> \AWS->makeReqeust + // -> NEW Client->request <= MOCK this + // NOT MOCK: + // any error calls in Client->request or exceptions - if ($mock === true) { - // create a new config with or without parameters - $agcod_config = new AmazonIncentives\Config\Config( - $parameters['key'] ?? null, - $parameters['secret'] ?? null, - $parameters['partner'] ?? null, - $parameters['endpoint'] ?? null, - $parameters['currency'] ?? null, - $parameters['debug'] ?? null - ); + if ($mock === true) { + // create a new config with or without parameters + $agcod_config = new AmazonIncentives\Config\Config( + $parameters['key'] ?? null, + $parameters['secret'] ?? null, + $parameters['partner'] ?? null, + $parameters['endpoint'] ?? null, + $parameters['currency'] ?? null, + $parameters['debug'] ?? null + ); - // MOCK CLIENT - // Master mock the Client class for request call - // If we wan't to get errors thrown - /** @var AmazonIncentives\Client\Client&MockObject */ - $client_mock = $this->createPartialMock(AmazonIncentives\Client\Client::class, ['request']); - // set the needed return here - $client_mock->method('request')->willReturn(json_encode($mock_response)); + // MOCK CLIENT + // Master mock the Client class for request call + // If we wan't to get errors thrown + /** @var AmazonIncentives\Client\Client&MockObject */ + $client_mock = $this->createPartialMock(AmazonIncentives\Client\Client::class, ['request']); + // set the needed return here + $client_mock->method('request')->willReturn(json_encode($mock_response)); - // MOCK AWS and attache above class in client return - /** @var AmazonIncentives\AWS\AWS&MockObject */ - $aws_mock = $this->getMockBuilder(AmazonIncentives\AWS\AWS::class) - ->setConstructorArgs([$agcod_config]) - ->onlyMethods(['newClient']) - ->getMock(); - // attach mocked client - $aws_mock->method('newClient')->willReturn($client_mock); + // MOCK AWS and attache above class in client return + /** @var AmazonIncentives\AWS\AWS&MockObject */ + $aws_mock = $this->getMockBuilder(AmazonIncentives\AWS\AWS::class) + ->setConstructorArgs([$agcod_config]) + ->onlyMethods(['newClient']) + ->getMock(); + // attach mocked client + $aws_mock->method('newClient')->willReturn($client_mock); - // MOCK AMAZONINCENTIVES - /** @var AmazonIncentives\AmazonIncentives&MockObject */ - $agcod = $this->getMockBuilder(AmazonIncentives\AmazonIncentives::class) - ->setConstructorArgs([ - $parameters['key'] ?? null, - $parameters['secret'] ?? null, - $parameters['partner'] ?? null, - $parameters['endpoint'] ?? null, - $parameters['currency'] ?? null, - $parameters['debug'] ?? null - ]) - ->onlyMethods(['newAWS']) - ->getMock(); - // attach mocked AWS class - $agcod->method('newAWS')->willReturn($aws_mock); - } else { - // if we mock, we mock the Client->request - $agcod = new AmazonIncentives\AmazonIncentives( - $parameters['key'] ?? null, - $parameters['secret'] ?? null, - $parameters['partner'] ?? null, - $parameters['endpoint'] ?? null, - $parameters['currency'] ?? null, - $parameters['debug'] ?? null - ); - } + // MOCK AMAZONINCENTIVES + /** @var AmazonIncentives\AmazonIncentives&MockObject */ + $agcod = $this->getMockBuilder(AmazonIncentives\AmazonIncentives::class) + ->setConstructorArgs([ + $parameters['key'] ?? null, + $parameters['secret'] ?? null, + $parameters['partner'] ?? null, + $parameters['endpoint'] ?? null, + $parameters['currency'] ?? null, + $parameters['debug'] ?? null + ]) + ->onlyMethods(['newAWS']) + ->getMock(); + // attach mocked AWS class + $agcod->method('newAWS')->willReturn($aws_mock); + } else { + // if we mock, we mock the Client->request + $agcod = new AmazonIncentives\AmazonIncentives( + $parameters['key'] ?? null, + $parameters['secret'] ?? null, + $parameters['partner'] ?? null, + $parameters['endpoint'] ?? null, + $parameters['currency'] ?? null, + $parameters['debug'] ?? null + ); + } - return $agcod; - } + return $agcod; + } - /** - * Holds the configs for loading data from .env for parameter - * - * @return array - */ - public function awsIncentivesProvider(): array - { - // 0: .env file folder - // 1: .env file name (if not set use .env) - // 2: parameters that override _ENV variables - return [ - // this is with real test account data - 'env_test' => [ - 'env_folder' => __DIR__ . DIRECTORY_SEPARATOR . '..', - 'env_file' => null, - 'parameters' => null - ], - // this is for mocking only - 'parameter_dummy' => [ - 'env_folder' => null, - 'env_file' => null, - 'parameters' => [ - null, - null, - null, - 'http://i.dont.exist.at.all', - 'JPY' - ] - ], - ]; - } + /** + * Holds the configs for loading data from .env for parameter + * + * @return array + */ + public function awsIncentivesProvider(): array + { + // 0: .env file folder + // 1: .env file name (if not set use .env) + // 2: parameters that override _ENV variables + return [ + // this is with real test account data + 'env_test' => [ + 'env_folder' => __DIR__ . DIRECTORY_SEPARATOR . '..', + 'env_file' => null, + 'parameters' => null + ], + // this is for mocking only + 'parameter_dummy' => [ + 'env_folder' => null, + 'env_file' => null, + 'parameters' => [ + null, + null, + null, + 'http://i.dont.exist.at.all', + 'JPY' + ] + ], + ]; + } - /** - * Undocumented function - * - * @return array - */ - public function amazonIncentivesProviderGetFunds(): array - { - // remove final keyword - // BypassFinals::enable(); - // get connectors - $connectors = $this->awsIncentivesProvider(); - // 0: connect array (env file, env folder, parameters array) - // 1: mock or normal call - // 2: if mock connect response must be defined here - // 3: exepcted response array - return [ - 'non mock test data' => [ - 'connect' => $connectors['env_test'], - 'mock' => false, - 'mock_response' => null, - 'expected' => [ - // - ] - ], - 'mock data test' => [ - 'connect' => $connectors['parameter_dummy'], - 'mock' => true, - 'mock_response' => [ - 'availableFunds' => [ - 'amount' => 0.0, - 'currencyCode' => 'JPY', - ], - 'status' => 'SUCCESS', - 'timestamp' => '20220610T085450Z', - ], - ], - ]; - } + /** + * Undocumented function + * + * @return array + */ + public function amazonIncentivesProviderGetFunds(): array + { + // remove final keyword + // BypassFinals::enable(); + // get connectors + $connectors = $this->awsIncentivesProvider(); + // 0: connect array (env file, env folder, parameters array) + // 1: mock or normal call + // 2: if mock connect response must be defined here + // 3: exepcted response array + return [ + 'non mock test data' => [ + 'connect' => $connectors['env_test'], + 'mock' => false, + 'mock_response' => null, + 'expected' => [ + // + ] + ], + 'mock data test' => [ + 'connect' => $connectors['parameter_dummy'], + 'mock' => true, + 'mock_response' => [ + 'availableFunds' => [ + 'amount' => 0.0, + 'currencyCode' => 'JPY', + ], + 'status' => 'SUCCESS', + 'timestamp' => '20220610T085450Z', + ], + ], + ]; + } - /** - * Undocumented function - * - * @dataProvider amazonIncentivesProviderGetFunds - * @testdox AWS Incentives get available funds [$_dataName] - * - * @param array $connect - * @param bool $mock - * @param array|null $mock_response - * @return void - */ - public function testAwsIncentivesGetAvailableFunds( - array $connect, - bool $mock, - ?array $mock_response - ): void { - // load class - $agcod = $this->awsIncentivesStartUp( - $connect, - $mock, - $mock_response, - ); + /** + * Undocumented function + * + * @dataProvider amazonIncentivesProviderGetFunds + * @testdox AWS Incentives get available funds [$_dataName] + * + * @param array $connect + * @param bool $mock + * @param array|null $mock_response + * @return void + */ + public function testAwsIncentivesGetAvailableFunds( + array $connect, + bool $mock, + ?array $mock_response + ): void { + // load class + $agcod = $this->awsIncentivesStartUp( + $connect, + $mock, + $mock_response, + ); - // - getAvailableFunds: get available fund - // - getStatus - // - getAmount - // - getCurrency - // - getTimestamp - try { - $funds = $agcod->getAvailableFunds(); - } catch (\Exception $e) { - $this->markTestSkipped( - $e->getMessage() - ); - } - // if not mock do type check - // if mock do matching check from mcok - if ($mock === false) { - $this->assertEquals( - 'SUCCESS', - $funds->getStatus(), - 'Assert status is success' - ); - // numeric number - $this->assertIsNumeric( - $funds->getAmount(), - 'Assert amoount is numeric' - ); - // USD, JPY, etc - $this->assertIsString( - $funds->getCurrency(), - 'Assert currency is string' - ); - // 20220610T085450Z - $this->assertMatchesRegularExpression( - "/^\d{8}T\d{6}Z$/", - $funds->getTimestamp(), - 'Assert timestamp matches regex' - ); - } else { - $this->assertEquals( - $mock_response['status'], - $funds->getStatus(), - 'Assert mock status' - ); - $this->assertEquals( - $mock_response['availableFunds']['amount'], - $funds->getAmount(), - 'Assert mock amount' - ); - $this->assertEquals( - $mock_response['availableFunds']['currencyCode'], - $funds->getCurrency(), - 'Assert mock currency code' - ); - $this->assertEquals( - $mock_response['timestamp'], - $funds->getTimestamp(), - 'Assert mock timestamp' - ); - } - } + // - getAvailableFunds: get available fund + // - getStatus + // - getAmount + // - getCurrency + // - getTimestamp + try { + $funds = $agcod->getAvailableFunds(); + } catch (\Exception $e) { + $this->markTestSkipped( + $e->getMessage() + ); + } + // if not mock do type check + // if mock do matching check from mcok + if ($mock === false) { + $this->assertEquals( + 'SUCCESS', + $funds->getStatus(), + 'Assert status is success' + ); + // numeric number + $this->assertIsNumeric( + $funds->getAmount(), + 'Assert amoount is numeric' + ); + // USD, JPY, etc + $this->assertIsString( + $funds->getCurrency(), + 'Assert currency is string' + ); + // 20220610T085450Z + $this->assertMatchesRegularExpression( + "/^\d{8}T\d{6}Z$/", + $funds->getTimestamp(), + 'Assert timestamp matches regex' + ); + } else { + $this->assertEquals( + $mock_response['status'], + $funds->getStatus(), + 'Assert mock status' + ); + $this->assertEquals( + $mock_response['availableFunds']['amount'], + $funds->getAmount(), + 'Assert mock amount' + ); + $this->assertEquals( + $mock_response['availableFunds']['currencyCode'], + $funds->getCurrency(), + 'Assert mock currency code' + ); + $this->assertEquals( + $mock_response['timestamp'], + $funds->getTimestamp(), + 'Assert mock timestamp' + ); + } + } - /** - * Undocumented function - * - * @return array - */ - public function amazonIncentivesProviderBuy(): array - { - // get connectors - $connectors = $this->awsIncentivesProvider(); - // 0: connect array (env file, env folder, parameters array) - // 1: mock or normal call - // 2: if mock connect response must be defined here - // 3: exepcted response array - // 4: value in float - return [ - 'non mock test data' => [ - 'connect' => $connectors['env_test'], - 'mock' => false, - 'mock_response' => null, - 'amount' => 500.0, - ], - 'mock data test' => [ - 'connect' => $connectors['parameter_dummy'], - 'mock' => true, - 'mock_response' => [ - 'cardInfo' => [ - 'cardNumber' => null, - 'cardStatus' => 'Fulfilled', - 'expirationDate' => null, - 'value' => [ - 'amount' => 1000.0, - 'currencyCode' => 'JPY', - ], - ], - 'creationRequestId' => 'PartnerId_62a309167e7a4', - 'gcClaimCode' => 'LJ49-AKDUV6-UYCP', - 'gcExpirationDate' => 'Thu Jun 10 14:59:59 UTC 2032', - 'gcId' => '5535125272070255', - 'status' => 'SUCCESS', - ], - 'amount' => 1000.0, - ], - ]; - } + /** + * Undocumented function + * + * @return array + */ + public function amazonIncentivesProviderBuy(): array + { + // get connectors + $connectors = $this->awsIncentivesProvider(); + // 0: connect array (env file, env folder, parameters array) + // 1: mock or normal call + // 2: if mock connect response must be defined here + // 3: exepcted response array + // 4: value in float + return [ + 'non mock test data' => [ + 'connect' => $connectors['env_test'], + 'mock' => false, + 'mock_response' => null, + 'amount' => 500.0, + ], + 'mock data test' => [ + 'connect' => $connectors['parameter_dummy'], + 'mock' => true, + 'mock_response' => [ + 'cardInfo' => [ + 'cardNumber' => null, + 'cardStatus' => 'Fulfilled', + 'expirationDate' => null, + 'value' => [ + 'amount' => 1000.0, + 'currencyCode' => 'JPY', + ], + ], + 'creationRequestId' => 'PartnerId_62a309167e7a4', + 'gcClaimCode' => 'LJ49-AKDUV6-UYCP', + 'gcExpirationDate' => 'Thu Jun 10 14:59:59 UTC 2032', + 'gcId' => '5535125272070255', + 'status' => 'SUCCESS', + ], + 'amount' => 1000.0, + ], + ]; + } - /** - * Undocumented function - * - * @dataProvider amazonIncentivesProviderBuy - * @testdox AWS Incentives buy gift card [$_dataName] - * - * @param array $connect - * @param bool $mock - * @param array|null $mock_response - * @param float $amount - * @return void - */ - public function testAwsIncentivesBuyGiftCard( - array $connect, - bool $mock, - ?array $mock_response, - float $amount - ): void { - // - init plain - // * via ::make() + /** + * Undocumented function + * + * @dataProvider amazonIncentivesProviderBuy + * @testdox AWS Incentives buy gift card [$_dataName] + * + * @param array $connect + * @param bool $mock + * @param array|null $mock_response + * @param float $amount + * @return void + */ + public function testAwsIncentivesBuyGiftCard( + array $connect, + bool $mock, + ?array $mock_response, + float $amount + ): void { + // - init plain + // * via ::make() - // - buyGiftCard: buy gift card - // - getCreationRequestId - // - getId - // - getClaimCode - // - getExpirationDate - // - getStatus + // - buyGiftCard: buy gift card + // - getCreationRequestId + // - getId + // - getClaimCode + // - getExpirationDate + // - getStatus - // load class - $agcod = $this->awsIncentivesStartUp( - $connect, - $mock, - $mock_response, - ); + // load class + $agcod = $this->awsIncentivesStartUp( + $connect, + $mock, + $mock_response, + ); - $response = $agcod->buyGiftCard($amount); + $response = $agcod->buyGiftCard($amount); - if ($mock === false) { - // type check - $this->assertEquals( - 'SUCCESS', - $response->getStatus(), - 'Assert status' - ); - // creation request id must start with partner id - $this->assertStringStartsWith( - $agcod->checkMe()['CONFIG']->getPartner(), - $response->getCreationRequestId(), - 'Assert creation request id starts with partner id' - ); - // gift card id is number - $this->assertIsString( - $response->getId(), - 'Assert gift card id is numeric' - ); - // claim code is 4-6-4 alphanumeric - $this->assertIsString( - $response->getClaimCode(), - 'Assert claim code is string' - ); - // card status - $this->assertEquals( - 'Fulfilled', - $response->getCardStatus(), - 'Assert card status' - ); - // value/amount of gitft - $this->assertEquals( - $amount, - $response->getValue(), - 'Assert card amount value' - ); - // check currency - $this->assertEquals( - $agcod->checkMe()['CONFIG']->getCurrency(), - $response->getCurrency(), - 'Assert card amount currency' - ); - // only for requests outside US/Australia cards - // expiration date: Thu Jun 10 14:59:59 UTC 2032 - $this->assertMatchesRegularExpression( - "/^[A-Z]{1}[a-z]{2} [A-Z]{1}[a-z]{2} \d{1,2} \d{1,2}:\d{1,2}:\d{1,2} [A-Z]{3} \d{4}$/", - $response->getExpirationDate(), - 'Assert expiration date regex' - ); - } else { - // value match to mock response - $this->assertEquals( - $mock_response['status'], - $response->getStatus(), - 'Assert mock status' - ); - $this->assertEquals( - $mock_response['cardInfo']['cardStatus'], - $response->getCardStatus(), - 'Assert mock card status' - ); - $this->assertEquals( - $mock_response['cardInfo']['value']['amount'], - $response->getValue(), - 'Assert mock card amount value' - ); - $this->assertEquals( - $mock_response['cardInfo']['value']['currencyCode'], - $response->getCurrency(), - 'Assert mock card amount currency' - ); - $this->assertEquals( - $mock_response['creationRequestId'], - $response->getCreationRequestId(), - 'Assert mock creation request id' - ); - $this->assertEquals( - $mock_response['gcId'], - $response->getId(), - 'Assert mock gift card id' - ); - $this->assertEquals( - $mock_response['gcClaimCode'], - $response->getClaimCode(), - 'Assert mock claim code' - ); - $this->assertEquals( - $mock_response['gcExpirationDate'], - $response->getExpirationDate(), - 'Assert mock expiration date' - ); - } - } + if ($mock === false) { + // type check + $this->assertEquals( + 'SUCCESS', + $response->getStatus(), + 'Assert status' + ); + // creation request id must start with partner id + $this->assertStringStartsWith( + $agcod->checkMe()['CONFIG']->getPartner(), + $response->getCreationRequestId(), + 'Assert creation request id starts with partner id' + ); + // gift card id is number + $this->assertIsString( + $response->getId(), + 'Assert gift card id is numeric' + ); + // claim code is 4-6-4 alphanumeric + $this->assertIsString( + $response->getClaimCode(), + 'Assert claim code is string' + ); + // card status + $this->assertEquals( + 'Fulfilled', + $response->getCardStatus(), + 'Assert card status' + ); + // value/amount of gitft + $this->assertEquals( + $amount, + $response->getValue(), + 'Assert card amount value' + ); + // check currency + $this->assertEquals( + $agcod->checkMe()['CONFIG']->getCurrency(), + $response->getCurrency(), + 'Assert card amount currency' + ); + // only for requests outside US/Australia cards + // expiration date: Thu Jun 10 14:59:59 UTC 2032 + $this->assertMatchesRegularExpression( + "/^[A-Z]{1}[a-z]{2} [A-Z]{1}[a-z]{2} \d{1,2} \d{1,2}:\d{1,2}:\d{1,2} [A-Z]{3} \d{4}$/", + $response->getExpirationDate(), + 'Assert expiration date regex' + ); + } else { + // value match to mock response + $this->assertEquals( + $mock_response['status'], + $response->getStatus(), + 'Assert mock status' + ); + $this->assertEquals( + $mock_response['cardInfo']['cardStatus'], + $response->getCardStatus(), + 'Assert mock card status' + ); + $this->assertEquals( + $mock_response['cardInfo']['value']['amount'], + $response->getValue(), + 'Assert mock card amount value' + ); + $this->assertEquals( + $mock_response['cardInfo']['value']['currencyCode'], + $response->getCurrency(), + 'Assert mock card amount currency' + ); + $this->assertEquals( + $mock_response['creationRequestId'], + $response->getCreationRequestId(), + 'Assert mock creation request id' + ); + $this->assertEquals( + $mock_response['gcId'], + $response->getId(), + 'Assert mock gift card id' + ); + $this->assertEquals( + $mock_response['gcClaimCode'], + $response->getClaimCode(), + 'Assert mock claim code' + ); + $this->assertEquals( + $mock_response['gcExpirationDate'], + $response->getExpirationDate(), + 'Assert mock expiration date' + ); + } + } - /** - * Buy a gift card and use same creation request id to get another gift card - * has to return same data ggain - * - * @dataProvider amazonIncentivesProviderBuy - * @testdox AWS Incentives buy gift card and again with same creation request id [$_dataName] - * - * @param array $connect - * @param bool $mock - * @param array|null $mock_response - * @param float $amount - * @return void - */ - public function testAwsIncentivesSameBuyGiftCard( - array $connect, - bool $mock, - ?array $mock_response, - float $amount - ): void { - // load class - $agcod = $this->awsIncentivesStartUp( - $connect, - $mock, - $mock_response, - ); - // get one - $response_a = $agcod->buyGiftCard($amount); - // get one again with same code - $response_b = $agcod->buyGiftCard($amount, $response_a->getCreationRequestId()); + /** + * Buy a gift card and use same creation request id to get another gift card + * has to return same data ggain + * + * @dataProvider amazonIncentivesProviderBuy + * @testdox AWS Incentives buy gift card and again with same creation request id [$_dataName] + * + * @param array $connect + * @param bool $mock + * @param array|null $mock_response + * @param float $amount + * @return void + */ + public function testAwsIncentivesSameBuyGiftCard( + array $connect, + bool $mock, + ?array $mock_response, + float $amount + ): void { + // load class + $agcod = $this->awsIncentivesStartUp( + $connect, + $mock, + $mock_response, + ); + // get one + $response_a = $agcod->buyGiftCard($amount); + // get one again with same code + $response_b = $agcod->buyGiftCard($amount, $response_a->getCreationRequestId()); - // a and b must be equalt - $this->assertEquals( - $response_a->getStatus(), - $response_b->getStatus(), - 'Assert status' - ); - $this->assertEquals( - $response_a->getCardStatus(), - $response_b->getCardStatus(), - 'Assert card status' - ); - $this->assertEquals( - $response_a->getValue(), - $response_b->getValue(), - 'Assert card amount value' - ); - $this->assertEquals( - $response_a->getCurrency(), - $response_b->getCurrency(), - 'Assert card amount currency' - ); - $this->assertEquals( - $response_a->getCreationRequestId(), - $response_b->getCreationRequestId(), - 'Assert creation request id' - ); - $this->assertEquals( - $response_a->getId(), - $response_b->getId(), - 'Assert gift card id' - ); - $this->assertEquals( - $response_a->getClaimCode(), - $response_b->getClaimCode(), - 'Assert claim code' - ); - $this->assertEquals( - $response_a->getExpirationDate(), - $response_b->getExpirationDate(), - 'Assert expiration date' - ); - } + // a and b must be equalt + $this->assertEquals( + $response_a->getStatus(), + $response_b->getStatus(), + 'Assert status' + ); + $this->assertEquals( + $response_a->getCardStatus(), + $response_b->getCardStatus(), + 'Assert card status' + ); + $this->assertEquals( + $response_a->getValue(), + $response_b->getValue(), + 'Assert card amount value' + ); + $this->assertEquals( + $response_a->getCurrency(), + $response_b->getCurrency(), + 'Assert card amount currency' + ); + $this->assertEquals( + $response_a->getCreationRequestId(), + $response_b->getCreationRequestId(), + 'Assert creation request id' + ); + $this->assertEquals( + $response_a->getId(), + $response_b->getId(), + 'Assert gift card id' + ); + $this->assertEquals( + $response_a->getClaimCode(), + $response_b->getClaimCode(), + 'Assert claim code' + ); + $this->assertEquals( + $response_a->getExpirationDate(), + $response_b->getExpirationDate(), + 'Assert expiration date' + ); + } - /** - * Undocumented function - * - * @return array - */ - public function amazonIncentivesProviderCancel(): array - { - // get connectors - $connectors = $this->awsIncentivesProvider(); - // 0: connect array (env file, env folder, parameters array) - // 1: mock or normal call - // 2: if mock connect response must be defined here - // 3: exepcted response array - return [ - 'non mock test data' => [ - 'connect' => $connectors['env_test'], - 'mock' => false, - 'mock_response' => null, - ], - 'mock data test' => [ - 'connect' => $connectors['parameter_dummy'], - 'mock' => true, - 'mock_response' => [ - 'creationRequestId' => 'PartnerId_62a309167e7a4', - 'gcId' => '5535125272070255', - 'status' => 'SUCCESS', - ], - ], - ]; - } + /** + * Undocumented function + * + * @return array + */ + public function amazonIncentivesProviderCancel(): array + { + // get connectors + $connectors = $this->awsIncentivesProvider(); + // 0: connect array (env file, env folder, parameters array) + // 1: mock or normal call + // 2: if mock connect response must be defined here + // 3: exepcted response array + return [ + 'non mock test data' => [ + 'connect' => $connectors['env_test'], + 'mock' => false, + 'mock_response' => null, + ], + 'mock data test' => [ + 'connect' => $connectors['parameter_dummy'], + 'mock' => true, + 'mock_response' => [ + 'creationRequestId' => 'PartnerId_62a309167e7a4', + 'gcId' => '5535125272070255', + 'status' => 'SUCCESS', + ], + ], + ]; + } - /** - * Cancel a bought gift card - * - * @dataProvider amazonIncentivesProviderCancel - * @testdox AWS Incentives cancel gift card [$_dataName] - * - * @param array $connect - * @param bool $mock - * @param array|null $mock_response - * @return void - */ - public function testAwsIncentivesCancelGiftCard( - array $connect, - bool $mock, - ?array $mock_response - ): void { - // - cancelGiftCard: cancel gift card - // load class - $agcod = $this->awsIncentivesStartUp( - $connect, - $mock, - $mock_response, - ); + /** + * Cancel a bought gift card + * + * @dataProvider amazonIncentivesProviderCancel + * @testdox AWS Incentives cancel gift card [$_dataName] + * + * @param array $connect + * @param bool $mock + * @param array|null $mock_response + * @return void + */ + public function testAwsIncentivesCancelGiftCard( + array $connect, + bool $mock, + ?array $mock_response + ): void { + // - cancelGiftCard: cancel gift card + // load class + $agcod = $this->awsIncentivesStartUp( + $connect, + $mock, + $mock_response, + ); - if ($mock === false) { - // get a gift card, then cancel it - $purchase = $agcod->buyGiftCard(500.0); - $response = $agcod->cancelGiftCard( - $purchase->getCreationRequestId(), - $purchase->getId() - ); - $this->assertEquals( - 'SUCCESS', - $response->getStatus(), - 'Assert mock status' - ); - // creation request id must start with partner id - $this->assertStringStartsWith( - $agcod->checkMe()['CONFIG']->getPartner(), - $response->getCreationRequestId(), - 'Assert creation request id starts with partner id' - ); - // gift card id is number - $this->assertIsString( - $response->getId(), - 'Assert gift card id is numeric' - ); - } else { - $response = $agcod->cancelGiftCard( - $mock_response['creationRequestId'], - $mock_response['gcId'] - ); - $this->assertEquals( - $mock_response['status'], - $response->getStatus(), - 'Assert mock status' - ); - $this->assertEquals( - $mock_response['creationRequestId'], - $response->getCreationRequestId(), - 'Assert mock creation request id' - ); - $this->assertEquals( - $mock_response['gcId'], - $response->getId(), - 'Assert mock gift card id' - ); - } - } + if ($mock === false) { + // get a gift card, then cancel it + $purchase = $agcod->buyGiftCard(500.0); + $response = $agcod->cancelGiftCard( + $purchase->getCreationRequestId(), + $purchase->getId() + ); + $this->assertEquals( + 'SUCCESS', + $response->getStatus(), + 'Assert mock status' + ); + // creation request id must start with partner id + $this->assertStringStartsWith( + $agcod->checkMe()['CONFIG']->getPartner(), + $response->getCreationRequestId(), + 'Assert creation request id starts with partner id' + ); + // gift card id is number + $this->assertIsString( + $response->getId(), + 'Assert gift card id is numeric' + ); + } else { + $response = $agcod->cancelGiftCard( + $mock_response['creationRequestId'], + $mock_response['gcId'] + ); + $this->assertEquals( + $mock_response['status'], + $response->getStatus(), + 'Assert mock status' + ); + $this->assertEquals( + $mock_response['creationRequestId'], + $response->getCreationRequestId(), + 'Assert mock creation request id' + ); + $this->assertEquals( + $mock_response['gcId'], + $response->getId(), + 'Assert mock gift card id' + ); + } + } - /** - * Undocumented function - * - * @return array - */ - public function amazonIncentivesProviderRefunded(): array - { - // get connectors - $connectors = $this->awsIncentivesProvider(); - // 0: connect array (env file, env folder, parameters array) - // 1: mock or normal call - // 2: if mock connect response must be defined here - // 3: exepcted response array - return [ - 'non mock test data' => [ - 'connect' => $connectors['env_test'], - 'mock' => false, - 'mock_response' => null, - ], - 'mock data test' => [ - 'connect' => $connectors['parameter_dummy'], - 'mock' => true, - 'mock_response' => [ - 'cardInfo' => [ - 'cardNumber' => null, - 'cardStatus' => 'RefundedToPurchaser', - 'expirationDate' => null, - 'value' => [ - 'amount' => 1000.0, - 'currencyCode' => 'JPY', - ], - ], - 'gcClaimCode' => 'LJ49-AKDUV6-UYCP', - 'creationRequestId' => 'PartnerId_62a309167e7a4', - 'gcId' => '5535125272070255', - 'status' => 'SUCCESS', - ], - ], - ]; - } + /** + * Undocumented function + * + * @return array + */ + public function amazonIncentivesProviderRefunded(): array + { + // get connectors + $connectors = $this->awsIncentivesProvider(); + // 0: connect array (env file, env folder, parameters array) + // 1: mock or normal call + // 2: if mock connect response must be defined here + // 3: exepcted response array + return [ + 'non mock test data' => [ + 'connect' => $connectors['env_test'], + 'mock' => false, + 'mock_response' => null, + ], + 'mock data test' => [ + 'connect' => $connectors['parameter_dummy'], + 'mock' => true, + 'mock_response' => [ + 'cardInfo' => [ + 'cardNumber' => null, + 'cardStatus' => 'RefundedToPurchaser', + 'expirationDate' => null, + 'value' => [ + 'amount' => 1000.0, + 'currencyCode' => 'JPY', + ], + ], + 'gcClaimCode' => 'LJ49-AKDUV6-UYCP', + 'creationRequestId' => 'PartnerId_62a309167e7a4', + 'gcId' => '5535125272070255', + 'status' => 'SUCCESS', + ], + ], + ]; + } - /** - * Undocumented function - * - * @dataProvider amazonIncentivesProviderRefunded - * @testdox AWS Incentives request cancled gift card [$_dataName] - * - * @param array $connect - * @param bool $mock - * @param array|null $mock_response - * @return void - */ - public function testAwsIncentivesRequestRefundedGiftCard( - array $connect, - bool $mock, - ?array $mock_response - ): void { - // load class - $agcod = $this->awsIncentivesStartUp( - $connect, - $mock, - $mock_response, - ); + /** + * Undocumented function + * + * @dataProvider amazonIncentivesProviderRefunded + * @testdox AWS Incentives request cancled gift card [$_dataName] + * + * @param array $connect + * @param bool $mock + * @param array|null $mock_response + * @return void + */ + public function testAwsIncentivesRequestRefundedGiftCard( + array $connect, + bool $mock, + ?array $mock_response + ): void { + // load class + $agcod = $this->awsIncentivesStartUp( + $connect, + $mock, + $mock_response, + ); - if ($mock === false) { - // get a gift card - $purchase = $agcod->buyGiftCard(500.0); - // then cancel it - $agcod->cancelGiftCard( - $purchase->getCreationRequestId(), - $purchase->getId() - ); - // buy again with same getCreationRequestId id will now have - $purchase_again = $agcod->buyGiftCard(500.0, $purchase->getCreationRequestId()); - // should return like purchase put with RefundedToPurchaser - $this->assertEquals( - 'RefundedToPurchaser', - $purchase_again->getCardStatus(), - 'Assert gift card purchased again after cancel with same code' - ); - } else { - $response = $agcod->buyGiftCard(500.0); - $this->assertEquals( - $mock_response['cardInfo']['cardStatus'], - $response->getCardStatus(), - 'Assert mock card status' - ); - } - } + if ($mock === false) { + // get a gift card + $purchase = $agcod->buyGiftCard(500.0); + // then cancel it + $agcod->cancelGiftCard( + $purchase->getCreationRequestId(), + $purchase->getId() + ); + // buy again with same getCreationRequestId id will now have + $purchase_again = $agcod->buyGiftCard(500.0, $purchase->getCreationRequestId()); + // should return like purchase put with RefundedToPurchaser + $this->assertEquals( + 'RefundedToPurchaser', + $purchase_again->getCardStatus(), + 'Assert gift card purchased again after cancel with same code' + ); + } else { + $response = $agcod->buyGiftCard(500.0); + $this->assertEquals( + $mock_response['cardInfo']['cardStatus'], + $response->getCardStatus(), + 'Assert mock card status' + ); + } + } - /** - * list of AWS mock codes for AWS side mock testing - * - * @return array - */ - public function awsIncentivesMockProvider(): array - { - return [ - 'successMock' => [ - 'creation_request_id' => 'F0000', - 'return_code' => '', - 'status' => 'SUCCESS' - ], - 'SimpleAmountIsNull' => [ - 'creation_request_id' => 'F1000', - 'return_code' => 'F100', - 'status' => 'FAILURE' - ], - 'InvalidAmountInput' => [ - 'creation_request_id' => 'F2003', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'InvalidAmountValue' => [ - 'creation_request_id' => 'F2004', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'InvalidCurrencyCodeInput' => [ - 'creation_request_id' => 'F2005', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'CardActivatedWithDifferentRequestId' => [ - 'creation_request_id' => 'F2010', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'MaxAmountExceeded' => [ - 'creation_request_id' => 'F2015', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'CurrencyCodeMismatch' => [ - 'creation_request_id' => 'F2016', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'FractionalAmountNotAllowed' => [ - 'creation_request_id' => 'F2017', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'CancelRequestArrivedAfterTimeLimit' => [ - 'creation_request_id' => 'F2047', - 'return_code' => 'F200', - 'status' => 'FAILURE' - ], - 'InsufficientFunds' => [ - 'creation_request_id' => 'F3003', - 'return_code' => 'F300', - 'status' => 'FAILURE' - ], - 'AccountHasProblems' => [ - 'creation_request_id' => 'F3005', - 'return_code' => 'F300', - 'status' => 'FAILURE' - ], - 'CustomerSurpassedDailyVelocityLimit' => [ - 'creation_request_id' => 'F3010', - 'return_code' => 'F300', - 'status' => 'FAILURE' - ], - 'SystemTemporarilyUnavailable' => [ - 'creation_request_id' => 'F4000', - 'return_code' => 'F400', - 'status' => 'RESEND' - ], - 'UnknownError' => [ - 'creation_request_id' => 'F5000', - 'return_code' => 'F500', - 'status' => 'FAILURE' - ], - ]; - } + /** + * list of AWS mock codes for AWS side mock testing + * + * @return array + */ + public function awsIncentivesMockProvider(): array + { + return [ + 'successMock' => [ + 'creation_request_id' => 'F0000', + 'return_code' => '', + 'status' => 'SUCCESS' + ], + 'SimpleAmountIsNull' => [ + 'creation_request_id' => 'F1000', + 'return_code' => 'F100', + 'status' => 'FAILURE' + ], + 'InvalidAmountInput' => [ + 'creation_request_id' => 'F2003', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'InvalidAmountValue' => [ + 'creation_request_id' => 'F2004', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'InvalidCurrencyCodeInput' => [ + 'creation_request_id' => 'F2005', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'CardActivatedWithDifferentRequestId' => [ + 'creation_request_id' => 'F2010', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'MaxAmountExceeded' => [ + 'creation_request_id' => 'F2015', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'CurrencyCodeMismatch' => [ + 'creation_request_id' => 'F2016', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'FractionalAmountNotAllowed' => [ + 'creation_request_id' => 'F2017', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'CancelRequestArrivedAfterTimeLimit' => [ + 'creation_request_id' => 'F2047', + 'return_code' => 'F200', + 'status' => 'FAILURE' + ], + 'InsufficientFunds' => [ + 'creation_request_id' => 'F3003', + 'return_code' => 'F300', + 'status' => 'FAILURE' + ], + 'AccountHasProblems' => [ + 'creation_request_id' => 'F3005', + 'return_code' => 'F300', + 'status' => 'FAILURE' + ], + 'CustomerSurpassedDailyVelocityLimit' => [ + 'creation_request_id' => 'F3010', + 'return_code' => 'F300', + 'status' => 'FAILURE' + ], + 'SystemTemporarilyUnavailable' => [ + 'creation_request_id' => 'F4000', + 'return_code' => 'F400', + 'status' => 'RESEND' + ], + 'UnknownError' => [ + 'creation_request_id' => 'F5000', + 'return_code' => 'F500', + 'status' => 'FAILURE' + ], + ]; + } - /** - * NOTE: Must have a valid test user connection setup - * This only works with a valid server connection. - * Runs through AWS Incentives mock values and checks the return code and status - * - * @dataProvider awsIncentivesMockProvider - * @testdox AWS Incentives Mock $creation_request_id will be $expected_status with $expected_code [$_dataName] - * - * @return void - */ - public function testAwsIncentivesWithMocks( - string $creation_request_id, - string $expected_code, - string $expected_status, - ): void { - // reset _ENV for reading - $_ENV = []; - // read the .env file - $status = DotEnv::readEnvFile(__DIR__ . DIRECTORY_SEPARATOR . '..'); - // if loading failed, abort - if ($status != 0) { - // abort with error - $this->markTestSkipped( - 'Cannot read .env file needed for AWS mock tests: ' . $status - ); - } - // if no value set, set to 500 - $value = $_ENV['AWS_MOCK_VALUE'] ?? 500; - // run tests - try { - $aws_gcod = AmazonIncentives\AmazonIncentives::make()->buyGiftCard( - (float)$value, - $creation_request_id - ); - $this->assertEquals( - $expected_status, - $aws_gcod->getStatus(), - 'Assert status ok in AWS GCOD mocks' - ); - } catch (\Exception $e) { - $error = AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage($e->getMessage()); - if ($error['code'] == "T001") { - $this->markTestSkipped( - "Skipped because of flooding" - ); - } - $this->assertEquals( - [ - 'code' => $expected_code, - 'status' => $expected_status, - ], - [ - 'code' => $error['code'], - 'status' => $error['status'], - ], - 'Assert status failed in AWS GCOD mocks' - ); - } - // wait a moment between tests - sleep($this->mock_wait); - } + /** + * NOTE: Must have a valid test user connection setup + * This only works with a valid server connection. + * Runs through AWS Incentives mock values and checks the return code and status + * + * @dataProvider awsIncentivesMockProvider + * @testdox AWS Incentives Mock $creation_request_id will be $expected_status with $expected_code [$_dataName] + * + * @return void + */ + public function testAwsIncentivesWithMocks( + string $creation_request_id, + string $expected_code, + string $expected_status, + ): void { + // reset _ENV for reading + $_ENV = []; + // read the .env file + $status = DotEnv::readEnvFile(__DIR__ . DIRECTORY_SEPARATOR . '..'); + // if loading failed, abort + if ($status != 0) { + // abort with error + $this->markTestSkipped( + 'Cannot read .env file needed for AWS mock tests: ' . $status + ); + } + // if no value set, set to 500 + $value = $_ENV['AWS_MOCK_VALUE'] ?? 500; + // run tests + try { + $aws_gcod = AmazonIncentives\AmazonIncentives::make()->buyGiftCard( + (float)$value, + $creation_request_id + ); + $this->assertEquals( + $expected_status, + $aws_gcod->getStatus(), + 'Assert status ok in AWS GCOD mocks' + ); + } catch (\Exception $e) { + $error = AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage($e->getMessage()); + if ($error['code'] == "T001") { + $this->markTestSkipped( + "Skipped because of flooding" + ); + } + $this->assertEquals( + [ + 'code' => $expected_code, + 'status' => $expected_status, + ], + [ + 'code' => $error['code'], + 'status' => $error['status'], + ], + 'Assert status failed in AWS GCOD mocks' + ); + } + // wait a moment between tests + sleep($this->mock_wait); + } - /** - * Undocumented function - * - * @return array - */ - public function checkMeProvider(): array - { - // 0: .env file folder - // 1: .env file name (if not set use .env) - // 2: parameters that override _ENV variables - return [ - 'default all empty' => [ - 'use_env' => null, - 'env_file' => null, - 'parameters' => null, - ], - 'set parameters' => [ - 'env_folder' => null, - 'env_file' => null, - 'parameters' => [ - 'key' => 'key', - 'secret' => 'secret', - 'partner' => 'partner id', - 'endpoint' => 'https://endpoint.test.com', - 'currency' => 'currency', - 'debug' => true, - ], - 'expected' => [], - ], - 'load from env' => [ - 'env_folder' => __DIR__ . DIRECTORY_SEPARATOR . '..', - 'env_file' => null, - 'parameters' => null, - ], - 'load from env, but override parameter' => [ - 'env_folder' => __DIR__ . DIRECTORY_SEPARATOR . '..', - 'env_file' => null, - 'parameters' => [ - 'key' => 'key', - 'secret' => 'secret', - 'partner' => 'partner id', - 'endpoint' => 'https://endpoint.test.com', - 'currency' => 'currency', - ] - ] - // test missing parameter, set vie _ENV - ]; - } + /** + * Undocumented function + * + * @return array + */ + public function checkMeProvider(): array + { + // 0: .env file folder + // 1: .env file name (if not set use .env) + // 2: parameters that override _ENV variables + return [ + 'default all empty' => [ + 'use_env' => null, + 'env_file' => null, + 'parameters' => null, + ], + 'set parameters' => [ + 'env_folder' => null, + 'env_file' => null, + 'parameters' => [ + 'key' => 'key', + 'secret' => 'secret', + 'partner' => 'partner id', + 'endpoint' => 'https://endpoint.test.com', + 'currency' => 'currency', + 'debug' => true, + ], + 'expected' => [], + ], + 'load from env' => [ + 'env_folder' => __DIR__ . DIRECTORY_SEPARATOR . '..', + 'env_file' => null, + 'parameters' => null, + ], + 'load from env, but override parameter' => [ + 'env_folder' => __DIR__ . DIRECTORY_SEPARATOR . '..', + 'env_file' => null, + 'parameters' => [ + 'key' => 'key', + 'secret' => 'secret', + 'partner' => 'partner id', + 'endpoint' => 'https://endpoint.test.com', + 'currency' => 'currency', + ] + ] + // test missing parameter, set vie _ENV + ]; + } - /** - * Check the checkMe function that will work with or without any settings - * passed on. - * This also tests basic loading - * - parseing for endoint as url - * - override check for _ENV vs parameter - * - * @cover ::checkMe - * @dataProvider checkMeProvider - * @testdox AmazonIncentives tests [$_dataName] - * - * @param string|null $env_folder - * @param string|null $env_file - * @param array|null $parameters - * @return void - */ - public function testCheckMe(?string $env_folder, ?string $env_file, ?array $parameters): void - { - // reset _ENV before each run to avoid nothing to load errors - $_ENV = []; - // env load status - $status = null; - if (!empty($env_folder)) { - if (!empty($env_file)) { - $status = DotEnv::readEnvFile($env_folder, $env_file); - } else { - $status = DotEnv::readEnvFile($env_folder); - } - } - if (!empty($parameters)) { - $aws = new AmazonIncentives\AmazonIncentives( - $parameters['key'], - $parameters['secret'], - $parameters['partner'], - $parameters['endpoint'], - $parameters['currency'], - $parameters['debug'] ?? null, - ); - } else { - $aws = new AmazonIncentives\AmazonIncentives(); - } - $aws_check_me = $aws->checkMe(); - // ENV must match _ENV vars if set - if (!empty($env_folder) && $status != 0) { - // abort with error - $this->markTestSkipped( - 'Cannot read .env file needed: ' . $status - ); - } elseif (!empty($env_folder)) { - $this->assertEquals( - $_ENV, - $aws_check_me['ENV'], - 'Assert _ENV set equal' - ); - } - // compare that data matches - // print "CM: " . print_r($aws_check_me, true) . "\n"; - // CONFIG must match to parameters or ENV, parsed host name check - $this->assertEquals( - // parameter > _ENV -> empty - !empty($parameters['partner']) ? - $parameters['partner'] : - $_ENV['AWS_GIFT_CARD_PARTNER_ID'] ?? '', - $aws_check_me['CONFIG']->getPartner(), - 'Assert config matching input' - ); - // KEY must match access_key/AWS_GIFT_CARD_KEY - $this->assertEquals( - $aws_check_me['CONFIG']->getAccessKey(), - $aws_check_me['KEY'], - 'Assert access key m' - ); - } + /** + * Check the checkMe function that will work with or without any settings + * passed on. + * This also tests basic loading + * - parseing for endoint as url + * - override check for _ENV vs parameter + * + * @cover ::checkMe + * @dataProvider checkMeProvider + * @testdox AmazonIncentives tests [$_dataName] + * + * @param string|null $env_folder + * @param string|null $env_file + * @param array|null $parameters + * @return void + */ + public function testCheckMe(?string $env_folder, ?string $env_file, ?array $parameters): void + { + // reset _ENV before each run to avoid nothing to load errors + $_ENV = []; + // env load status + $status = null; + if (!empty($env_folder)) { + if (!empty($env_file)) { + $status = DotEnv::readEnvFile($env_folder, $env_file); + } else { + $status = DotEnv::readEnvFile($env_folder); + } + } + if (!empty($parameters)) { + $aws = new AmazonIncentives\AmazonIncentives( + $parameters['key'], + $parameters['secret'], + $parameters['partner'], + $parameters['endpoint'], + $parameters['currency'], + $parameters['debug'] ?? null, + ); + } else { + $aws = new AmazonIncentives\AmazonIncentives(); + } + $aws_check_me = $aws->checkMe(); + // ENV must match _ENV vars if set + if (!empty($env_folder) && $status != 0) { + // abort with error + $this->markTestSkipped( + 'Cannot read .env file needed: ' . $status + ); + } elseif (!empty($env_folder)) { + $this->assertEquals( + $_ENV, + $aws_check_me['ENV'], + 'Assert _ENV set equal' + ); + } + // compare that data matches + // print "CM: " . print_r($aws_check_me, true) . "\n"; + // CONFIG must match to parameters or ENV, parsed host name check + $this->assertEquals( + // parameter > _ENV -> empty + !empty($parameters['partner']) ? + $parameters['partner'] : + $_ENV['AWS_GIFT_CARD_PARTNER_ID'] ?? '', + $aws_check_me['CONFIG']->getPartner(), + 'Assert config matching input' + ); + // KEY must match access_key/AWS_GIFT_CARD_KEY + $this->assertEquals( + $aws_check_me['CONFIG']->getAccessKey(), + $aws_check_me['KEY'], + 'Assert access key m' + ); + } } // __END__ diff --git a/test/phpUnit/Hook/BypassFinalHook.php b/test/phpUnit/Hook/BypassFinalHook.php index 2963b0d..d36ef37 100644 --- a/test/phpUnit/Hook/BypassFinalHook.php +++ b/test/phpUnit/Hook/BypassFinalHook.php @@ -12,10 +12,10 @@ use PHPUnit\Runner\BeforeFirstTestHook; // only works if it is the FIRST load and not before EACH test final class BypassFinalHook implements BeforeFirstTestHook { - public function executeBeforeFirstTest(): void - { - BypassFinals::enable(); - } + public function executeBeforeFirstTest(): void + { + BypassFinals::enable(); + } } // __END__