Add PHPstan and fix all checks for max level

This commit is contained in:
2021-10-21 13:29:50 +09:00
parent 18cf3330df
commit c2721cb8d4
13 changed files with 140 additions and 116 deletions

View File

@@ -99,16 +99,31 @@ to extract the below array from the thrown exception
`status`, `code` and `type` must be checked on a failure. `status`, `code` and `type` must be checked on a failure.
**NOTE**: if code is T001 then this is a request flood error: ## Other Errors from exceptions
### T001
if code is T001 then this is a request flood error:
In this case the request has to be resend after a certain waiting period. In this case the request has to be resend after a certain waiting period.
**NOTE**: if code is E999 some other critical error has happened ### E9999
**NOTE**: if code is E001 if the return create/cancel/check calls is not an array if code is E999 some other critical error has happened
**NOTE**: if code is C001 a curl error has happened ### E001
**NOTE**: any other NON amazon error will have only 'message' set if run through decode if code is E001 if the return create/cancel/check calls is not an array
### C001
fif code is C001 curl failed to init
### C002
if code is C002 a curl error has happened
### empty error code
any other NON amazon error will have only 'message' set if run through decode
## Debugging ## Debugging

22
phpstan.neon Normal file
View File

@@ -0,0 +1,22 @@
# PHP Stan Config
parameters:
tmpDir: /tmp/phpstan-codeblocks-amazon-incentives
level: max
paths:
- %currentWorkingDirectory%
excludes_analyse:
# ignore composer
- vendor
# ignore errores with
ignoreErrors:
-
message: '#Strict comparison using === between false and true will always evaluate to false.#'
path: %currentWorkingDirectory%/test/aws_gift_card_tests.php
#- 'error regex'
#-
# message: 'error regex'
# path: %currentWorkingDirectory%/www/some/*
# paths:
# - ...
# - ...

View File

