16 Commits

Author SHA1 Message Date
59d4612a0a Documentation update for development part 2026-01-13 18:42:12 +09:00
aeb84dcb60 Switch to PHPunit 12 and adjust code accordingly 2026-01-13 18:26:16 +09:00
b0d8c55536 Add phive tools folder, Switch to tabs for indent and add phpcs.xml 2026-01-13 11:06:11 +09:00
4adbf4e30a Run CI only on pull requests 2025-03-10 19:53:43 +09:00
09df49009a Fix .gitignore 2025-02-28 12:57:54 +09:00
33a48f47de Update unit tests to allow skip if AWS API flood
on Github a lot of API tests will fail with "T001" flooding, so we just skip them
2025-01-21 11:11:56 +09:00
cf5ece0b5f github flow yml had tabs instead of spaces 2025-01-21 11:07:10 +09:00
db8df612b4 Remove phpunit from github actions 2025-01-21 11:05:58 +09:00
75f4d0b10a Add phpstan to compoer dev install 2025-01-21 11:02:55 +09:00
7fed1c2a85 Readme update 2025-01-21 10:55:11 +09:00
28a9e390cc Code clean up with declare strict and php stan level 9 checks
add "declare(strict_types=1);" to all pages

Add a json handler class to handle that json_decode always returns array<mixed> and throws error otherwise
On failure these will throw the normal JSON encoded error was FAILURE with code "J-" and the number is the json error
If 0 then the return was null or some other problem that did not return an array

amount is float and not string and checks are done that the returned value is a float

various updates for phpdoc array delcarations
- curl header is array<int, string>
- the log array is proper declared as array with string key and a list of mixed arrays
2025-01-21 10:48:41 +09:00
a565d2899b Comment typo fix 2024-08-21 11:22:33 +09:00
58b126ab83 Rename the github action job 2024-05-22 18:42:48 +09:00
e9a6332ad0 Add skip on error for funds test 2024-05-22 18:26:46 +09:00
a79fd519ed Gitbub action cache 2024-05-22 18:02:01 +09:00
04aa9fa019 Github actions add 2024-05-22 17:27:20 +09:00
25 changed files with 3011 additions and 2806 deletions

55
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,55 @@
name: CI
run-name: ${{ github.actor}} runs CI
on:
pull_request:
branches:
- main
- master
- staging
- development
jobs:
ci-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: php-actions/composer@v6
env:
COMPOSER_ROOT_VERSION: dev-master
- name: "Restore result cache"
uses: actions/cache/restore@v4
with:
path: ./tmp
key: "result-cache-v1-${{ matrix.php-version }}-${{ github.run_id }}"
restore-keys: |
result-cache-v1-${{ matrix.php-version }}-
- name: PHPStan Static Analysis
uses: php-actions/phpstan@v3
with:
path: src/
- name: "Save result cache"
uses: actions/cache/save@v4
if: always()
with:
path: ./tmp
key: "result-cache-v1-${{ matrix.php-version }}-${{ github.run_id }}"
# We need to use phpunit from the self install to get the class paths
# Skip auto tests here, there are too many problems with flooding of the AWS API from github
- name: PHPunit Tests Prepare
env:
AWS_GIFT_CARD_ENDPOINT: "${{ secrets.AWS_GIFT_CARD_ENDPOINT }}"
AWS_GIFT_CARD_KEY: "${{ secrets.AWS_GIFT_CARD_KEY }}"
AWS_GIFT_CARD_SECRET: "${{ secrets.AWS_GIFT_CARD_SECRET }}"
AWS_GIFT_CARD_PARTNER_ID: "${{ secrets.AWS_GIFT_CARD_PARTNER_ID }}"
AWS_GIFT_CARD_CURRENCY: "${{ secrets.AWS_GIFT_CARD_CURRENCY }}"
run: |
echo "AWS_GIFT_CARD_ENDPOINT=${AWS_GIFT_CARD_ENDPOINT}" > test/.env;
echo "AWS_GIFT_CARD_KEY=${AWS_GIFT_CARD_KEY}" >> test/.env;
echo "AWS_GIFT_CARD_SECRET=${AWS_GIFT_CARD_SECRET}" >> test/.env;
echo "AWS_GIFT_CARD_PARTNER_ID=${AWS_GIFT_CARD_PARTNER_ID}" >> test/.env;
echo "AWS_GIFT_CARD_CURRENCY=${AWS_GIFT_CARD_CURRENCY}" >> test/.env;
echo "AWS_DEBUG=1" >> test/.env;
- name: PHPunit Tests
run: |
vendor/bin/phpunit

