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 vendor
.phpunit.result.cache .phpunit.result.cache
composer.lock composer.lock
**/.env
**/.target
.phpunit.cache/
tools/

View File

@@ -26,73 +26,77 @@
// use Phan\Config; // use Phan\Config;
return [ return [
// If true, missing properties will be created when // turn color on (-C)
// they are first seen. If false, we'll report an "color_issue_messages_if_supported" => true,
// error message. // set minimum version
"allow_missing_properties" => false, "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 // Allow null to be cast as any type and for any
// type to be cast to null. // type to be cast to null.
"null_casts_as_any_type" => false, "null_casts_as_any_type" => false,
// Backwards Compatibility Checking // Backwards Compatibility Checking
'backward_compatibility_checks' => true, 'backward_compatibility_checks' => true,
// Run a quick version of checks that takes less // Run a quick version of checks that takes less
// time // time
"quick_mode" => false, "quick_mode" => false,
// Only emit critical issues to start with // Only emit critical issues to start with
// (0 is low severity, 5 is normal severity, 10 is critical) // (0 is low severity, 5 is normal severity, 10 is critical)
"minimum_severity" => 10, "minimum_severity" => 10,
// default false for include path check // default false for include path check
"enable_include_path_checks" => true, "enable_include_path_checks" => true,
"include_paths" => [ "include_paths" => [
], ],
'ignore_undeclared_variables_in_global_scope' => true, 'ignore_undeclared_variables_in_global_scope' => true,
"file_list" => [ "file_list" => [
], ],
// A list of directories that should be parsed for class and // A list of directories that should be parsed for class and
// method information. After excluding the directories // method information. After excluding the directories
// defined in exclude_analysis_directory_list, the remaining // defined in exclude_analysis_directory_list, the remaining
// files will be statically analyzed for errors. // files will be statically analyzed for errors.
// //
// Thus, both first-party and third-party code being used by // Thus, both first-party and third-party code being used by
// your application should be included in this list. // your application should be included in this list.
'directory_list' => [ 'directory_list' => [
// Change this to include the folders you wish to analyze // Change this to include the folders you wish to analyze
// (and the folders of their dependencies) // (and the folders of their dependencies)
'.' 'src/'
// 'www', // 'www',
// To speed up analysis, we recommend going back later and // To speed up analysis, we recommend going back later and
// limiting this to only the vendor/ subdirectories your // limiting this to only the vendor/ subdirectories your
// project depends on. // project depends on.
// `phan --init` will generate a list of folders for you // `phan --init` will generate a list of folders for you
//'www/vendor', //'www/vendor',
], ],
// A list of directories holding code that we want // A list of directories holding code that we want
// to parse, but not analyze // to parse, but not analyze
"exclude_analysis_directory_list" => [ "exclude_analysis_directory_list" => [
'vendor', 'vendor',
'test', 'test',
], ],
'exclude_file_list' => [ 'exclude_file_list' => [
], ],
// what not to show as problem // what not to show as problem
'suppress_issue_types' => [ 'suppress_issue_types' => [
// 'PhanUndeclaredMethod', // 'PhanUndeclaredMethod',
'PhanEmptyFile', 'PhanEmptyFile',
], ],
// Override to hardcode existence and types of (non-builtin) globals in the global scope. // Override to hardcode existence and types of (non-builtin) globals in the global scope.
// Class names should be prefixed with `\`. // Class names should be prefixed with `\`.
// //
// (E.g. `['_FOO' => '\FooClass', 'page' => '\PageClass', 'userId' => 'int']`) // (E.g. `['_FOO' => '\FooClass', 'page' => '\PageClass', 'userId' => 'int']`)
'globals_type_map' => [], '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 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 ### empty error code
any other NON amazon error will have only 'message' set if run through decode 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 sucessful run the log data is accessable with `$aws->getLog()`
On exception the log data is in the error message json (see exceptions) 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"] "exclude": ["/test/", "/test/*", "/phpstan.neon", "/psalm.xml", "/.phan/", "/.vscode/", "/phpunit.xml"]
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^9",
"gullevek/dotenv": "dev-master", "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 # PHP Stan Config
parameters: parameters:
tmpDir: /tmp/phpstan-codeblocks-amazon-incentives tmpDir: %currentWorkingDirectory%/tmp/phpstan-codeblocks-amazon-incentives
level: 8 level: 9
paths: paths:
- %currentWorkingDirectory% - %currentWorkingDirectory%/src
excludePaths: excludePaths:
# ignore composer # ignore composer
- vendor - vendor

View File

@@ -1,9 +1,12 @@
<phpunit <?xml version="1.0"?>
colors="true" <phpunit colors="true" cacheDirectory=".phpunit.cache" bootstrap="vendor/autoload.php" >
verbose="true"
>
<!-- Below removes final from classes for mock tests --> <!-- Below removes final from classes for mock tests -->
<extensions> <extensions>
<extension class="test\phpUnit\Hook\BypassFinalHook" file="test/phpUnit/Hook/BypassFinalHook.php" /> <bootstrap class="DG\BypassFinals\PHPUnitExtension"/>
</extensions> </extensions>
<testsuites>
<testsuite name="unit">
<directory>test/phpUnit/</directory>
</testsuite>
</testsuites>
</phpunit> </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 final class AmazonIncentives
{ {
/** /**
* @var Config * @var Config
*/ */
private $config; private $config;
/** /**
* AmazonGiftCode constructor. * AmazonGiftCode constructor.
* *
* @param string|null $key Account key * @param string|null $key Account key
* @param string|null $secret Secret key * @param string|null $secret Secret key
* @param string|null $partner Partner ID * @param string|null $partner Partner ID
* @param string|null $endpoint Endpoint URL including https:// * @param string|null $endpoint Endpoint URL including https://
* @param string|null $currency Currency type. Eg USD, JPY, etc * @param string|null $currency Currency type. Eg USD, JPY, etc
* @param bool|null $debug Debug flag * @param bool|null $debug Debug flag
*/ */
public function __construct( public function __construct(
string $key = null, ?string $key = null,
string $secret = null, ?string $secret = null,
string $partner = null, ?string $partner = null,
string $endpoint = null, ?string $endpoint = null,
string $currency = null, ?string $currency = null,
bool $debug = null ?bool $debug = null
) { ) {
// load AWS settings // load AWS settings
// fail here if settings missing // fail here if settings missing
$this->config = new Config($key, $secret, $partner, $endpoint, $currency, $debug); $this->config = new Config($key, $secret, $partner, $endpoint, $currency, $debug);
// init debug // init debug
AmazonDebug::setDebug($this->config->getDebug()); AmazonDebug::setDebug($this->config->getDebug());
} }
// ********************************************************************* // *********************************************************************
// PRIVATE HELPER METHODS // PRIVATE HELPER METHODS
// ********************************************************************* // *********************************************************************
// ********************************************************************* // *********************************************************************
// PUBLIC METHODS // PUBLIC METHODS
// ********************************************************************* // *********************************************************************
/** /**
* Buy a gift card * Buy a gift card
* *
* @param float $value Amount to purchase a gift card * @param float $value Amount to purchase a gift card
* in currency value * in currency value
* @param string|null $creation_request_id Override automatically created request id * @param string|null $creation_request_id Override automatically created request id
* If not set will create a new one, or * If not set will create a new one, or
* return data for created one * return data for created one
* @return Response\CreateResponse Returns new created response object or * @return Response\CreateResponse Returns new created response object or
* previous created if creation_request_id was used * previous created if creation_request_id was used
* *
* @throws AmazonErrors * @throws AmazonErrors
*/ */
public function buyGiftCard(float $value, string $creation_request_id = null): Response\CreateResponse public function buyGiftCard(float $value, ?string $creation_request_id = null): Response\CreateResponse
{ {
return ($this->newAWS())->getCode($value, $creation_request_id); return ($this->newAWS())->getCode($value, $creation_request_id);
} }
/** /**
* Cancel a previous created gift card, if within the time frame * Cancel a previous created gift card, if within the time frame
* *
* @param string $creation_request_id Previous created request id from buyGiftCard * @param string $creation_request_id Previous created request id from buyGiftCard
* @param string $gift_card_id Previous gift card id from buyGiftCard (gcId) * @param string $gift_card_id Previous gift card id from buyGiftCard (gcId)
* @return Response\CancelResponse Returns the cancled request object * @return Response\CancelResponse Returns the cancled request object
* *
* @throws AmazonErrors * @throws AmazonErrors
*/ */
public function cancelGiftCard(string $creation_request_id, string $gift_card_id): Response\CancelResponse public function cancelGiftCard(string $creation_request_id, string $gift_card_id): Response\CancelResponse
{ {
return ($this->newAWS())->cancelCode($creation_request_id, $gift_card_id); return ($this->newAWS())->cancelCode($creation_request_id, $gift_card_id);
} }
/** /**
* Gets the current funds in this account * Gets the current funds in this account
* *
* @return Response\CreateBalanceResponse Returns the account funds object * @return Response\CreateBalanceResponse Returns the account funds object
* *
* @throws AmazonErrors * @throws AmazonErrors
*/ */
public function getAvailableFunds(): Response\CreateBalanceResponse public function getAvailableFunds(): Response\CreateBalanceResponse
{ {
return ($this->newAWS())->getBalance(); return ($this->newAWS())->getBalance();
} }
/** /**
* AmazonIncentives creates own client and returns it as static object * AmazonIncentives creates own client and returns it as static object
* *
* @param string|null $key Account key * @param string|null $key Account key
* @param string|null $secret Secret key * @param string|null $secret Secret key
* @param string|null $partner Partner ID * @param string|null $partner Partner ID
* @param string|null $endpoint Endpoint URL including https:// * @param string|null $endpoint Endpoint URL including https://
* @param string|null $currency Currency type. Eg USD, JPY, etc * @param string|null $currency Currency type. Eg USD, JPY, etc
* @param bool|null $debug Debug flag * @param bool|null $debug Debug flag
* @return AmazonIncentives self class * @return AmazonIncentives self class
*/ */
public static function make( public static function make(
string $key = null, ?string $key = null,
string $secret = null, ?string $secret = null,
string $partner = null, ?string $partner = null,
string $endpoint = null, ?string $endpoint = null,
string $currency = null, ?string $currency = null,
bool $debug = null ?bool $debug = null
): AmazonIncentives { ): AmazonIncentives {
return new static($key, $secret, $partner, $endpoint, $currency, $debug); return new static($key, $secret, $partner, $endpoint, $currency, $debug);
} }
/** /**
* wrapper to create new AWS class. * wrapper to create new AWS class.
* used in all buy/cancel/get calss * used in all buy/cancel/get calss
* *
* @return AWS Main AWS worker class * @return AWS Main AWS worker class
*/ */
public function newAWS(): AWS public function newAWS(): AWS
{ {
return new AWS($this->config); return new AWS($this->config);
} }
/** /**
* Decodes the Exception message body * Decodes the Exception message body
* Returns an array with code (Amazon error codes), type (Amazon error info) * Returns an array with code (Amazon error codes), type (Amazon error info)
* message (Amazon returned error message string) * message (Amazon returned error message string)
* *
* @param string $message Exception message json string * @param string $message Exception message json string
* @return array<mixed> Decoded with code, type, message fields * @return array<mixed> Decoded with code, type, message fields
* *
* @deprecated use \gullevek\AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage() * @deprecated use \gullevek\AmazonIncentives\Exceptions\AmazonErrors::decodeExceptionMessage()
*/ */
public static function decodeExceptionMessage(string $message): array public static function decodeExceptionMessage(string $message): array
{ {
return AmazonErrors::decodeExceptionMessage($message); return AmazonErrors::decodeExceptionMessage($message);
} }
// ********************************************************************* // *********************************************************************
// PUBLIC TEST METHODS // PUBLIC TEST METHODS
// ********************************************************************* // *********************************************************************
/** /**
* Prints out ENV, CONFIG and KEY data * Prints out ENV, CONFIG and KEY data
* This is for debug only, this will print out secrets. * This is for debug only, this will print out secrets.
* Use with care * Use with care
* *
* @return array<mixed> * @return array<mixed>
*/ */
public function checkMe(): array public function checkMe(): array
{ {
$data = []; $data = [];
$data['ENV'] = $_ENV; $data['ENV'] = $_ENV;
$data['CONFIG'] = $this->config; $data['CONFIG'] = $this->config;
$data['KEY'] = $this->config->getAccessKey(); $data['KEY'] = $this->config->getAccessKey();
return $data; return $data;
} }
} }
// __END__ // __END__