@@ -26,6 +26,9 @@ class AWS
public const CANCEL_GIFT_CARD_SERVICE = 'CancelGiftCard'; public const CANCEL_GIFT_CARD_SERVICE = 'CancelGiftCard';
public const GET_AVAILABLE_FUNDS_SERVICE = 'GetAvailableFunds'; public const GET_AVAILABLE_FUNDS_SERVICE = 'GetAvailableFunds';
/**
* @var Config
*/
private $config; private $config;
/** /**
@@ -162,7 +165,7 @@ class AWS
* @param string $authorization_value * @param string $authorization_value
* @param string $date_time_string * @param string $date_time_string
* @param string $service_target * @param string $service_target
* @return array * @return array<mixed>
*/ */
public function buildHeaders( public function buildHeaders(
string $payload, string $payload,
@@ -323,7 +326,6 @@ class AWS
*/ */
public function getGiftCardPayload(float $amount, ?string $creation_id = null): string public function getGiftCardPayload(float $amount, ?string $creation_id = null): string
{ {
$amount = trim($amount);
$payload = [ $payload = [
'creationRequestId' => $creation_id ?: uniqid($this->config->getPartner() . '_'), 'creationRequestId' => $creation_id ?: uniqid($this->config->getPartner() . '_'),
'partnerId' => $this->config->getPartner(), 'partnerId' => $this->config->getPartner(),
@@ -333,7 +335,7 @@ class AWS
'amount' => (float)$amount 'amount' => (float)$amount
] ]
]; ];
return json_encode($payload); return (json_encode($payload)) ?: '';
} }
/** /**
@@ -343,13 +345,12 @@ class AWS
*/ */
public function getCancelGiftCardPayload(string $creation_request_id, string $gift_card_id): string public function getCancelGiftCardPayload(string $creation_request_id, string $gift_card_id): string
{ {
$gift_card_response_id = trim($gift_card_id);
$payload = [ $payload = [
'creationRequestId' => $creation_request_id, 'creationRequestId' => $creation_request_id,
'partnerId' => $this->config->getPartner(), 'partnerId' => $this->config->getPartner(),
'gcId' => $gift_card_response_id 'gcId' => $gift_card_id
]; ];
return json_encode($payload); return (json_encode($payload)) ?: '';
} }
/** /**
@@ -360,7 +361,7 @@ class AWS
$payload = [ $payload = [
'partnerId' => $this->config->getPartner(), 'partnerId' => $this->config->getPartner(),
]; ];
return json_encode($payload); return (json_encode($payload)) ?: '';
} }
/** /**
@@ -394,7 +395,7 @@ class AWS
} }
/** /**
* @return false|string * @return string
*/ */
public function getTimestamp() public function getTimestamp()
{ {
@@ -413,7 +414,7 @@ class AWS
} }
/** /**
* @return bool|string * @return string
*/ */
public function getDateString() public function getDateString()
{ {

View File

@@ -2,36 +2,7 @@
/* /*
* Amazon Incentive Code * Amazon Incentive Code
* * Amazon Gift Code on Demand
* # settings:
* aws endpoint (also sets region)
* aws key
* aws secret
* aws partner id
* money type (set as default, override in call)
* money value (set as default, override in call)
*
* # checks
* endpoint + region must match
*
* # calls:
* create gift card: CreateGiftCard
* cancel gift card: CancelGiftCard
*
* activate gift card: ActivateGiftCard
* deactivate gift card: DeactivateGiftCard
*
* gift card status: ActivationStatusCheck
*
* check available funds: GetAvailablefunds
*
* api server health check
*
* # sub classes
* config reader/checker
* API v4 encrypter
* submitter/data getter
* error handler/retry
*/ */
namespace gullevek\AmazonIncentives; namespace gullevek\AmazonIncentives;
@@ -41,8 +12,11 @@ use gullevek\AmazonIncentives\Config\Config;
use gullevek\AmazonIncentives\Exceptions\AmazonErrors; use gullevek\AmazonIncentives\Exceptions\AmazonErrors;
use gullevek\AmazonIncentives\Debug\AmazonDebug; use gullevek\AmazonIncentives\Debug\AmazonDebug;
class AmazonIncentives final class AmazonIncentives
{ {
/**
* @var Config
*/
private $config; private $config;
/** /**
@@ -112,7 +86,7 @@ class AmazonIncentives
} }
/** /**
* AmazonGiftCode make own client. * AmazonIncentives make own client.
* *
* @param string|null $key * @param string|null $key
* @param string|null $secret * @param string|null $secret
@@ -120,7 +94,7 @@ class AmazonIncentives
* @param string|null $endpoint * @param string|null $endpoint
* @param string|null $currency * @param string|null $currency
* @param bool|null $debug * @param bool|null $debug
* @return AmazonGiftCode * @return AmazonIncentives
*/ */
public static function make( public static function make(
string $key = null, string $key = null,
@@ -139,7 +113,7 @@ class AmazonIncentives
* 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 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
{ {
@@ -162,6 +136,9 @@ class AmazonIncentives
// PUBLIC TEST METHODS // PUBLIC TEST METHODS
// ********************************************************************* // *********************************************************************
/**
* @return array<mixed>
*/
public function checkMe(): array public function checkMe(): array
{ {
$data = []; $data = [];

View File

@@ -13,15 +13,25 @@ class Client implements ClientInterface
/** /**
* *
* @param string $url The URL being requested, including domain and protocol * @param string $url The URL being requested, including domain and protocol
* @param array $headers Headers to be used in the request * @param array<mixed> $headers Headers to be used in the request
* @param array|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
{ {
$handle = curl_init($url); $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_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);
@@ -39,7 +49,7 @@ class Client implements ClientInterface
$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($result, true); $result_ar = json_decode((string)$result, true);
// if message is 'Rate exceeded', set different error // if message is 'Rate exceeded', set different error
if (($result_ar['message'] ?? '') == 'Rate exceeded') { if (($result_ar['message'] ?? '') == 'Rate exceeded') {
$error_status = 'RESEND'; $error_status = 'RESEND';
@@ -62,14 +72,14 @@ class Client implements ClientInterface
$err $err
); );
} }
return $result; return (string)$result;
} }
/** /**
* Undocumented function * Undocumented function
* *
* @param string $url * @param string $url
* @param string $errno * @param int $errno
* @param string $message * @param string $message
* @return void * @return void
*/ */
@@ -97,7 +107,7 @@ class Client implements ClientInterface
// 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',
'C001', 'C002',
'CurlError', 'CurlError',
$message, $message,
$errno $errno

View File

@@ -5,9 +5,10 @@ namespace gullevek\AmazonIncentives\Client;
interface ClientInterface interface ClientInterface
{ {
/** /**
* @param string $url The URL being requested, including domain and protocol * @param string $url The URL being requested,
* @param array $headers Headers to be used in the request * including domain and protocol
* @param array|string $params Can be nested for arrays and hashes * @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 * @return String
*/ */

View File

@@ -44,12 +44,12 @@ class Config implements ConfigInterface
?string $currency, ?string $currency,
?bool $debug, ?bool $debug,
) { ) {
$this->setAccessKey($key ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); $this->setAccessKey(($key) ?: $this->parseEnv('AWS_GIFT_CARD_KEY')); /** @phpstan-ignore-line */
$this->setSecret($secret ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); $this->setSecret(($secret) ?: $this->parseEnv('AWS_GIFT_CARD_SECRET')); /** @phpstan-ignore-line */
$this->setPartner($partner ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); $this->setPartner(($partner) ?: $this->parseEnv('AWS_GIFT_CARD_PARTNER_ID')); /** @phpstan-ignore-line */
$this->setEndpoint($endpoint ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); $this->setEndpoint(($endpoint) ?: $this->parseEnv('AWS_GIFT_CARD_ENDPOINT')); /** @phpstan-ignore-line */
$this->setCurrency($currency ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); $this->setCurrency(($currency) ?: $this->parseEnv('AWS_GIFT_CARD_CURRENCY')); /** @phpstan-ignore-line */
$this->setDebug($debug ?: $this->parseEnv('AWS_DEBUG')); $this->setDebug(($debug) ?: $this->parseEnv('AWS_DEBUG')); /** @phpstan-ignore-line */
} }
/** /**
@@ -94,7 +94,7 @@ class Config implements ConfigInterface
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;
} }
@@ -177,9 +177,9 @@ class Config implements ConfigInterface
} }
/** /**
* @return bool|null * @return bool
*/ */
public function getDebug(): ?bool public function getDebug(): bool
{ {
return $this->debug; return $this->debug;
} }

View File

@@ -7,8 +7,17 @@ namespace gullevek\AmazonIncentives\Debug;
class AmazonDebug class AmazonDebug
{ {
/**
* @var array<mixed>
*/
private static $log = []; private static $log = [];
/**
* @var bool
*/
private static $debug = false; private static $debug = false;
/**
* @var string|null;
*/
private static $id = null; private static $id = null;
/** /**
@@ -74,7 +83,7 @@ class AmazonDebug
* 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 $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
@@ -91,7 +100,7 @@ class AmazonDebug
* *
* @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 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
{ {

View File

@@ -5,14 +5,14 @@ namespace gullevek\AmazonIncentives\Exceptions;
use RuntimeException; use RuntimeException;
use gullevek\AmazonIncentives\Debug\AmazonDebug; use gullevek\AmazonIncentives\Debug\AmazonDebug;
class AmazonErrors extends RuntimeException final class AmazonErrors extends RuntimeException
{ {
/** /**
* @param string $error_status agcodResponse->status from Amazon * @param string $error_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 * @param string $message
* @param string $_error_code * @param int $_error_code
* @return AmazonErrors * @return AmazonErrors
*/ */
public static function getError( public static function getError(
@@ -20,11 +20,11 @@ class AmazonErrors extends RuntimeException
string $error_code, string $error_code,
string $error_type, string $error_type,
string $message, string $message,
string $_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,
@@ -32,7 +32,7 @@ class AmazonErrors extends RuntimeException
// atach log data if exists // atach log data if exists
'log_id' => AmazonDebug::getId(), 'log_id' => AmazonDebug::getId(),
'log' => AmazonDebug::getLog(), 'log' => AmazonDebug::getLog(),
]), ])) ?: 'AmazonErrors: json encode problem: ' . $message,
$_error_code $_error_code
); );
} }

View File

@@ -28,31 +28,26 @@ class CancelResponse
/** /**
* Amazon Gift Card Raw JSON * Amazon Gift Card Raw JSON
* *
* @var string * @var array<mixed>
*/ */
protected $raw_json; protected $raw_json;
/**
* @var array
*/
protected $log;
/** /**
* Response constructor. * Response constructor.
* @param array $json_response * @param array<mixed> $json_response
*/ */
public function __construct(array $json_response) public function __construct(array $json_response)
{ {
$this->raw_json = $json_response; $this->raw_json = $json_response;
$this->log = AmazonDebug::getLog(AmazonDebug::getId());
$this->parseJsonResponse($json_response); $this->parseJsonResponse($json_response);
} }
/** /**
* @return array * @return array<mixed>
*/ */
public function getLog(): array public function getLog(): array
{ {
return $this->log; return AmazonDebug::getLog(AmazonDebug::getId());
} }
/** /**
@@ -84,11 +79,11 @@ class CancelResponse
*/ */
public function getRawJson(): string public function getRawJson(): string
{ {
return json_encode($this->raw_json); return (json_encode($this->raw_json)) ?: '';
} }
/** /**
* @param array $json_response * @param array<mixed> $json_response
* @return CancelResponse * @return CancelResponse
*/ */
public function parseJsonResponse(array $json_response): self public function parseJsonResponse(array $json_response): self

View File

@@ -34,32 +34,27 @@ class CreateBalanceResponse
/** /**
* Amazon Gift Card Raw JSON * Amazon Gift Card Raw JSON
* *
* @var string * @var array<mixed>
*/ */
protected $raw_json; protected $raw_json;
/**
* @var array
*/
protected $log;
/** /**
* Response constructor. * Response constructor.
* *
* @param array $json_response * @param array<mixed> $json_response
*/ */
public function __construct(array $json_response) public function __construct(array $json_response)
{ {
$this->raw_json = $json_response; $this->raw_json = $json_response;
$this->log = AmazonDebug::getLog(AmazonDebug::getId());
$this->parseJsonResponse($json_response); $this->parseJsonResponse($json_response);
} }
/** /**
* @return array * @return array<mixed>
*/ */
public function getLog(): array public function getLog(): array
{ {
return $this->log; return AmazonDebug::getLog(AmazonDebug::getId());
} }
/** /**
@@ -99,13 +94,13 @@ class CreateBalanceResponse
*/ */
public function getRawJson(): string public function getRawJson(): string
{ {
return json_encode($this->raw_json); return (json_encode($this->raw_json)) ?: '';
} }
/** /**
* Undocumented function * Undocumented function
* *
* @param array $json_response * @param array<mixed> $json_response
* @return CreateBalanceResponse * @return CreateBalanceResponse
*/ */
public function parseJsonResponse(array $json_response): self public function parseJsonResponse(array $json_response): self

View File

@@ -62,31 +62,26 @@ class CreateResponse
/** /**
* Amazon Gift Card Raw JSON * Amazon Gift Card Raw JSON
* *
* @var string * @var array<mixed>
*/ */
protected $raw_json; protected $raw_json;
/**
* @var array
*/
protected $log;
/** /**
* Response constructor. * Response constructor.
* @param array $json_response * @param array<mixed> $json_response
*/ */
public function __construct(array $json_response) public function __construct(array $json_response)
{ {
$this->raw_json = $json_response; $this->raw_json = $json_response;
$this->log = AmazonDebug::getLog(AmazonDebug::getId());
$this->parseJsonResponse($json_response); $this->parseJsonResponse($json_response);
} }
/** /**
* @return array * @return array<mixed>
*/ */
public function getLog(): array public function getLog(): array
{ {
return $this->log; return AmazonDebug::getLog(AmazonDebug::getId());
} }
/** /**
@@ -114,9 +109,9 @@ class CreateResponse
} }
/** /**
* @return string * @return float
*/ */
public function getValue(): string public function getValue(): float
{ {
return $this->value; return $this->value;
} }
@@ -159,11 +154,11 @@ class CreateResponse
*/ */
public function getRawJson(): string public function getRawJson(): string
{ {
return json_encode($this->raw_json); return (json_encode($this->raw_json)) ?: '';
} }
/** /**
* @param array $json_response * @param array<mixed> $json_response
* @return CreateResponse * @return CreateResponse
*/ */
public function parseJsonResponse(array $json_response): self public function parseJsonResponse(array $json_response): self

View File

@@ -6,7 +6,7 @@
* write log as string from array data * write log as string from array data
* includes timestamp * includes timestamp
* *
* @param array $data Debug log array data to add to the json string * @param array<mixed> $data Debug log array data to add to the json string
* @return string * @return string
*/ */
function writeLog(array $data): string function writeLog(array $data): string
@@ -25,16 +25,16 @@ 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)); return date('Y-m-d H:i:s', (strtotime($date)) ?: null);
} }
/** /**
* print exception string * print exception string
* *
* @param string $call_request Call request, eg buyGiftCard * @param string $call_request Call request, eg buyGiftCard
* @param integer $error_code $e Exception error code * @param integer $error_code $e Exception error code
* @param array $error Array from the Exception message json string * @param array<mixed> $error Array from the Exception message json string
* @param boolean $debug_print If we should show the debug log * @param boolean $debug_print If we should show the debug log
* @return void * @return void
*/ */
function printException( function printException(
@@ -93,6 +93,9 @@ foreach (
// 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)) {
die("Cannot open log debug file");
}
// run info test (prints ENV vars) // run info test (prints ENV vars)
$run_info_test = false; $run_info_test = false;
@@ -221,6 +224,7 @@ if ($run_gift_tests === true) {
$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();
$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 . ", "
@@ -241,7 +245,7 @@ if ($run_gift_tests === true) {
} }
// MOCK TEST // MOCK TEST
if ($mock_debug === 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;