4
.gitignore vendored
View File

@@ -1,3 +1,7 @@
vendor
.phpunit.result.cache
composer.lock
**/.env
**/.target
.phpunit.cache/
tools/

View File

@@ -26,73 +26,77 @@
// use Phan\Config;
return [
// If true, missing properties will be created when
// they are first seen. If false, we'll report an
// error message.
"allow_missing_properties" => false,
// turn color on (-C)
"color_issue_messages_if_supported" => true,
// set minimum version
"minimum_target_php_version" => "7.4",
// If true, missing properties will be created when
// they are first seen. If false, we'll report an
// error message.
"allow_missing_properties" => false,
// Allow null to be cast as any type and for any
// type to be cast to null.
"null_casts_as_any_type" => false,
// Allow null to be cast as any type and for any
// type to be cast to null.
"null_casts_as_any_type" => false,
// Backwards Compatibility Checking
'backward_compatibility_checks' => true,
// Backwards Compatibility Checking
'backward_compatibility_checks' => true,
// Run a quick version of checks that takes less
// time
"quick_mode" => false,
// Run a quick version of checks that takes less
// time
"quick_mode" => false,
// Only emit critical issues to start with
// (0 is low severity, 5 is normal severity, 10 is critical)
"minimum_severity" => 10,
// Only emit critical issues to start with
// (0 is low severity, 5 is normal severity, 10 is critical)
"minimum_severity" => 10,
// default false for include path check
"enable_include_path_checks" => true,
"include_paths" => [
],
'ignore_undeclared_variables_in_global_scope' => true,
// default false for include path check
"enable_include_path_checks" => true,
"include_paths" => [
],
'ignore_undeclared_variables_in_global_scope' => true,
"file_list" => [
],
"file_list" => [
],
// A list of directories that should be parsed for class and
// method information. After excluding the directories
// defined in exclude_analysis_directory_list, the remaining
// files will be statically analyzed for errors.
//
// Thus, both first-party and third-party code being used by
// your application should be included in this list.
'directory_list' => [
// Change this to include the folders you wish to analyze
// (and the folders of their dependencies)
'.'
// 'www',
// To speed up analysis, we recommend going back later and
// limiting this to only the vendor/ subdirectories your
// project depends on.
// `phan --init` will generate a list of folders for you
//'www/vendor',
],
// A list of directories that should be parsed for class and
// method information. After excluding the directories
// defined in exclude_analysis_directory_list, the remaining
// files will be statically analyzed for errors.
//
// Thus, both first-party and third-party code being used by
// your application should be included in this list.
'directory_list' => [
// Change this to include the folders you wish to analyze
// (and the folders of their dependencies)
'src/'
// 'www',
// To speed up analysis, we recommend going back later and
// limiting this to only the vendor/ subdirectories your
// project depends on.
// `phan --init` will generate a list of folders for you
//'www/vendor',
],
// A list of directories holding code that we want
// to parse, but not analyze
"exclude_analysis_directory_list" => [
'vendor',
'test',
],
'exclude_file_list' => [
],
// A list of directories holding code that we want
// to parse, but not analyze
"exclude_analysis_directory_list" => [
'vendor',
'test',
],
'exclude_file_list' => [
],
// what not to show as problem
'suppress_issue_types' => [
// 'PhanUndeclaredMethod',
'PhanEmptyFile',
],
// what not to show as problem
'suppress_issue_types' => [
// 'PhanUndeclaredMethod',
'PhanEmptyFile',
],
// Override to hardcode existence and types of (non-builtin) globals in the global scope.
// Class names should be prefixed with `\`.
//
// (E.g. `['_FOO' => '\FooClass', 'page' => '\PageClass', 'userId' => 'int']`)
'globals_type_map' => [],
// Override to hardcode existence and types of (non-builtin) globals in the global scope.
// Class names should be prefixed with `\`.
//
// (E.g. `['_FOO' => '\FooClass', 'page' => '\PageClass', 'userId' => 'int']`)
'globals_type_map' => [],
];