View File

@@ -1,119 +1,127 @@
<?php <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Client; namespace gullevek\AmazonIncentives\Client;
use gullevek\AmazonIncentives\Exceptions\AmazonErrors; use gullevek\AmazonIncentives\Exceptions\AmazonErrors;
use gullevek\AmazonIncentives\Debug\AmazonDebug; use gullevek\AmazonIncentives\Debug\AmazonDebug;
use gullevek\AmazonIncentives\Handle\Json;
class Client implements ClientInterface class Client implements ClientInterface
{ {
/** @var int instead of JsonResponse::HTTP_OK */ /** @var int instead of JsonResponse::HTTP_OK */
private const HTTP_OK = 200; private const HTTP_OK = 200;
/** /**
* Makes an request to the target url via curl * Makes an request to the target url via curl
* Returns result as string (json) * Returns result as string (json)
* *
* @param string $url The URL being requested, * @param string $url The URL being requested,
* including domain and protocol * including domain and protocol
* @param array<mixed> $headers Headers to be used in the request * @param array<int,string> $headers Headers to be used in the request
* @param array<mixed>|string $params Can be nested for arrays and hashes * @param array<mixed>|string $params Can be nested for arrays and hashes
* @return string Result as json string * @return string Result as json string
*/ */
public function request(string $url, array $headers, $params): string public function request(string $url, array $headers, $params): string
{ {
$handle = curl_init($url); $handle = curl_init($url);
if ($handle === false) { if ($handle === false) {
// throw Error here with all codes // throw Error here with all codes
throw AmazonErrors::getError( throw AmazonErrors::getError(
'FAILURE', 'FAILURE',
'C001', 'C001',
'CurlInitError', 'CurlInitError',
'Failed to init curl with url: ' . $url, 'Failed to init curl with url: ' . $url,
0 0
); );
} }
curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($handle, CURLOPT_FAILONERROR, true); // curl_setopt($handle, CURLOPT_FAILONERROR, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $params); curl_setopt($handle, CURLOPT_POSTFIELDS, $params);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($handle); $result = curl_exec($handle);
if ($result === false) { if ($result === false) {
$err = curl_errno($handle); $err = curl_errno($handle);
$message = curl_error($handle); $message = curl_error($handle);
$this->handleCurlError($url, $err, $message); $this->handleCurlError($url, $err, $message);
} }
if (curl_getinfo($handle, CURLINFO_HTTP_CODE) !== self::HTTP_OK) { if (curl_getinfo($handle, CURLINFO_HTTP_CODE) !== self::HTTP_OK) {
$err = curl_errno($handle); $err = curl_errno($handle);
AmazonDebug::writeLog(['CURL_REQUEST_RESULT' => $result]); AmazonDebug::writeLog(['CURL_REQUEST_RESULT' => $result]);
// extract all the error codes from Amazon // extract all the error codes from Amazon
$result_ar = json_decode((string)$result, true); // note we do not care about result errors here, if json decode fails, just set to empty
// if message is 'Rate exceeded', set different error try {
if (($result_ar['message'] ?? '') == 'Rate exceeded') { $result_ar = Json::jsonDecode((string)$result);
$error_status = 'RESEND'; } catch (AmazonErrors $e) {
$error_code = 'T001'; $result_ar = [];
$error_type = 'RateExceeded'; }
$message = $result_ar['message'] ?? 'Rate exceeded'; // if message is 'Rate exceeded', set different error
} else { if (($result_ar['message'] ?? '') == 'Rate exceeded') {
// for all other error messages $error_status = 'RESEND';
$error_status = $result_ar['agcodResponse']['status'] ?? 'FAILURE'; $error_code = 'T001';
$error_code = $result_ar['errorCode'] ?? 'E999'; $error_type = 'RateExceeded';
$error_type = $result_ar['errorType'] ?? 'OtherUnknownError'; $message = $result_ar['message'] ?? 'Rate exceeded';
$message = $result_ar['message'] ?? 'Unknown error occured'; } else {
} // for all other error messages
// throw Error here with all codes $error_status = $result_ar['agcodResponse']['status'] ?? 'FAILURE';
throw AmazonErrors::getError( $error_code = $result_ar['errorCode'] ?? 'E999';
$error_status, $error_type = $result_ar['errorType'] ?? 'OtherUnknownError';
$error_code, $message = $result_ar['message'] ?? 'Unknown error occured';
$error_type, }
$message, // throw Error here with all codes
$err throw AmazonErrors::getError(
); $error_status,
} $error_code,
return (string)$result; $error_type,
} $message,
$err
);
}
return (string)$result;
}
/** /**
* handles any CURL errors and throws an error with the correct * handles any CURL errors and throws an error with the correct
* error message * error message
* *
* @param string $url The url that was originaly used * @param string $url The url that was originaly used
* @param int $errno Error number from curl handler * @param int $errno Error number from curl handler
* @param string $message The error message string from curl * @param string $message The error message string from curl
* @return void * @return void
*/ */
private function handleCurlError(string $url, int $errno, string $message): void private function handleCurlError(string $url, int $errno, string $message): void
{ {
switch ($errno) { switch ($errno) {
case CURLE_COULDNT_CONNECT: case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST: case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED: case CURLE_OPERATION_TIMEOUTED:
$message = 'Could not connect to AWS (' . $url . '). Please check your ' $message = 'Could not connect to AWS (' . $url . '). Please check your '
. 'internet connection and try again. [' . $message . ']'; . 'internet connection and try again. [' . $message . ']';
break; break;
case CURLE_SSL_PEER_CERTIFICATE: case CURLE_SSL_PEER_CERTIFICATE:
$message = 'Could not verify AWS SSL certificate. Please make sure ' $message = 'Could not verify AWS SSL certificate. Please make sure '
. 'that your network is not intercepting certificates. ' . 'that your network is not intercepting certificates. '
. '(Try going to ' . $url . 'in your browser.) ' . '(Try going to ' . $url . 'in your browser.) '
. '[' . $message . ']'; . '[' . $message . ']';
break; break;
case 0: case 0:
default: default:
$message = 'Unexpected error communicating with AWS: ' . $message; $message = 'Unexpected error communicating with AWS: ' . $message;
} }
// throw an error like in the normal reqeust, but set to CURL error // throw an error like in the normal reqeust, but set to CURL error
throw AmazonErrors::getError( throw AmazonErrors::getError(
'FAILURE', 'FAILURE',
'C002', 'C002',
'CurlError', 'CurlError',
$message, $message,
$errno $errno
); );
} }
} }
// __END__ // __END__

