Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ composer.lock
composer.phar
vendor
reports
coverage.xml
coverage
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
"phpunit/phpunit": "^8.5 || ^9.5",
"friendsofphp/php-cs-fixer": "^2.19.3 || ^3.9.5",
"phpstan/phpstan": "1.11.0",
"vlucas/phpdotenv": "5.5.0"
"vlucas/phpdotenv": "5.5.0",
"brain/monkey": "2.6.2"
},
"autoload": {
"classmap": ["lib/omise/"]
Expand All @@ -44,7 +45,8 @@
},
"scripts": {
"test:unit": "TEST_TYPE=unit ./vendor/bin/phpunit --testdox",
"test:coverage": "XDEBUG_MODE=coverage TEST_TYPE=unit ./vendor/bin/phpunit --coverage-clover=coverage.xml",
"test:coverage:html": "XDEBUG_MODE=coverage TEST_TYPE=unit ./vendor/bin/phpunit --coverage-html=coverage",
"test:coverage:xml": "XDEBUG_MODE=coverage TEST_TYPE=unit ./vendor/bin/phpunit --coverage-clover=coverage/coverage.xml",
"fix": "vendor/bin/php-cs-fixer fix -vvv --diff --dry-run --allow-risky=yes --using-cache=no",
"analyse": "vendor/bin/phpstan analyse lib tests",
"phpstan": "vendor/bin/phpstan analyse lib tests"
Expand Down
2 changes: 2 additions & 0 deletions lib/Omise.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Cores and utilities.
require_once __DIR__ . '/omise/res/obj/OmiseObject.php';
require_once __DIR__ . '/omise/res/OmiseApiResource.php';
require_once __DIR__ . '/omise/http/OmiseHttpExecutorInterface.php';
require_once __DIR__ . '/omise/http/OmiseHttpExecutor.php';

// Errors
require_once __DIR__ . '/omise/exception/OmiseExceptions.php';
Expand Down
87 changes: 87 additions & 0 deletions lib/omise/http/OmiseHttpExecutor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

class OmiseHttpExecutor implements OmiseHttpExecutorInterface
{
private $OMISE_CONNECTTIMEOUT = 30;
private $OMISE_TIMEOUT = 60;

public function execute($url, $requestMethod, $key, $params = null)
{
$ch = curl_init($url);

curl_setopt_array($ch, $this->genOptions($requestMethod, $key . ':', $params));

// Make a request or thrown an exception.
if (($result = curl_exec($ch)) === false) {
$error = curl_error($ch);
curl_close($ch);

throw new Exception($error);
}

// Close.
curl_close($ch);

return $result;
}

/**
* Creates an option for php-curl from the given request method and parameters in an associative array.
*
* @param string $requestMethod
* @param array $params
*
* @return array
*/
private function genOptions($requestMethod, $userpwd, $params)
{
$user_agent = 'OmisePHP/' . OMISE_PHP_LIB_VERSION . ' PHP/' . PHP_VERSION;
$omise_api_version = defined('OMISE_API_VERSION') ? OMISE_API_VERSION : null;

$options = [
// Set the HTTP version to 1.1.
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
// Set the request method.
CURLOPT_CUSTOMREQUEST => $requestMethod,
// Make php-curl returns the data as string.
CURLOPT_RETURNTRANSFER => true,
// Do not include the header in the output.
CURLOPT_HEADER => false,
// Track the header request string and set the referer on redirect.
CURLINFO_HEADER_OUT => true,
CURLOPT_AUTOREFERER => true,
// Make HTTP error code above 400 an error.
// CURLOPT_FAILONERROR => true,
// Time before the request is aborted.
CURLOPT_TIMEOUT => $this->OMISE_TIMEOUT,
// Time before the request is aborted when attempting to connect.
CURLOPT_CONNECTTIMEOUT => $this->OMISE_CONNECTTIMEOUT,
// Authentication.
CURLOPT_USERPWD => $userpwd
];

// Config Omise API Version
if ($omise_api_version) {
$options += [CURLOPT_HTTPHEADER => ['Omise-Version: ' . $omise_api_version]];

$user_agent .= ' OmiseAPI/' . $omise_api_version;
}

// Config UserAgent
if (defined('OMISE_USER_AGENT_SUFFIX')) {
$options += [CURLOPT_USERAGENT => $user_agent . ' ' . OMISE_USER_AGENT_SUFFIX];
} else {
$options += [CURLOPT_USERAGENT => $user_agent];
}

// Also merge POST parameters with the option.
if (is_array($params) && count($params) > 0) {
$http_query = http_build_query($params);
$http_query = preg_replace('/%5B\d+%5D/simU', '%5B%5D', $http_query);

$options += [CURLOPT_POSTFIELDS => $http_query];
}

return $options;
}
}
16 changes: 16 additions & 0 deletions lib/omise/http/OmiseHttpExecutorInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

interface OmiseHttpExecutorInterface
{
/**
* @param string $url
* @param string $requestMethod
* @param string $key
* @param array $params
*
* @throws OmiseException
*
* @return string
*/
public function execute($url, $requestMethod, $key, $params = null);
}
158 changes: 8 additions & 150 deletions lib/omise/res/OmiseApiResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@ class OmiseApiResource extends OmiseObject
const REQUEST_DELETE = 'DELETE';
const REQUEST_PATCH = 'PATCH';

// Timeout settings
private $OMISE_CONNECTTIMEOUT = 30;
private $OMISE_TIMEOUT = 60;

protected static $instances = [];
protected static $httpExecutor = null;

private static $classesToUsePublicKey = [
OmiseToken::class,
Expand All @@ -42,6 +39,12 @@ protected static function getInstance($publickey = null, $secretkey = null)
if (!isset(self::$instances[$className])) {
static::$instances[$className] = $resource;

if (preg_match('/phpunit/', $_SERVER['SCRIPT_NAME']) && getenv('TEST_TYPE') == 'unit') {
static::$httpExecutor = OMISE_HTTP_TEST_EXECUTOR;
} else {
static::$httpExecutor = new OmiseHttpExecutor();
}

return static::$instances[$className];
}

Expand Down Expand Up @@ -177,11 +180,7 @@ protected static function g_reload($url)
*/
protected function execute($url, $requestMethod, $key, $params = null)
{
if (preg_match('/phpunit/', $_SERVER['SCRIPT_NAME']) && getenv('TEST_TYPE') == 'unit') {
$result = $this->_executeTest($url, $requestMethod, $key, $params);
} else {
$result = $this->_executeCurl($url, $requestMethod, $key, $params);
}
$result = self::$httpExecutor->execute($url, $requestMethod, $key, $params);

// Decode the JSON response as an associative array.
$array = json_decode($result, true);
Expand Down Expand Up @@ -210,147 +209,6 @@ protected static function isValidAPIResponse($array)
return $array && count($array) && isset($array['object']);
}

/**
* @param string $url
* @param string $requestMethod
* @param array $params
*
* @throws OmiseException
*
* @return string
*/
private function _executeTest($url, $requestMethod, $key, $params = null)
{
// Extract only hostname and URL path without trailing slash.
$parsed = parse_url($url);
$request_url = $parsed['host'] . rtrim($parsed['path'], '/');

// Convert query string into filename friendly format.
if (!empty($parsed['query'])) {
$query = base64_encode($parsed['query']);
$query = str_replace(['+', '/', '='], ['-', '_', ''], $query);
$request_url = $request_url . '-' . $query;
}

// Finally.
$request_url = dirname(__FILE__) . '/../../../tests/fixtures/' . $request_url . '-' . strtolower($requestMethod) . '.json';

// Make a request from Curl if json file was not exists.
if (!file_exists($request_url)) {
// Get a directory that's file should contain.
$request_dir = explode('/', $request_url);
unset($request_dir[count($request_dir) - 1]);
$request_dir = implode('/', $request_dir);

// Create directory if it not exists.
if (!file_exists($request_dir)) {
mkdir($request_dir, 0777, true);
}

$result = $this->_executeCurl($url, $requestMethod, $key, $params);

$f = fopen($request_url, 'w');
if ($f) {
fwrite($f, $result);

fclose($f);
}
} else { // Or get response from json file.
$result = file_get_contents($request_url);
}

return $result;
}

/**
* @param string $url
* @param string $requestMethod
* @param array $params
*
* @throws OmiseException
*
* @return string
*/
private function _executeCurl($url, $requestMethod, $key, $params = null)
{
$ch = curl_init($url);

curl_setopt_array($ch, $this->genOptions($requestMethod, $key . ':', $params));

// Make a request or thrown an exception.
if (($result = curl_exec($ch)) === false) {
$error = curl_error($ch);
curl_close($ch);

throw new Exception($error);
}

// Close.
curl_close($ch);

return $result;
}

/**
* Creates an option for php-curl from the given request method and parameters in an associative array.
*
* @param string $requestMethod
* @param array $params
*
* @return array
*/
private function genOptions($requestMethod, $userpwd, $params)
{
$user_agent = 'OmisePHP/' . OMISE_PHP_LIB_VERSION . ' PHP/' . PHP_VERSION;
$omise_api_version = defined('OMISE_API_VERSION') ? OMISE_API_VERSION : null;

$options = [
// Set the HTTP version to 1.1.
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
// Set the request method.
CURLOPT_CUSTOMREQUEST => $requestMethod,
// Make php-curl returns the data as string.
CURLOPT_RETURNTRANSFER => true,
// Do not include the header in the output.
CURLOPT_HEADER => false,
// Track the header request string and set the referer on redirect.
CURLINFO_HEADER_OUT => true,
CURLOPT_AUTOREFERER => true,
// Make HTTP error code above 400 an error.
// CURLOPT_FAILONERROR => true,
// Time before the request is aborted.
CURLOPT_TIMEOUT => $this->OMISE_TIMEOUT,
// Time before the request is aborted when attempting to connect.
CURLOPT_CONNECTTIMEOUT => $this->OMISE_CONNECTTIMEOUT,
// Authentication.
CURLOPT_USERPWD => $userpwd
];

// Config Omise API Version
if ($omise_api_version) {
$options += [CURLOPT_HTTPHEADER => ['Omise-Version: ' . $omise_api_version]];

$user_agent .= ' OmiseAPI/' . $omise_api_version;
}

// Config UserAgent
if (defined('OMISE_USER_AGENT_SUFFIX')) {
$options += [CURLOPT_USERAGENT => $user_agent . ' ' . OMISE_USER_AGENT_SUFFIX];
} else {
$options += [CURLOPT_USERAGENT => $user_agent];
}

// Also merge POST parameters with the option.
if (is_array($params) && count($params) > 0) {
$http_query = http_build_query($params);
$http_query = preg_replace('/%5B\d+%5D/simU', '%5B%5D', $http_query);

$options += [CURLOPT_POSTFIELDS => $http_query];
}

return $options;
}

/**
* Checks whether the resource has been destroyed.
*
Expand Down
53 changes: 28 additions & 25 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
backupGlobals="true"
backupStaticAttributes="false"
Expand All @@ -21,29 +21,32 @@

<testsuites>
<testsuite name="Test">
<file>./tests/InitTest.php</file>
<file>./tests/OmiseExceptionTest.php</file>
<file>./tests/ClassExistsTest.php</file>
<file>./tests/AccountTest.php</file>
<file>./tests/BalanceTest.php</file>
<file>./tests/CapabilityTest.php</file>
<file>./tests/ChargeTest.php</file>
<file>./tests/DisputeTest.php</file>
<file>./tests/EventTest.php</file>
<file>./tests/ForexTest.php</file>
<file>./tests/LinkTest.php</file>
<file>./tests/OccurrenceTest.php</file>
<file>./tests/ReceiptTest.php</file>
<file>./tests/TransferTest.php</file>
<file>./tests/RecipientTest.php</file>
<file>./tests/RefundTest.php</file>
<file>./tests/SchedulerTest.php</file>
<file>./tests/SearchTest.php</file>
<file>./tests/SourceTest.php</file>
<file>./tests/TokenTest.php</file>
<file>./tests/TransactionTest.php</file>
<file>./tests/CardTest.php</file>
<file>./tests/CustomerTest.php</file>
<file>./tests/unit/InitTest.php</file>
<file>./tests/unit/ClassExistsTest.php</file>
<!-- Resource classes -->
<file>./tests/unit/http/OmiseHttpExecutorTest.php</file>
<file>./tests/unit/exception/OmiseExceptionTest.php</file>
<!-- API classes -->
<file>./tests/unit/AccountTest.php</file>
<file>./tests/unit/BalanceTest.php</file>
<file>./tests/unit/CapabilityTest.php</file>
<file>./tests/unit/ChargeTest.php</file>
<file>./tests/unit/DisputeTest.php</file>
<file>./tests/unit/EventTest.php</file>
<file>./tests/unit/ForexTest.php</file>
<file>./tests/unit/LinkTest.php</file>
<file>./tests/unit/OccurrenceTest.php</file>
<file>./tests/unit/ReceiptTest.php</file>
<file>./tests/unit/TransferTest.php</file>
<file>./tests/unit/RecipientTest.php</file>
<file>./tests/unit/RefundTest.php</file>
<file>./tests/unit/SchedulerTest.php</file>
<file>./tests/unit/SearchTest.php</file>
<file>./tests/unit/SourceTest.php</file>
<file>./tests/unit/TokenTest.php</file>
<file>./tests/unit/TransactionTest.php</file>
<file>./tests/unit/CardTest.php</file>
<file>./tests/unit/CustomerTest.php</file>
</testsuite>
</testsuites>
<coverage>
Expand Down
Loading
Loading