8
.phive/phars.xml Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<phive xmlns="https://phar.io/phive">
<phar name="phpcs" version="^4.0.1" installed="4.0.1" location="./tools/phpcs" copy="false"/>
<phar name="phpcbf" version="^4.0.1" installed="4.0.1" location="./tools/phpcbf" copy="false"/>
<phar name="phan" version="^5.5.2" installed="5.5.2" location="./tools/phan" copy="false"/>
<phar name="phpstan" version="^2.1.33" installed="2.1.33" location="./tools/phpstan" copy="false"/>
<phar name="phpunit" version="^12.5.4" installed="12.5.4" location="./tools/phpunit" copy="false"/>
</phive>

View File

@@ -127,6 +127,11 @@ fif code is C001 curl failed to init
if code is C002 a curl error has happened
### J-number
if a JSON error was encountered during some encoding this error will be found.
The number is the json error code.
### empty error code
any other NON amazon error will have only 'message' set if run through decode
@@ -147,3 +152,40 @@ 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
Run `composer install` or `phive install` to setup the tools
phpcs config is stored in `phpcs.xml` and should be picked up by the standard tools
* we use tabs instead of spaces for indents, the rest is standard PSR1+PSR12
### Direct tests
These direct run tests exist:
* `tests/aws_read_env_tests.php`: Equal to running `tests/aws_gift_card_tests.php?info=true`, will output env test data
* `test/aws_gift_card_tests.php`: The following parameters exists
* info: set to print out info
* fund: set to run funds get tests
* gift: run all the gift card get/set/remove tests
* mocks: run the error checks
* debug: print out debug information
* debug_mock: print out all the debug logs too
### Phan
`vendor/bin/phan --analyze-twice` or `tools/phan --analyze-twice`
### PHPstan
`vendor/bin/phpstan` or `tools/phpstan`
> [!notice] Level 9 is set as we have various mixed values that cannot be easily changed into a direct value type
### PHPUnit
Unit tests have to be run from base folder with
`vendor/bin/phpunit` or `tools/phpunit`

View File

@@ -25,8 +25,10 @@
"exclude": ["/test/", "/test/*", "/phpstan.neon", "/psalm.xml", "/.phan/", "/.vscode/", "/phpunit.xml"]
},
"require-dev": {
"phpunit/phpunit": "^9",
"gullevek/dotenv": "dev-master",
"dg/bypass-finals": "dev-master"
"dg/bypass-finals": "dev-master",
"phpstan/phpstan": "2.1.x-dev",
"phpstan/phpstan-deprecation-rules": "2.0.x-dev",
"phpunit/phpunit": "^12"
}
}

18
phpcs.xml Normal file
View File

@@ -0,0 +1,18 @@
<?xml version="1.0"?>
<ruleset name="MyStandard">
<description>PSR12 override rules (strict, standard). Switch spaces indent to tab.</description>
<arg name="tab-width" value="4"/>
<rule ref="PSR1"/>
<rule ref="PSR12">
<!-- turn off white space check for tab -->
<exclude name="Generic.WhiteSpace.DisallowTabIndent"/>
</rule>
<!-- no space indent, must be tab, 4 is tab iwdth -->
<rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/>
<rule ref="Generic.WhiteSpace.ScopeIndent">
<properties>
<property name="indent" value="4"/>
<property name="tabIndent" value="true"/>
</properties>
</rule>
</ruleset>

View File

@@ -1,10 +1,10 @@
# PHP Stan Config
parameters:
tmpDir: /tmp/phpstan-codeblocks-amazon-incentives
level: 8
tmpDir: %currentWorkingDirectory%/tmp/phpstan-codeblocks-amazon-incentives
level: 9
paths:
- %currentWorkingDirectory%
- %currentWorkingDirectory%/src
excludePaths:
# ignore composer
- vendor

View File