View File

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

View File

@@ -1,213 +1,216 @@
<?php <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Config; namespace gullevek\AmazonIncentives\Config;
class Config implements ConfigInterface class Config implements ConfigInterface
{ {
/** @var string Endpoint URL without https:// */ /** @var string Endpoint URL without https:// */
private $endpoint = ''; private $endpoint = '';
/** @var string Access Key */ /** @var string Access Key */
private $access_key = ''; private $access_key = '';
/** @var string Secret Key */ /** @var string Secret Key */
private $secret_key = ''; private $secret_key = '';
/** @var string Partner ID */ /** @var string Partner ID */
private $partner_id = ''; private $partner_id = '';
/** @var string Currency type as USD, JPY, etc */ /** @var string Currency type as USD, JPY, etc */
private $currency = ''; private $currency = '';
/** @var bool Debug flag on or off */ /** @var bool Debug flag on or off */
private $debug = false; private $debug = false;
/** /**
* @param string|null $key Access key * @param string|null $key Access key
* @param string|null $secret Secret Key * @param string|null $secret Secret Key
* @param string|null $partner Partner ID * @param string|null $partner Partner ID
* @param string|null $endpoint Endpoing URL including https:// * @param string|null $endpoint Endpoing URL including https://
* @param string|null $currency Currency to use, see valid list on AWS documentation. * @param string|null $currency Currency to use, see valid list on AWS documentation.
* valid names are like USD, JPY, etc * valid names are like USD, JPY, etc
* @param bool|null $debug Debug flag * @param bool|null $debug Debug flag
*/ */
public function __construct( public function __construct(
?string $key, ?string $key,
?string $secret, ?string $secret,
?string $partner, ?string $partner,
?string $endpoint, ?string $endpoint,
?string $currency, ?string $currency,
?bool $debug ?bool $debug
) { ) {
/** /**
* @psalm-suppress InvalidScalarArgument * @psalm-suppress InvalidScalarArgument
* @phpstan-ignore-next-line * @phpstan-ignore-next-line
*/ */
$this->setAccessKey(($key) ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); $this->setAccessKey(($key) ?: $this->parseEnv('AWS_GIFT_CARD_KEY'));
/** /**
* @psalm-suppress InvalidScalarArgument * @psalm-suppress InvalidScalarArgument
* @phpstan-ignore-next-line * @phpstan-ignore-next-line
*/ */
$this->setSecret(($secret) ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); $this->setSecret(($secret) ?: $this->parseEnv('AWS_GIFT_CARD_SECRET'));
/** /**
* @psalm-suppress InvalidScalarArgument * @psalm-suppress InvalidScalarArgument
* @phpstan-ignore-next-line * @phpstan-ignore-next-line
*/ */
$this->setPartner(($partner) ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); $this->setPartner(($partner) ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID'));
/** /**
* @psalm-suppress InvalidScalarArgument * @psalm-suppress InvalidScalarArgument
* @phpstan-ignore-next-line * @phpstan-ignore-next-line
*/ */
$this->setEndpoint(($endpoint) ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); $this->setEndpoint(($endpoint) ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT'));
/** /**
* @psalm-suppress InvalidScalarArgument * @psalm-suppress InvalidScalarArgument
* @phpstan-ignore-next-line * @phpstan-ignore-next-line
*/ */
$this->setCurrency(($currency) ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); $this->setCurrency(($currency) ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY'));
/** /**
* @psalm-suppress InvalidScalarArgument * @psalm-suppress InvalidScalarArgument
* @phpstan-ignore-next-line * @phpstan-ignore-next-line
*/ */
$this->setDebug(($debug) ?: $this->parseEnv('AWS_DEBUG')); $this->setDebug(($debug) ?: $this->parseEnv('AWS_DEBUG'));
} }
/** /**
* string key to search, returns entry from _ENV * string key to search, returns entry from _ENV
* if not matchin key, returns empty * if not matchin key, returns empty
* *
* @param string $key To search in _ENV array * @param string $key To search in _ENV array
* @return string|bool Returns either string or true/false (DEBUG flag) * @return string|bool Returns either string or true/false (DEBUG flag)
*/ */
private function parseEnv(string $key) private function parseEnv(string $key)
{ {
$return = ''; $return = '';
switch ($key) { switch ($key) {
case 'AWS_DEBUG': case 'AWS_DEBUG':
$return = !empty($_ENV['AWS_DEBUG']) ? true : false; $return = !empty($_ENV['AWS_DEBUG']) ? true : false;
break; break;
case 'AWS_GIFT_CARD_KEY': case 'AWS_GIFT_CARD_KEY':
case 'AWS_GIFT_CARD_SECRET': case 'AWS_GIFT_CARD_SECRET':
case 'AWS_GIFT_CARD_PARTNER_ID': case 'AWS_GIFT_CARD_PARTNER_ID':
case 'AWS_GIFT_CARD_ENDPOINT': case 'AWS_GIFT_CARD_ENDPOINT':
case 'AWS_GIFT_CARD_CURRENCY': case 'AWS_GIFT_CARD_CURRENCY':
$return = (string)($_ENV[$key] ?? ''); $return = !empty($_ENV[$key]) && is_string($_ENV[$key]) ?
break; $_ENV[$key] : '';
default: break;
break; default:
} break;
return $return; }
} return $return;
}
/** /**
* @return string Returns current set endpoint, without https:// * @return string Returns current set endpoint, without https://
*/ */
public function getEndpoint(): string public function getEndpoint(): string
{ {
return $this->endpoint; return $this->endpoint;
} }
/** /**
* @param string $endpoint Full endpoint url with https:// * @param string $endpoint Full endpoint url with https://
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setEndpoint(string $endpoint): ConfigInterface public function setEndpoint(string $endpoint): ConfigInterface
{ {
// TODO: check valid endpoint + set region // TODO: check valid endpoint + set region
$this->endpoint = (parse_url($endpoint, PHP_URL_HOST)) ?: ''; $this->endpoint = (parse_url($endpoint, PHP_URL_HOST)) ?: '';
return $this; return $this;
} }
/** /**
* @return string Current access key * @return string Current access key
*/ */
public function getAccessKey(): string public function getAccessKey(): string
{ {
return $this->access_key; return $this->access_key;
} }
/** /**
* @param string $key Access Key to set * @param string $key Access Key to set
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setAccessKey(string $key): ConfigInterface public function setAccessKey(string $key): ConfigInterface
{ {
$this->access_key = $key; $this->access_key = $key;
return $this; return $this;
} }
/** /**
* @return string Current secret key * @return string Current secret key
*/ */
public function getSecret(): string public function getSecret(): string
{ {
return $this->secret_key; return $this->secret_key;
} }
/** /**
* @param string $secret Secret key to set * @param string $secret Secret key to set
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setSecret(string $secret): ConfigInterface public function setSecret(string $secret): ConfigInterface
{ {
$this->secret_key = $secret; $this->secret_key = $secret;
return $this; return $this;
} }
/** /**
* @return string Current set currency * @return string Current set currency
*/ */
public function getCurrency(): string public function getCurrency(): string
{ {
return $this->currency; return $this->currency;
} }
/** /**
* @param string $currency Currency to set (eg USD, JPY, etc) * @param string $currency Currency to set (eg USD, JPY, etc)
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setCurrency(string $currency): ConfigInterface public function setCurrency(string $currency): ConfigInterface
{ {
// TODO: check currency valid + currenc valid for region // TODO: check currency valid + currenc valid for region
$this->currency = $currency; $this->currency = $currency;
return $this; return $this;
} }
/** /**
* @return string Current set partner id * @return string Current set partner id
*/ */
public function getPartner(): string public function getPartner(): string
{ {
return $this->partner_id; return $this->partner_id;
} }
/** /**
* @param string $partner Partner id to set * @param string $partner Partner id to set
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setPartner(string $partner): ConfigInterface public function setPartner(string $partner): ConfigInterface
{ {
$this->partner_id = $partner; $this->partner_id = $partner;
return $this; return $this;
} }
/** /**
* @return bool Current set debug flag as bool * @return bool Current set debug flag as bool
*/ */
public function getDebug(): bool public function getDebug(): bool
{ {
return $this->debug; return $this->debug;
} }
/** /**
* @param bool $debug Set debug flag as bool * @param bool $debug Set debug flag as bool
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setDebug(bool $debug): ConfigInterface public function setDebug(bool $debug): ConfigInterface
{ {
$this->debug = $debug; $this->debug = $debug;
return $this; return $this;
} }
} }
// __END__ // __END__

View File

@@ -1,74 +1,76 @@
<?php <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Config; namespace gullevek\AmazonIncentives\Config;
interface ConfigInterface interface ConfigInterface
{ {
/** /**
* @return string Returns current set endpoint, without https:// * @return string Returns current set endpoint, without https://
*/ */
public function getEndpoint(): string; public function getEndpoint(): string;
/** /**
* @param string $endpoint Full endpoint url with https:// * @param string $endpoint Full endpoint url with https://
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setEndpoint(string $endpoint): ConfigInterface; public function setEndpoint(string $endpoint): ConfigInterface;
/** /**
* @return string Current access key * @return string Current access key
*/ */
public function getAccessKey(): string; public function getAccessKey(): string;
/** /**
* @param string $key Access Key to set * @param string $key Access Key to set
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setAccessKey(string $key): ConfigInterface; public function setAccessKey(string $key): ConfigInterface;
/** /**
* @return string Current secret key * @return string Current secret key
*/ */
public function getSecret(): string; public function getSecret(): string;
/** /**
* @param string $secret Secret key to set * @param string $secret Secret key to set
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setSecret(string $secret): ConfigInterface; public function setSecret(string $secret): ConfigInterface;
/** /**
* @return string Current set currency * @return string Current set currency
*/ */
public function getCurrency(): string; public function getCurrency(): string;
/** /**
* @param string $currency Currency to set (eg USD, JPY, etc) * @param string $currency Currency to set (eg USD, JPY, etc)
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setCurrency(string $currency): ConfigInterface; public function setCurrency(string $currency): ConfigInterface;
/** /**
* @return string Current set partner id * @return string Current set partner id
*/ */
public function getPartner(): string; public function getPartner(): string;
/** /**
* @param string $partner Partner id to set * @param string $partner Partner id to set
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setPartner(string $partner): ConfigInterface; public function setPartner(string $partner): ConfigInterface;
/** /**
* @return bool Current set debug flag as bool * @return bool Current set debug flag as bool
*/ */
public function getDebug(): bool; public function getDebug(): bool;
/** /**
* @param bool $debug Set debug flag as bool * @param bool $debug Set debug flag as bool
* @return ConfigInterface Class interface (self) * @return ConfigInterface Class interface (self)
*/ */
public function setDebug(bool $debug): ConfigInterface; public function setDebug(bool $debug): ConfigInterface;
} }
// __END__ // __END__

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
// simple write all into an array that we can poll in the return group // simple write all into an array that we can poll in the return group
// to activate AmazonDebug::setDebug(true) must be called once // to activate AmazonDebug::setDebug(true) must be called once
@@ -7,103 +9,103 @@ namespace gullevek\AmazonIncentives\Debug;
class AmazonDebug class AmazonDebug
{ {
/** @var array<mixed> Log data array log id -> array of log entries */ /** @var array<string,array<array<mixed>>> Log data array log id -> array of log entries */
private static $log = []; private static $log = [];
/** @var bool debug flag */ /** @var bool debug flag */
private static $debug = false; private static $debug = false;
/** @var string|null Last set internal log array id */ /** @var string|null Last set internal log array id */
private static $id = null; private static $id = null;
/** /**
* set the ID for current run * set the ID for current run
* if debug is off, nothing will be set and id is null * if debug is off, nothing will be set and id is null
* This is run on setFlag, if debug is true * This is run on setFlag, if debug is true
* *
* @param string|null $id If not set, will default to uniqid() call * @param string|null $id If not set, will default to uniqid() call
* @return void * @return void
*/ */
private static function setId(?string $id = null): void private static function setId(?string $id = null): void
{ {
if (self::$debug === false) { if (self::$debug === false) {
return; return;
} }
if ($id === null) { if ($id === null) {
$id = uniqid(); $id = uniqid();
} }
self::$id = $id; self::$id = $id;
} }
/** /**
* set the debug flag. * set the debug flag.
* This is automatically run in gullevek\AmazonIncentives\AmazonIncentives::__construct * This is automatically run in gullevek\AmazonIncentives\AmazonIncentives::__construct
* No need to run manuall * No need to run manuall
* *
* @param boolean $debug Can only be True or False * @param boolean $debug Can only be True or False
* @param string|null $id If not set, will default to uniqid() call * @param string|null $id If not set, will default to uniqid() call
* @return void * @return void
*/ */
public static function setDebug(bool $debug, ?string $id = null): void public static function setDebug(bool $debug, ?string $id = null): void
{ {
self::$debug = $debug; self::$debug = $debug;
if (self::$debug === false) { if (self::$debug === false) {
return; return;
} }
self::setId($id); self::setId($id);
} }
/** /**
* returns current debug flag status * returns current debug flag status
* *
* @return boolean True if debug is on, False if debug is off * @return boolean True if debug is on, False if debug is off
*/ */
public static function getDebug(): bool public static function getDebug(): bool
{ {
return self::$debug; return self::$debug;
} }
/** /**
* get the current set ID, can return null if debug is off * get the current set ID, can return null if debug is off
* *
* @return string|null Current set ID for this log run * @return string|null Current set ID for this log run
*/ */
public static function getId(): ?string public static function getId(): ?string
{ {
return self::$id; return self::$id;
} }
/** /**
* write a log entry * write a log entry
* Data is as array key -> value * Data is as array key -> value
* Will be pushed as new array entry int log * Will be pushed as new array entry int log
* Main key is the set Id for this run * Main key is the set Id for this run
* *
* @param array<mixed> $data Any array data to store in the log * @param array<mixed> $data Any array data to store in the log
* @return void * @return void
*/ */
public static function writeLog(array $data): void public static function writeLog(array $data): void
{ {
if (self::$debug === false) { if (self::$debug === false) {
return; return;
} }
self::$log[self::getId() ?? ''][] = $data; self::$log[self::getId() ?? ''][] = $data;
} }
/** /**
* get all logs written since first class run * get all logs written since first class run
* or get all log entries for given ID * or get all log entries for given ID
* *
* @param string|null $id If set returns only this id logs * @param string|null $id If set returns only this id logs
* or empty array if not found * or empty array if not found
* @return array<mixed> Always array, empty if not data or not found * @return array<mixed> Always array, empty if not data or not found
*/ */
public static function getLog(?string $id = null): array public static function getLog(?string $id = null): array
{ {
if ($id === null) { if ($id === null) {
return self::$log; return self::$log;
} else { } else {
return self::$log[$id] ?? []; return self::$log[$id] ?? [];
} }
} }
} }
// __END__ // __END__

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Exceptions; namespace gullevek\AmazonIncentives\Exceptions;
use RuntimeException; use RuntimeException;
@@ -7,63 +9,63 @@ use gullevek\AmazonIncentives\Debug\AmazonDebug;
final class AmazonErrors extends RuntimeException final class AmazonErrors extends RuntimeException
{ {
/** /**
* Returns an Runtime exception including a json encoded string with all * Returns an Runtime exception including a json encoded string with all
* parameters including last log id and log * parameters including last log id and log
* *
* @param string $error_status agcodResponse->status from Amazon * @param string $error_status agcodResponse->status from Amazon
* @param string $error_code errorCode from Amazon * @param string $error_code errorCode from Amazon
* @param string $error_type errorType from Amazon * @param string $error_type errorType from Amazon
* @param string $message Message string to ad * @param string $message Message string to ad
* @param int $_error_code Error code to set * @param int $_error_code Error code to set
* @return AmazonErrors Exception Class * @return AmazonErrors Exception Class
*/ */
public static function getError( public static function getError(
string $error_status, string $error_status,
string $error_code, string $error_code,
string $error_type, string $error_type,
string $message, string $message,
int $_error_code int $_error_code
): self { ): self {
// NOTE: if xdebug.show_exception_trace is set to 1 this will print ERRORS // NOTE: if xdebug.show_exception_trace is set to 1 this will print ERRORS
return new static( return new static(
(json_encode([ (json_encode([
'status' => $error_status, 'status' => $error_status,
'code' => $error_code, 'code' => $error_code,
'type' => $error_type, 'type' => $error_type,
'message' => $message, 'message' => $message,
// atach log data if exists // attach log data if exists
'log_id' => AmazonDebug::getId(), 'log_id' => AmazonDebug::getId(),
'log' => AmazonDebug::getLog(), 'log' => AmazonDebug::getLog(),
])) ?: 'AmazonErrors: json encode problem: ' . $message, ])) ?: 'AmazonErrors: json encode problem: ' . $message,
$_error_code $_error_code
); );
} }
/** /**
* Decodes the Exception message body * Decodes the Exception message body
* Returns an array with code (Amazon error codes), type (Amazon error info) * Returns an array with code (Amazon error codes), type (Amazon error info)
* message (Amazon returned error message string) * message (Amazon returned error message string)
* *
* @param string $message Exception message json string * @param string $message Exception message json string
* @return array<mixed> Decoded with code, type, message fields * @return array<mixed> Decoded with code, type, message fields
*/ */
public static function decodeExceptionMessage(string $message): array public static function decodeExceptionMessage(string $message): array
{ {
$message_ar = json_decode($message, true); $message_ar = json_decode($message, true);
// if we have an error, build empty block and only fill message // if we have an error, build empty block and only fill message
if (json_last_error()) { if (json_last_error() || $message_ar === null || !is_array($message_ar)) {
$message_ar = [ $message_ar = [
'status' => '', 'status' => '',
'code' => '', 'code' => '',
'type' => '', 'type' => '',
'message' => $message, 'message' => $message,
'log_id' => '', 'log_id' => '',
'log' => [] 'log' => []
]; ];
} }
return $message_ar; return $message_ar;
} }
} }
// __END__ // __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 <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Response; namespace gullevek\AmazonIncentives\Response;
use gullevek\AmazonIncentives\Debug\AmazonDebug; use gullevek\AmazonIncentives\Debug\AmazonDebug;
class CancelResponse class CancelResponse
{ {
/** @var string Amazon Gift Card gcId (gift card id). */ /** @var string Amazon Gift Card gcId (gift card id). */
protected $id = ''; protected $id = '';
/** @var string Amazon Gift Card creationRequestId (creation request id) */ /** @var string Amazon Gift Card creationRequestId (creation request id) */
protected $creation_request_id = ''; protected $creation_request_id = '';
/** @var string Amazon Gift Card status */ /** @var string Amazon Gift Card status */
protected $status = ''; protected $status = '';
/** @var array<mixed> Amazon Gift Card Raw JSON */ /** @var array<mixed> Amazon Gift Card Raw JSON */
protected $raw_json = []; protected $raw_json = [];
/** /**
* Response constructor for canceling gitf cards * Response constructor for canceling gitf cards
* *
* @param array<mixed> $json_response JSON response from web request to AWS * @param array<mixed> $json_response JSON response from web request to AWS
*/ */
public function __construct(array $json_response) public function __construct(array $json_response)
{ {
$this->raw_json = $json_response; $this->raw_json = $json_response;
$this->parseJsonResponse($json_response); $this->parseJsonResponse($json_response);
} }
/** /**
* Get log entry with current set log id * Get log entry with current set log id
* *
* @return array<mixed> Log array * @return array<mixed> Log array
*/ */
public function getLog(): array public function getLog(): array
{ {
return AmazonDebug::getLog(AmazonDebug::getId()); return AmazonDebug::getLog(AmazonDebug::getId());
} }
/** /**
* The gift card id as created by the previous get code call * The gift card id as created by the previous get code call
* *
* @return string Gift card id * @return string Gift card id
*/ */
public function getId(): string public function getId(): string
{ {
return $this->id; return $this->id;
} }
/** /**
* Creation Request id from original get code call * Creation Request id from original get code call
* *
* @return string Creation request id * @return string Creation request id
*/ */
public function getCreationRequestId(): string public function getCreationRequestId(): string
{ {
return $this->creation_request_id; return $this->creation_request_id;
} }
/** /**
* Request status * Request status
* *
* @return string Request status as string: SUCCESS, FAILURE, RESEND * @return string Request status as string: SUCCESS, FAILURE, RESEND
*/ */
public function getStatus(): string public function getStatus(): string
{ {
return $this->status; return $this->status;
} }
/** /**
* Returns the request data as json string. This is a re-encode from decoded * Returns the request data as json string. This is a re-encode from decoded
* makeRequest call * makeRequest call
* *
* @return string JSON encoded string from the return values * @return string JSON encoded string from the return values
*/ */
public function getRawJson(): string public function getRawJson(): string
{ {
return (json_encode($this->raw_json)) ?: ''; return (json_encode($this->raw_json)) ?: '';
} }
/** /**
* Set class variables with response data from makeRequest and return self * Set class variables with response data from makeRequest and return self
* *
* @param array<mixed> $json_response JSON response as array * @param array<mixed> $json_response JSON response as array
* @return CancelResponse Return self object * @return CancelResponse Return self object
*/ */
public function parseJsonResponse(array $json_response): self public function parseJsonResponse(array $json_response): self
{ {
if (array_key_exists('gcId', $json_response)) { if (array_key_exists('gcId', $json_response)) {
$this->id = $json_response['gcId']; $this->id = $json_response['gcId'];
} }
if (array_key_exists('creationRequestId', $json_response)) { if (array_key_exists('creationRequestId', $json_response)) {
$this->creation_request_id = $json_response['creationRequestId']; $this->creation_request_id = $json_response['creationRequestId'];
} }
// SUCCESS, FAILURE, RESEND // SUCCESS, FAILURE, RESEND
if (array_key_exists('status', $json_response)) { if (array_key_exists('status', $json_response)) {
$this->status = $json_response['status']; $this->status = $json_response['status'];
} }
return $this; return $this;
} }
} }
// __END__ // __END__

View File

@@ -1,117 +1,127 @@
<?php <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Response; namespace gullevek\AmazonIncentives\Response;
use gullevek\AmazonIncentives\Debug\AmazonDebug; use gullevek\AmazonIncentives\Debug\AmazonDebug;
class CreateBalanceResponse class CreateBalanceResponse
{ {
/** @var string Amazon Gift Card Balance Amount */ /** @var float Amazon Gift Card Balance Amount */
protected $amount = ''; protected $amount = 0;
/** @var string Amazon Gift Card Balance Currency */ /** @var string Amazon Gift Card Balance Currency */
protected $currency = ''; protected $currency = '';
/** @var string Amazon Gift Card Balance Status */ /** @var string Amazon Gift Card Balance Status */
protected $status = ''; protected $status = '';
/** @var string Amazon Gift Card Balance Timestamp */ /** @var string Amazon Gift Card Balance Timestamp */
protected $timestamp = ''; protected $timestamp = '';
/** @var array<mixed> Amazon Gift Card Raw JSON */ /** @var array<mixed> Amazon Gift Card Raw JSON */
protected $raw_json = []; protected $raw_json = [];
/** /**
* Response constructor for requesting account funds status * Response constructor for requesting account funds status
* *
* @param array<mixed> $json_response JSON response from web request to AWS * @param array<mixed> $json_response JSON response from web request to AWS
*/ */
public function __construct(array $json_response) public function __construct(array $json_response)
{ {
$this->raw_json = $json_response; $this->raw_json = $json_response;
$this->parseJsonResponse($json_response); $this->parseJsonResponse($json_response);
} }
/** /**
* Get log entry with current set log id * Get log entry with current set log id
* *
* @return array<mixed> Log array * @return array<mixed> Log array
*/ */
public function getLog(): array public function getLog(): array
{ {
return AmazonDebug::getLog(AmazonDebug::getId()); return AmazonDebug::getLog(AmazonDebug::getId());
} }
/** /**
* Return the current available funds amount * Return the current available funds amount
* *
* @return string Funds amount in set currency * @return float Funds amount in set currency
*/ */
public function getAmount(): string public function getAmount(): float
{ {
return $this->amount; return $this->amount;
} }
/** /**
* Get the set currency type * Get the set currency type
* *
* @return string Currency type. Eg USD, JPY, etc * @return string Currency type. Eg USD, JPY, etc
*/ */
public function getCurrency(): string public function getCurrency(): string
{ {
return $this->currency; return $this->currency;
} }
/** /**
* Get timestamp as set. * Get timestamp as set.
* eg 20220609T061446Z * eg 20220609T061446Z
* *
* @return string Timestamp string. Ymd\THis\Z * @return string Timestamp string. Ymd\THis\Z
*/ */
public function getTimestamp(): string public function getTimestamp(): string
{ {
return $this->timestamp; return $this->timestamp;
} }
/** /**
* Request status * Request status
* *
* @return string Request status as string: SUCCESS, FAILURE, RESEND * @return string Request status as string: SUCCESS, FAILURE, RESEND
*/ */
public function getStatus(): string public function getStatus(): string
{ {
return $this->status; return $this->status;
} }
/** /**
* Returns the request data as json string. This is a re-encode from decoded * Returns the request data as json string. This is a re-encode from decoded
* makeRequest call * makeRequest call
* *
* @return string JSON encoded string from the return values * @return string JSON encoded string from the return values
*/ */
public function getRawJson(): string public function getRawJson(): string
{ {
return (json_encode($this->raw_json)) ?: ''; return (json_encode($this->raw_json)) ?: '';
} }
/** /**
* Set class variables with response data from makeRequest and return self * Set class variables with response data from makeRequest and return self
* *
* @param array<mixed> $json_response JSON response as array * @param array<mixed> $json_response JSON response as array
* @return CreateBalanceResponse Return self object * @return CreateBalanceResponse Return self object
*/ */
public function parseJsonResponse(array $json_response): self public function parseJsonResponse(array $json_response): self
{ {
if (array_key_exists('amount', $json_response['availableFunds'])) { if (
$this->amount = $json_response['availableFunds']['amount']; is_array($json_response['availableFunds']) &&
} array_key_exists('amount', $json_response['availableFunds']) &&
if (array_key_exists('currencyCode', $json_response['availableFunds'])) { is_numeric($json_response['availableFunds']['amount'])
$this->currency = $json_response['availableFunds']['currencyCode']; ) {
} $this->amount = (float)$json_response['availableFunds']['amount'];
// SUCCESS, FAILURE, RESEND }
if (array_key_exists('status', $json_response)) { if (
$this->status = $json_response['status']; is_array($json_response['availableFunds']) &&
} array_key_exists('currencyCode', $json_response['availableFunds']) &&
if (array_key_exists('timestamp', $json_response)) { is_string($json_response['availableFunds']['currencyCode'])
$this->timestamp = $json_response['timestamp']; ) {
} $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 <?php
declare(strict_types=1);
namespace gullevek\AmazonIncentives\Response; namespace gullevek\AmazonIncentives\Response;
use gullevek\AmazonIncentives\Debug\AmazonDebug; use gullevek\AmazonIncentives\Debug\AmazonDebug;
class CreateResponse class CreateResponse
{ {
/** @var string Amazon Gift Card gcId */ /** @var string Amazon Gift Card gcId */
protected $id = ''; protected $id = '';
/** @var string Amazon Gift Card creationRequestId */ /** @var string Amazon Gift Card creationRequestId */
protected $creation_request_id = ''; protected $creation_request_id = '';
/** @var string Amazon Gift Card gcClaimCode */ /** @var string Amazon Gift Card gcClaimCode */
protected $claim_code = ''; protected $claim_code = '';
/** @var float Amazon Gift Card amount */ /** @var float Amazon Gift Card amount */
protected $value = 0; protected $value = 0;
/** @var string Amazon Gift Card currency */ /** @var string Amazon Gift Card currency */
protected $currency = ''; protected $currency = '';
/** @var string Amazon Gift Card status */ /** @var string Amazon Gift Card status */
protected $status = ''; protected $status = '';
/** @var string Amazon Gift Card Expiration Date */ /** @var string Amazon Gift Card Expiration Date */
protected $expiration_date = ''; protected $expiration_date = '';
/** @var string Amazon Gift Card Expiration Date */ /** @var string Amazon Gift Card Expiration Date */
protected $card_status = ''; protected $card_status = '';
/** @var array<mixed> Amazon Gift Card Raw JSON as array */ /** @var array<mixed> Amazon Gift Card Raw JSON as array */
protected $raw_json = []; protected $raw_json = [];
/** /**
* Response constructor for creating gift cards * Response constructor for creating gift cards
* *
* @param array<mixed> $json_response JSON response from web request to AWS * @param array<mixed> $json_response JSON response from web request to AWS
*/ */
public function __construct(array $json_response) public function __construct(array $json_response)
{ {
$this->raw_json = $json_response; $this->raw_json = $json_response;
$this->parseJsonResponse($json_response); $this->parseJsonResponse($json_response);
} }
/** /**
* Get log entry with current set log id * Get log entry with current set log id
* *
* @return array<mixed> Log array * @return array<mixed> Log array
*/ */
public function getLog(): array public function getLog(): array
{ {
return AmazonDebug::getLog(AmazonDebug::getId()); return AmazonDebug::getLog(AmazonDebug::getId());
} }
/** /**
* Gift Card ID returned from AWS. Can be used in the cancel request * Gift Card ID returned from AWS. Can be used in the cancel request
* *
* @return string Gift card id * @return string Gift card id
*/ */
public function getId(): string public function getId(): string
{ {
return $this->id; return $this->id;
} }
/** /**
* Either the one set with the method parameter, or automatically created * Either the one set with the method parameter, or automatically created
* during get code request * during get code request
* *
* @return string Creation request id * @return string Creation request id
*/ */
public function getCreationRequestId(): string public function getCreationRequestId(): string
{ {
return $this->creation_request_id; return $this->creation_request_id;
} }
/** /**
* The actual gift code, recommended not to be stored anywhere and only shown * The actual gift code, recommended not to be stored anywhere and only shown
* to user * to user
* *
* @return string Gift order claim code on AWS * @return string Gift order claim code on AWS
*/ */
public function getClaimCode(): string public function getClaimCode(): string
{ {
return $this->claim_code; return $this->claim_code;
} }
/** /**
* The ordered gift code value in given currency * The ordered gift code value in given currency
* *
* @return float Gift order value in currency * @return float Gift order value in currency
*/ */
public function getValue(): float public function getValue(): float
{ {
return $this->value; return $this->value;
} }
/** /**
* The currently set currency * The currently set currency
* *
* @return string Currency type. Eg USD, JPY, etc * @return string Currency type. Eg USD, JPY, etc
*/ */
public function getCurrency(): string public function getCurrency(): string
{ {
return $this->currency; return $this->currency;
} }
/** /**
* Expiration date for the ordered gift code. * Expiration date for the ordered gift code.
* eg 20220609T061446Z * eg 20220609T061446Z
* *
* @return string Timestamp until when the gift code is valid. Ymd\THis\Z * @return string Timestamp until when the gift code is valid. Ymd\THis\Z
*/ */
public function getExpirationDate(): string public function getExpirationDate(): string
{ {
return $this->expiration_date; return $this->expiration_date;
} }
/** /**
* Gift card status. If the same creation request id is sent again and the * Gift card status. If the same creation request id is sent again and the
* gift card got cancled, this is reflected here * gift card got cancled, this is reflected here
* *
* @return string Gift card status * @return string Gift card status
*/ */
public function getCardStatus(): string public function getCardStatus(): string
{ {
return $this->card_status; return $this->card_status;
} }
/** /**
* Request status * Request status
* *
* @return string Request status as string: SUCCESS, FAILURE, RESEND * @return string Request status as string: SUCCESS, FAILURE, RESEND
*/ */
public function getStatus(): string public function getStatus(): string
{ {
return $this->status; return $this->status;
} }
/** /**
* @Returns the request data as json string. This is a re-encode from decoded * @Returns the request data as json string. This is a re-encode from decoded
* makeRequest call * makeRequest call
* *
* @return string JSON encoded string from the return values * @return string JSON encoded string from the return values
*/ */
public function getRawJson(): string public function getRawJson(): string
{ {
return (json_encode($this->raw_json)) ?: ''; return (json_encode($this->raw_json)) ?: '';
} }
/** /**
* Set class variables with response data from makeRequest and return self * Set class variables with response data from makeRequest and return self
* *
* @param array<mixed> $json_response JSON response as array * @param array<mixed> $json_response JSON response as array
* @return CreateResponse Return self object * @return CreateResponse Return self object
*/ */
public function parseJsonResponse(array $json_response): self public function parseJsonResponse(array $json_response): self
{ {
if (array_key_exists('gcId', $json_response)) { if (array_key_exists('gcId', $json_response)) {
$this->id = $json_response['gcId']; $this->id = $json_response['gcId'];
} }
if (array_key_exists('creationRequestId', $json_response)) { if (array_key_exists('creationRequestId', $json_response)) {
$this->creation_request_id = $json_response['creationRequestId']; $this->creation_request_id = $json_response['creationRequestId'];
} }
if (array_key_exists('gcClaimCode', $json_response)) { if (array_key_exists('gcClaimCode', $json_response)) {
$this->claim_code = $json_response['gcClaimCode']; $this->claim_code = $json_response['gcClaimCode'];
} }
if (array_key_exists('amount', $json_response['cardInfo']['value'])) { if (array_key_exists('amount', $json_response['cardInfo']['value'])) {
$this->value = $json_response['cardInfo']['value']['amount']; $this->value = $json_response['cardInfo']['value']['amount'];
} }
if (array_key_exists('currencyCode', $json_response['cardInfo']['value'])) { if (array_key_exists('currencyCode', $json_response['cardInfo']['value'])) {
$this->currency = $json_response['cardInfo']['value']['currencyCode']; $this->currency = $json_response['cardInfo']['value']['currencyCode'];
} }
if (array_key_exists('gcExpirationDate', $json_response)) { if (array_key_exists('gcExpirationDate', $json_response)) {
$this->expiration_date = $json_response['gcExpirationDate']; $this->expiration_date = $json_response['gcExpirationDate'];
} }
if (array_key_exists('cardStatus', $json_response['cardInfo'])) { if (array_key_exists('cardStatus', $json_response['cardInfo'])) {
$this->card_status = $json_response['cardInfo']['cardStatus']; $this->card_status = $json_response['cardInfo']['cardStatus'];
} }
// SUCCESS, FAILURE, RESEND // SUCCESS, FAILURE, RESEND
if (array_key_exists('status', $json_response)) { if (array_key_exists('status', $json_response)) {
$this->status = $json_response['status']; $this->status = $json_response['status'];
} }
return $this; return $this;
} }
} }
// __END__ // __END__

View File

@@ -11,10 +11,10 @@
*/ */
function writeLog(array $data): string function writeLog(array $data): string
{ {
return json_encode([ return json_encode([
'date' => date('Y-m-d H:i:s'), 'date' => date('Y-m-d H:i:s'),
'log' => $data 'log' => $data
]) . "\n"; ]) . "\n";
} }
/** /**
@@ -25,7 +25,7 @@ function writeLog(array $data): string
*/ */
function dateTr(string $date): 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 * @return void
*/ */
function printException( function printException(
string $call_request, string $call_request,
int $error_code, int $error_code,
array $error, array $error,
bool $debug_print bool $debug_print
): void { ): void {
print "AWS: " . $call_request . ": " . $error['status'] print "AWS: " . $call_request . ": " . $error['status']
. " [" . $error_code . "]: " . " [" . $error_code . "]: "
. $error['code'] . " | " . $error['type'] . $error['code'] . " | " . $error['type']
. " | " . $error['message']; . " | " . $error['message'];
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>"; print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
} }
} }
// composer auto loader // composer auto loader
@@ -95,234 +95,234 @@ $mock_debug = !empty($_GET['debug_mock']) ? true : false;
$mock_wait = 2; $mock_wait = 2;
if (empty($_GET)) { 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 // open debug file output
$fp = fopen('log/debug.' . date('YmdHis') . '.log', 'w'); $fp = fopen('log/debug.' . date('YmdHis') . '.log', 'w');
if (!is_resource($fp)) { if (!is_resource($fp)) {
die("Cannot open log debug file"); die("Cannot open log debug file");
} }
if ($run_info_test === true) { if ($run_info_test === true) {
$aws = new AmazonIncentives(); $aws = new AmazonIncentives();
$aws_check_me = $aws->checkMe(); $aws_check_me = $aws->checkMe();
print "checkMe: <pre>" . print_r($aws_check_me, true) . "</pre>"; print "checkMe: <pre>" . print_r($aws_check_me, true) . "</pre>";
fwrite($fp, writeLog($aws_check_me)); fwrite($fp, writeLog($aws_check_me));
print "<hr>"; print "<hr>";
} }
// check balance // check balance
if ($run_fund_test === true) { if ($run_fund_test === true) {
try { try {
$aws_test = AmazonIncentives::make()->getAvailableFunds(); $aws_test = AmazonIncentives::make()->getAvailableFunds();
print "AWS: getAvailableFunds: " . $aws_test->getStatus() . ": " print "AWS: getAvailableFunds: " . $aws_test->getStatus() . ": "
. "Amount: " . $aws_test->getAmount() . ", " . "Amount: " . $aws_test->getAmount() . ", "
. "Currency: " . $aws_test->getCurrency() . ", " . "Currency: " . $aws_test->getCurrency() . ", "
. "Timestamp: " . $aws_test->getTimestamp(); . "Timestamp: " . $aws_test->getTimestamp();
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (Exception $e) { } catch (Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
printException('getAvailableFunds', $e->getCode(), $error, $debug_print); printException('getAvailableFunds', $e->getCode(), $error, $debug_print);
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
}; };
print "<br>"; print "<br>";
sleep($debug_wait); sleep($debug_wait);
// print "LOG: <pre>" . print_r($aws_test->getLog(), true) . "</pre><br>"; // print "LOG: <pre>" . print_r($aws_test->getLog(), true) . "</pre><br>";
print "<hr>"; print "<hr>";
} }
if ($run_gift_tests === true) { if ($run_gift_tests === true) {
// create card // create card
$value = 1000; $value = 1000;
$creation_request_id = ''; $creation_request_id = '';
$gift_card_id = ''; $gift_card_id = '';
try { try {
// we must be sure we pass FLOAT there // we must be sure we pass FLOAT there
$aws_test = AmazonIncentives::make()->buyGiftCard((float)$value); $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value);
$creation_request_id = $aws_test->getCreationRequestId(); $creation_request_id = $aws_test->getCreationRequestId();
$gift_card_id = $aws_test->getId(); $gift_card_id = $aws_test->getId();
$claim_code = $aws_test->getClaimCode(); $claim_code = $aws_test->getClaimCode();
$expiration_date = $aws_test->getExpirationDate(); $expiration_date = $aws_test->getExpirationDate();
$request_status = $aws_test->getStatus(); $request_status = $aws_test->getStatus();
print "AWS: buyGiftCard: " . $request_status . ": " print "AWS: buyGiftCard: " . $request_status . ": "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, " . "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>"; . "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (\Exception $e) { } catch (\Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
printException('buyGiftCard', $e->getCode(), $error, $debug_print); printException('buyGiftCard', $e->getCode(), $error, $debug_print);
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
} }
print "<br>"; print "<br>";
sleep($debug_wait); sleep($debug_wait);
try { try {
// cancel above created card card // cancel above created card card
$aws_test = AmazonIncentives::make()->cancelGiftCard($creation_request_id, $gift_card_id); $aws_test = AmazonIncentives::make()->cancelGiftCard($creation_request_id, $gift_card_id);
$request_status = $aws_test->getStatus(); $request_status = $aws_test->getStatus();
print "AWS: cancelGiftCard: " . $request_status . ": " print "AWS: cancelGiftCard: " . $request_status . ": "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id; . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id;
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (\Exception $e) { } catch (\Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
print "AWS: cancelGiftCard: " . $error['status'] print "AWS: cancelGiftCard: " . $error['status']
. " [" . $e->getCode() . "]: " . " [" . $e->getCode() . "]: "
. $error['code'] . " | " . $error['type'] . $error['code'] . " | " . $error['type']
. " | " . $error['message']; . " | " . $error['message'];
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>"; print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
} }
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
} }
print "<br>"; print "<br>";
sleep($debug_wait); sleep($debug_wait);
// request same card again and get error // request same card again and get error
try { try {
$aws_test = AmazonIncentives::make()->buyGiftCard((float)$value, $creation_request_id); $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value, $creation_request_id);
$request_status = $aws_test->getStatus(); $request_status = $aws_test->getStatus();
// same? // same?
$claim_code = $aws_test->getClaimCode(); $claim_code = $aws_test->getClaimCode();
$expiration_date = $aws_test->getExpirationDate(); $expiration_date = $aws_test->getExpirationDate();
print "AWS: buyGiftCard: CANCLED SAME CODE AGAIN: " . $request_status . ": " print "AWS: buyGiftCard: CANCLED SAME CODE AGAIN: " . $request_status . ": "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, " . "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>"; . "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (\Exception $e) { } catch (\Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
printException('buyGiftCard', $e->getCode(), $error, $debug_print); printException('buyGiftCard', $e->getCode(), $error, $debug_print);
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
} }
print "<br>"; print "<br>";
sleep($debug_wait); sleep($debug_wait);
// set same request ID twice to get same response test // set same request ID twice to get same response test
try { try {
$aws_test = AmazonIncentives::make()->buyGiftCard((float)$value); $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value);
$creation_request_id = $aws_test->getCreationRequestId(); $creation_request_id = $aws_test->getCreationRequestId();
$gift_card_id = $aws_test->getId(); $gift_card_id = $aws_test->getId();
$claim_code = $aws_test->getClaimCode(); $claim_code = $aws_test->getClaimCode();
$expiration_date = $aws_test->getExpirationDate(); $expiration_date = $aws_test->getExpirationDate();
$request_status = $aws_test->getStatus(); $request_status = $aws_test->getStatus();
print "AWS: buyGiftCard: CODE A: " . $request_status . ": " print "AWS: buyGiftCard: CODE A: " . $request_status . ": "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, " . "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>"; . "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (\Exception $e) { } catch (\Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
printException('cancelGiftCard', $e->getCode(), $error, $debug_print); printException('cancelGiftCard', $e->getCode(), $error, $debug_print);
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
} }
print "<br>"; print "<br>";
sleep($debug_wait); sleep($debug_wait);
try { try {
$aws_test = AmazonIncentives::make()->buyGiftCard((float)$value, $creation_request_id); $aws_test = AmazonIncentives::make()->buyGiftCard((float)$value, $creation_request_id);
$request_status = $aws_test->getStatus(); $request_status = $aws_test->getStatus();
// same? // same?
$claim_code = $aws_test->getClaimCode(); $claim_code = $aws_test->getClaimCode();
$expiration_date = $aws_test->getExpirationDate(); $expiration_date = $aws_test->getExpirationDate();
print "AWS: buyGiftCard: SAME CODE A AGAIN: " . $request_status . ": " print "AWS: buyGiftCard: SAME CODE A AGAIN: " . $request_status . ": "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, " . "EXPIRE DATE: <b>" . dateTr($expiration_date) . "</b>, "
. "CLAIM CODE: <b>" . $claim_code . "</b>"; . "CLAIM CODE: <b>" . $claim_code . "</b>";
if ($debug_print === true) { if ($debug_print === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (\Exception $e) { } catch (\Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
printException('buyGiftCard', $e->getCode(), $error, $debug_print); printException('buyGiftCard', $e->getCode(), $error, $debug_print);
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
} }
print "<br>"; print "<br>";
print "<hr>"; print "<hr>";
sleep($debug_wait); sleep($debug_wait);
} }
// MOCK TEST // MOCK TEST
if ($run_mocks === true) { if ($run_mocks === true) {
$mock_ok = '<span style="color:green;">MOCK OK</span>'; $mock_ok = '<span style="color:green;">MOCK OK</span>';
$mock_failure = '<span style="color:red;">MOCK FAILURE</span>'; $mock_failure = '<span style="color:red;">MOCK FAILURE</span>';
$mock_value = 500; $mock_value = 500;
$mock = []; $mock = [];
$mock['F0000'] = [ 'ret' => '', 'st' => 'SUCCESS']; // success mock $mock['F0000'] = [ 'ret' => '', 'st' => 'SUCCESS']; // success mock
$mock['F1000'] = [ 'ret' => 'F100', 'st' => 'FAILURE']; // SimpleAmountIsNull, etc $mock['F1000'] = [ 'ret' => 'F100', 'st' => 'FAILURE']; // SimpleAmountIsNull, etc
$mock['F2003'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountInput $mock['F2003'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountInput
$mock['F2004'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountValue $mock['F2004'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidAmountValue
$mock['F2005'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidCurrencyCodeInput $mock['F2005'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // InvalidCurrencyCodeInput
$mock['F2010'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CardActivatedWithDifferentRequestId $mock['F2010'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CardActivatedWithDifferentRequestId
$mock['F2015'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // MaxAmountExceeded $mock['F2015'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // MaxAmountExceeded
$mock['F2016'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CurrencyCodeMismatch $mock['F2016'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CurrencyCodeMismatch
$mock['F2017'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // FractionalAmountNotAllowed $mock['F2017'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // FractionalAmountNotAllowed
$mock['F2047'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CancelRequestArrivedAfterTimeLimit $mock['F2047'] = [ 'ret' => 'F200', 'st' => 'FAILURE']; // CancelRequestArrivedAfterTimeLimit
$mock['F3003'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // InsufficientFunds $mock['F3003'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // InsufficientFunds
$mock['F3005'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // AccountHasProblems $mock['F3005'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // AccountHasProblems
$mock['F3010'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // CustomerSurpassedDailyVelocityLimit $mock['F3010'] = [ 'ret' => 'F300', 'st' => 'FAILURE']; // CustomerSurpassedDailyVelocityLimit
$mock['F4000'] = [ 'ret' => 'F400', 'st' => 'RESEND']; // SystemTemporarilyUnavailable $mock['F4000'] = [ 'ret' => 'F400', 'st' => 'RESEND']; // SystemTemporarilyUnavailable
$mock['F5000'] = [ 'ret' => 'F500', 'st' => 'FAILURE']; // UnknownError $mock['F5000'] = [ 'ret' => 'F500', 'st' => 'FAILURE']; // UnknownError
foreach ($mock as $creation_id => $mock_return) { foreach ($mock as $creation_id => $mock_return) {
print "<b>TS: " . microtime() . "</b>: "; print "<b>TS: " . microtime() . "</b>: ";
try { try {
$aws_test = AmazonIncentives::make()->buyGiftCard((float)$mock_value, $creation_id); $aws_test = AmazonIncentives::make()->buyGiftCard((float)$mock_value, $creation_id);
$creation_request_id = $aws_test->getCreationRequestId(); $creation_request_id = $aws_test->getCreationRequestId();
$gift_card_id = $aws_test->getId(); $gift_card_id = $aws_test->getId();
$claim_code = $aws_test->getClaimCode(); $claim_code = $aws_test->getClaimCode();
$request_status = $aws_test->getStatus(); $request_status = $aws_test->getStatus();
print "AWS: MOCK: " . $creation_id . ": buyGiftCard: <b>" . $request_status . "</b>: " print "AWS: MOCK: " . $creation_id . ": buyGiftCard: <b>" . $request_status . "</b>: "
. "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", " . "creationRequestId: " . $creation_request_id . ", gcId: " . $gift_card_id . ", "
. "CLAIM CODE: <b>" . $claim_code . "</b>: "; . "CLAIM CODE: <b>" . $claim_code . "</b>: ";
if ($mock_return['st'] == $request_status) { if ($mock_return['st'] == $request_status) {
print $mock_ok; print $mock_ok;
} else { } else {
print $mock_failure; print $mock_failure;
} }
if ($mock_debug === true) { if ($mock_debug === true) {
print "<pre>" . print_r($aws_test, true) . "</pre>"; print "<pre>" . print_r($aws_test, true) . "</pre>";
} }
fwrite($fp, writeLog((array)$aws_test)); fwrite($fp, writeLog((array)$aws_test));
} catch (Exception $e) { } catch (Exception $e) {
$error = AmazonErrors::decodeExceptionMessage($e->getMessage()); $error = AmazonErrors::decodeExceptionMessage($e->getMessage());
print "AWS: MOCK: " . $creation_id . ": buyGiftCard: " . $error['status'] print "AWS: MOCK: " . $creation_id . ": buyGiftCard: " . $error['status']
. " [" . $e->getCode() . "]: " . " [" . $e->getCode() . "]: "
. $error['code'] . " | " . $error['type'] . $error['code'] . " | " . $error['type']
. " | " . $error['message'] . ": "; . " | " . $error['message'] . ": ";
if ( if (
$mock_return['ret'] == $error['code'] && $mock_return['ret'] == $error['code'] &&
$mock_return['st'] == $error['status'] $mock_return['st'] == $error['status']
) { ) {
print $mock_ok; print $mock_ok;
} else { } else {
print $mock_failure; print $mock_failure;
} }
if ($mock_debug === true) { if ($mock_debug === true) {
print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>"; print "<pre>" . print_r($error['log'][$error['log_id'] ?? ''] ?? [], true) . "</pre>";
} }
fwrite($fp, writeLog($error)); fwrite($fp, writeLog($error));
} }
print "<br>"; print "<br>";
// Waiting a moment, so we don't flood // Waiting a moment, so we don't flood
sleep($mock_wait); sleep($mock_wait);
} }
print "<hr>"; print "<hr>";
} }
fclose($fp); 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