@@ -1,9 +1,12 @@
<phpunit
colors="true"
verbose="true"
>
<?xml version="1.0"?>
<phpunit colors="true" cacheDirectory=".phpunit.cache" bootstrap="vendor/autoload.php" >
<!-- Below removes final from classes for mock tests -->
<extensions>
<extension class="test\phpUnit\Hook\BypassFinalHook" file="test/phpUnit/Hook/BypassFinalHook.php" />
<bootstrap class="DG\BypassFinals\PHPUnitExtension"/>
</extensions>
<testsuites>
<testsuite name="unit">
<directory>test/phpUnit/</directory>
</testsuite>
</testsuites>
</phpunit>

File diff suppressed because it is too large Load Diff

View File

@@ -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<mixed> 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<mixed> 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<mixed>
*/
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<mixed>
*/
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__

View File

@@ -1,119 +1,127 @@
<?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Client;
use gullevek\AmazonIncentives\Exceptions\AmazonErrors;
use gullevek\AmazonIncentives\Debug\AmazonDebug;
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<mixed> $headers Headers to be used in the request
* @param array<mixed>|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<int,string> $headers Headers to be used in the request
* @param array<mixed>|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
$result_ar = json_decode((string)$result, true);
// 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__

View File

@@ -1,18 +1,20 @@
<?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Client;
interface ClientInterface
{
/**
* @param string $url The URL being requested,
* including domain and protocol
* @param array<mixed> $headers Headers to be used in the request
* @param array<mixed>|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<mixed> $headers Headers to be used in the request
* @param array<mixed>|string $params Can be nested for arrays and hashes
*
* @return String
*/
public function request(string $url, array $headers, $params): string;
}
// __END__

View File

@@ -1,213 +1,216 @@
<?php
declare(strict_types=1);
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 = (string)($_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__

View File

@@ -1,74 +1,76 @@
<?php
declare(strict_types=1);
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__

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
// simple write all into an array that we can poll in the return group
// to activate AmazonDebug::setDebug(true) must be called once
@@ -7,103 +9,103 @@ namespace gullevek\AmazonIncentives\Debug;
class AmazonDebug
{
/** @var array<mixed> 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<string,array<array<mixed>>> 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<mixed> $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<mixed> $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<mixed> 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<mixed> 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__

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Exceptions;
use RuntimeException;
@@ -7,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,
// atach 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<mixed> 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 = [
'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<mixed> 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__

42
src/Handle/Json.php Normal file
View File

@@ -0,0 +1,42 @@
<?php
/**
* Handle json conversions
*/
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Handle;
use gullevek\AmazonIncentives\Exceptions\AmazonErrors;
class Json
{
/**
* decode json string
*
* @param string $json
* @return array<mixed>
* @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__

View File

@@ -1,103 +1,105 @@
<?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Response;
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<mixed> 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<mixed> Amazon Gift Card Raw JSON */
protected $raw_json = [];
/**
* Response constructor for canceling gitf cards
*
* @param array<mixed> $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<mixed> $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<mixed> Log array
*/
public function getLog(): array
{
return AmazonDebug::getLog(AmazonDebug::getId());
}
/**
* Get log entry with current set log id
*
* @return array<mixed> 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<mixed> $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<mixed> $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__

View File

@@ -1,117 +1,127 @@
<?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Response;
use gullevek\AmazonIncentives\Debug\AmazonDebug;
class CreateBalanceResponse
{
/** @var string Amazon Gift Card Balance Amount */
protected $amount = '';
/** @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<mixed> 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<mixed> Amazon Gift Card Raw JSON */
protected $raw_json = [];
/**
* Response constructor for requesting account funds status
*
* @param array<mixed> $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<mixed> $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<mixed> Log array
*/
public function getLog(): array
{
return AmazonDebug::getLog(AmazonDebug::getId());
}
/**
* Get log entry with current set log id
*
* @return array<mixed> Log array
*/
public function getLog(): array
{
return AmazonDebug::getLog(AmazonDebug::getId());
}
/**
* Return the current available funds amount
*
* @return string Funds amount in set currency
*/
public function getAmount(): string
{
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<mixed> $json_response JSON response as array
* @return CreateBalanceResponse Return self object
*/
public function parseJsonResponse(array $json_response): self
{
if (array_key_exists('amount', $json_response['availableFunds'])) {
$this->amount = $json_response['availableFunds']['amount'];
}
if (array_key_exists('currencyCode', $json_response['availableFunds'])) {
$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<mixed> $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;
}
}

View File

@@ -1,182 +1,184 @@
<?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Response;
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<mixed> 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<mixed> Amazon Gift Card Raw JSON as array */
protected $raw_json = [];
/**
* Response constructor for creating gift cards
*
* @param array<mixed> $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<mixed> $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<mixed> Log array
*/
public function getLog(): array
{
return AmazonDebug::getLog(AmazonDebug::getId());
}
/**
* Get log entry with current set log id
*
* @return array<mixed> 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<mixed> $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<mixed> $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__

View File

@@ -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 "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
}
print "AWS: " . $call_request . ": " . $error['status']
. " [" . $error_code . "]: "
. $error['code'] . " | " . $error['type']
. " | " . $error['message'];
if ($debug_print === true) {
print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
}
}
// composer auto loader
@@ -95,234 +95,234 @@ $mock_debug = !empty($_GET['debug_mock']) ? true : false;
$mock_wait = 2;
if (empty($_GET)) {
print "<b>Use _GET parameters to start tests</b>";
print "<b>Use _GET parameters to start tests</b>";
}
// 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: <pre>" . print_r($aws_check_me, true) . "</pre>";
fwrite($fp, writeLog($aws_check_me));
print "<hr>";
$aws = new AmazonIncentives();
$aws_check_me = $aws->checkMe();
print "checkMe: <pre>" . print_r($aws_check_me, true) . "</pre>";
fwrite($fp, writeLog($aws_check_me));
print "<hr>";
}
// 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 "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
sleep($debug_wait);
// print "LOG: <pre>" . print_r($aws_test->getLog(), true) . "</pre><br>";
print "<hr>";
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 "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
sleep($debug_wait);
// print "LOG: <pre>" . print_r($aws_test->getLog(), true) . "</pre><br>";
print "<hr>";
}
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
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 "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
}
fwrite($fp, writeLog($error));
}
print "<br>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
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 "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
}
fwrite($fp, writeLog($error));
}
print "<br>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
print "<hr>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
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: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<br>";
print "<hr>";
sleep($debug_wait);
}
// MOCK TEST
if ($run_mocks === true) {
$mock_ok = '<span style="color:green;">MOCK OK</span>';
$mock_failure = '<span style="color:red;">MOCK FAILURE</span>';
$mock_value = 500;
$mock = [];
$mock_ok = '<span style="color:green;">MOCK OK</span>';
$mock_failure = '<span style="color:red;">MOCK FAILURE</span>';
$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 "<b>TS: " . microtime() . "</b>: ";
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: <b>" . $request_status . "</b>: "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "CLAIM CODE: <b>" . $claim_code . "</b>: ";
if ($mock_return['st'] == $request_status) {
print $mock_ok;
} else {
print $mock_failure;
}
if ($mock_debug === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
}
fwrite($fp, writeLog($error));
}
print "<br>";
// Waiting a moment, so we don't flood
sleep($mock_wait);
}
print "<hr>";
foreach ($mock as $creation_id => $mock_return) {
print "<b>TS: " . microtime() . "</b>: ";
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: <b>" . $request_status . "</b>: "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "CLAIM CODE: <b>" . $claim_code . "</b>: ";
if ($mock_return['st'] == $request_status) {
print $mock_ok;
} else {
print $mock_failure;
}
if ($mock_debug === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>";
}
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 "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
}
fwrite($fp, writeLog($error));
}
print "<br>";
// Waiting a moment, so we don't flood
sleep($mock_wait);
}
print "<hr>";
}
fclose($fp);

File diff suppressed because it is too large Load Diff

View File

@@ -1,21 +0,0 @@
<?php
// strip the final name from a to be mocked class
declare(strict_types=1);
namespace test\phpUnit\Hook;
use DG\BypassFinals;
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();
}
}
// __END__

2
tmp/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore