Local phan/phpstan install and config update, merge in UrlRequest changes

This commit is contained in:
Clemens Schwaighofer
2024-11-07 11:39:33 +09:00
parent 62e1e3b97c
commit 9818410889
7 changed files with 121 additions and 75 deletions

View File

@@ -370,6 +370,7 @@ return [
'file_list' => [ 'file_list' => [
"./test/configs/config.php", "./test/configs/config.php",
"./test/configs/config.other.php", "./test/configs/config.other.php",
"./test/configs/config.path.php",
"./test/configs/config.master.php", "./test/configs/config.master.php",
], ],
]; ];

View File

@@ -20,6 +20,8 @@
"psr/log": "^3.0@dev" "psr/log": "^3.0@dev"
}, },
"require-dev": { "require-dev": {
"phpstan/phpstan": "^1.12",
"phan/phan": "^5.4",
"egrajp/smarty-extended": "^4.3", "egrajp/smarty-extended": "^4.3",
"gullevek/dotenv": "dev-master", "gullevek/dotenv": "dev-master",
"phpunit/phpunit": "^9" "phpunit/phpunit": "^9"

View File

@@ -8,5 +8,6 @@ $_SERVER['HTTP_HOST'] = 'soba.tokyo.tequila.jp';
// for whatever reason it does not load that from the confing.master.php // for whatever reason it does not load that from the confing.master.php
// for includes/admin_header.php // for includes/admin_header.php
define('BASE_NAME', ''); define('BASE_NAME', '');
define('CONTENT_PATH', '');
// __END__ // __END__

View File

@@ -175,7 +175,7 @@ class Curl implements Interface\RequestsInterface
* @param array{0:string,1:string,2:string} $auth * @param array{0:string,1:string,2:string} $auth
* @return array{auth_basic_header:string,auth_type:int,auth_userpwd:string} * @return array{auth_basic_header:string,auth_type:int,auth_userpwd:string}
*/ */
private function authParser(?array $auth): array private function authParser(array $auth): array
{ {
$return_auth = [ $return_auth = [
'auth_basic_header' => '', 'auth_basic_header' => '',
@@ -376,6 +376,8 @@ class Curl implements Interface\RequestsInterface
// convert to string as JSON block if it is an array // convert to string as JSON block if it is an array
if (is_array($body)) { if (is_array($body)) {
$params = Json::jsonConvertArrayTo($body); $params = Json::jsonConvertArrayTo($body);
} elseif (is_string($body)) {
$params = $body;
} }
return $params ?? ''; return $params ?? '';
} }
@@ -505,36 +507,59 @@ class Curl implements Interface\RequestsInterface
return $headers; return $headers;
} }
/**
* Set the array block that is sent to the request call
* Make sure that if headers is set as key but null it stays null and set to empty array
* if headers key is missing
* "get" calls do not set any body (null)
*
* phpcs:disable Generic.Files.LineLength
* @param string $type if set as get do not add body, else add body
* @param array{auth?:null|array{0:string,1:string,2:string},headers?:null|array<string,string|array<string>>,query?:null|array<string,string>,body?:null|string|array<mixed>,http_errors?:null|bool} $options Request options
* @return array{auth:null|array{0:string,1:string,2:string},headers:null|array<string,string|array<string>>,query:null|array<string,string>,body:null|string|array<mixed>,http_errors:null|bool}
* phpcs:enable Generic.Files.LineLength
*/
private function setOptions(string $type, array $options): array
{
return [
"auth" => !array_key_exists('auth', $options) ? ['', '', ''] : $options['auth'],
"headers" => !array_key_exists('headers', $options) ? [] : $options['headers'],
"query" => $options['query'] ?? null,
"http_errors" => !array_key_exists('http_errors', $options) ? null : $options['http_errors'],
"body" => $options["body"] ??
// check if we need a payload data set, set empty on not set
(in_array($type, self::MANDATORY_POST_FIELDS) && !isset($options['body']) ? [] : null)
];
}
// MARK: main curl request // MARK: main curl request
/** /**
* Overall request call * Overall request call
* *
* @param string $type get, post, pathc, put, delete: * phpcs:disable Generic.Files.LineLength
* if not set or invalid throw error * @param string $type get, post, pathc, put, delete:
* @param string $url The URL being requested, * if not set or invalid throw error
* including domain and protocol * @param string $url The URL being requested,
* @param null|array<string,string|array<string>> $headers Headers to be used in the request * including domain and protocol
* @param null|array<string,string> $query Optinal query parameters * @param array{auth?:null|array{0:string,1:string,2:string},headers?:null|array<string,string|array<string>>,query?:null|array<string,string>,body?:null|string|array<mixed>,http_errors?:null|bool} $options Request options
* @param null|string|array<string,mixed> $body Data body, converted to JSON * @return array{code:string,headers:array<string,array<string>>,content:string} Return content
* @param null|bool $http_errors Throw exception on http response * code: HTTP code, if http_errors if off, this can also hold 400 or 500 type codes
* 400 or higher if set to true * headers: earch header entry has an array of the entries, can be more than one if proxied, etc
* @param null|array{0:string,1:string,2:string} $auth auth array, if null reset global set auth * content: content string as is, if JSON type must be decoded afterwards
* @return array{code:string,headers:array<string,array<string>>,content:string}
* @throws \RuntimeException if type param is not valid * @throws \RuntimeException if type param is not valid
* phpcs:enable Generic.Files.LineLength
*/ */
private function curlRequest( private function curlRequest(
string $type, string $type,
string $url, string $url,
null|array $headers, array $options,
null|array $query,
null|string|array $body,
null|bool $http_errors,
null|array $auth,
): array { ): array {
// check if we need a payload data set, set empty on not set
$options = $this->setOptions($type, $options);
// set auth from override // set auth from override
if (is_array($auth)) { if (is_array($options['auth'])) {
$auth_data = $this->authParser($auth); $auth_data = $this->authParser($options['auth']);
} else { } else {
$auth_data = [ $auth_data = [
'auth_basic_header' => null, 'auth_basic_header' => null,
@@ -543,9 +568,9 @@ class Curl implements Interface\RequestsInterface
]; ];
} }
// build url // build url
$this->url = $this->buildQuery($url, $query); $this->url = $this->buildQuery($url, $options['query']);
$this->headers = $this->convertHeaders($this->buildHeaders( $this->headers = $this->convertHeaders($this->buildHeaders(
$headers, $options['headers'],
$auth_data['auth_basic_header'] $auth_data['auth_basic_header']
)); ));
if (!in_array($type, self::VALID_REQUEST_TYPES)) { if (!in_array($type, self::VALID_REQUEST_TYPES)) {
@@ -578,8 +603,8 @@ class Curl implements Interface\RequestsInterface
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, strtoupper($type)); curl_setopt($handle, CURLOPT_CUSTOMREQUEST, strtoupper($type));
} }
// set body data if not null, will send empty [] for empty data // set body data if not null, will send empty [] for empty data
if (in_array($type, self::HAVE_POST_FIELDS) && $body !== null) { if (in_array($type, self::HAVE_POST_FIELDS) && $options['body'] !== null) {
curl_setopt($handle, CURLOPT_POSTFIELDS, $this->convertPayloadData($body)); curl_setopt($handle, CURLOPT_POSTFIELDS, $this->convertPayloadData($options['body']));
} }
// reset all headers before we start the call // reset all headers before we start the call
$this->received_headers = []; $this->received_headers = [];
@@ -588,7 +613,7 @@ class Curl implements Interface\RequestsInterface
// for debug // for debug
// print "CURLINFO_HEADER_OUT: <pre>" . curl_getinfo($handle, CURLINFO_HEADER_OUT) . "</pre>"; // print "CURLINFO_HEADER_OUT: <pre>" . curl_getinfo($handle, CURLINFO_HEADER_OUT) . "</pre>";
// get response code and bail on not authorized // get response code and bail on not authorized
$http_response = $this->handleCurlResponse($handle, $http_result, $http_errors); $http_response = $this->handleCurlResponse($handle, $http_result, $options['http_errors']);
// close handler // close handler
$this->handleCurlClose($handle); $this->handleCurlClose($handle);
// return response and result // return response and result
@@ -641,7 +666,7 @@ class Curl implements Interface\RequestsInterface
* @param array{auth_type:?int,auth_userpwd:?string} $auth_data auth options to override global * @param array{auth_type:?int,auth_userpwd:?string} $auth_data auth options to override global
* @return void * @return void
*/ */
private function setCurlOptions(\CurlHandle $handle, array $headers, ?array $auth_data): void private function setCurlOptions(\CurlHandle $handle, array $headers, array $auth_data): void
{ {
// for not Basic auth only, basic auth sets its own header // for not Basic auth only, basic auth sets its own header
if ($auth_data['auth_type'] !== null || $auth_data['auth_userpwd'] !== null) { if ($auth_data['auth_type'] !== null || $auth_data['auth_userpwd'] !== null) {
@@ -674,8 +699,7 @@ class Curl implements Interface\RequestsInterface
$timeout_requires_no_signal = false; $timeout_requires_no_signal = false;
// if we have a timeout signal // if we have a timeout signal
if (!empty($this->config['timeout'])) { if (!empty($this->config['timeout'])) {
$timeout_requires_no_signal = $timeout_requires_no_signal || $timeout_requires_no_signal = $this->config['timeout'] < 1;
$this->config['timeout'] < 1;
curl_setopt($handle, CURLOPT_TIMEOUT_MS, $this->config['timeout'] * 1000); curl_setopt($handle, CURLOPT_TIMEOUT_MS, $this->config['timeout'] * 1000);
} }
if (!empty($this->config['connection_timeout'])) { if (!empty($this->config['connection_timeout'])) {
@@ -772,9 +796,10 @@ class Curl implements Interface\RequestsInterface
* Handle curl response, will throw exception on anything that is lower 400 * Handle curl response, will throw exception on anything that is lower 400
* can be turned off by setting http_errors to false * can be turned off by setting http_errors to false
* *
* @param string $http_result result string from the url call
* @param ?bool $http_errors if we should throw an exception on error, override config setting
* @param \CurlHandle $handle Curl handler * @param \CurlHandle $handle Curl handler
* @param string $http_result result string from the url call
* @param ?bool $http_errors if we should throw an exception on error,
* override config setting
* @return string http response code * @return string http response code
* @throws \RuntimeException if http_errors is true then will throw exception on any response code >= 400 * @throws \RuntimeException if http_errors is true then will throw exception on any response code >= 400
*/ */
@@ -1000,21 +1025,15 @@ class Curl implements Interface\RequestsInterface
// can have // can have
// - headers // - headers
// - query // - query
// - auth: null for no auth at all
// - http_errors: false for no exception on http error
// depending on type, must have (post/put/patch), optional for (delete) // depending on type, must have (post/put/patch), optional for (delete)
// - body // - body
$type = strtolower($type); $type = strtolower($type);
// check if we need a payload data set, set empty on not set
if (in_array($type, self::MANDATORY_POST_FIELDS) && !isset($options['body'])) {
$options['body'] = [];
}
return $this->curlRequest( return $this->curlRequest(
$type, $type,
$url, $url,
!array_key_exists('headers', $options) ? [] : $options['headers'], $options,
$options['query'] ?? null,
$options['body'] ?? null,
!array_key_exists('http_errors', $options) ? null : $options['http_errors'],
!array_key_exists('auth', $options) ? [] : $options['auth'],
); );
} }
} }

View File

@@ -18,30 +18,6 @@ namespace CoreLibs\UrlRequests;
trait CurlTrait trait CurlTrait
{ {
/**
* Set the array block that is sent to the request call
* Make sure that if headers is set as key but null it stays null and set to empty array
* if headers key is missing
* "get" calls do not set any body
*
* @param string $type if set as get do not add body, else add body
* @param array{auth?:null|array{0:string,1:string,2:string},headers?:null|array<string,string|array<string>>,query?:null|array<string,string>,body?:null|string|array<mixed>,http_errors?:null|bool} $options Request options
* @return array{auth?:array{0:string,1:string,2:string},headers?:null|array<string,string|array<string>>,query?:null|array<string,string>,body?:null|string|array<mixed>,http_errors?:null|bool}
*/
private function setOptions(string $type, array $options): array
{
$base = [
"auth" => !array_key_exists('auth', $options) ? [] : $options['auth'],
"headers" => !array_key_exists('headers', $options) ? [] : $options['headers'],
"query" => $options['query'] ?? null,
"http_errors" => !array_key_exists('http_errors', $options) ? null : $options['http_errors'],
];
if ($type != "get") {
$base["body"] = $options['body'] ?? null;
}
return $base;
}
/** /**
* combined set call for any type of request with options type parameters * combined set call for any type of request with options type parameters
* The following options can be set: * The following options can be set:
@@ -71,7 +47,7 @@ trait CurlTrait
return $this->request( return $this->request(
"get", "get",
$url, $url,
$this->setOptions('get', $options), $options,
); );
} }
@@ -89,7 +65,7 @@ trait CurlTrait
return $this->request( return $this->request(
"post", "post",
$url, $url,
$this->setOptions('post', $options), $options,
); );
} }
@@ -107,7 +83,7 @@ trait CurlTrait
return $this->request( return $this->request(
"put", "put",
$url, $url,
$this->setOptions('put', $options), $options,
); );
} }
@@ -125,7 +101,7 @@ trait CurlTrait
return $this->request( return $this->request(
"patch", "patch",
$url, $url,
$this->setOptions('patch', $options), $options,
); );
} }
@@ -144,7 +120,7 @@ trait CurlTrait
return $this->request( return $this->request(
"delete", "delete",
$url, $url,
$this->setOptions('delete', $options), $options,
); );
} }
} }

View File

@@ -13,16 +13,26 @@ declare(strict_types=1);
* build return json * build return json
* *
* @param array<string,mixed> $http_headers * @param array<string,mixed> $http_headers
* @param string $body * @param ?string $body
* @return string * @return string
*/ */
function buildContent(array $http_headers, string $body): string function buildContent(array $http_headers, ?string $body): string
{ {
if (is_string($body) && !empty($body)) {
$_body = json_decode($body, true);
if (!is_array($_body)) {
$body = [$body];
} else {
$body = $_body;
}
} elseif (is_string($body)) {
$body = [];
}
return json_encode([ return json_encode([
'HEADERS' => $http_headers, 'HEADERS' => $http_headers,
"REQUEST_TYPE" => $_SERVER['REQUEST_METHOD'], "REQUEST_TYPE" => $_SERVER['REQUEST_METHOD'],
"PARAMS" => $_GET, "PARAMS" => $_GET,
"BODY" => json_decode($body, true) "BODY" => $body,
]); ]);
} }
@@ -41,11 +51,15 @@ if (!empty($http_headers['HTTP_AUTHORIZATION']) && !empty($http_headers['HTTP_RU
exit; exit;
} }
if (($file_get = file_get_contents('php://input')) === false) { // if server request type is get set file_get to null -> no body
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$file_get = null;
} elseif (($file_get = file_get_contents('php://input')) === false) {
header("HTTP/1.1 404 Not Found"); header("HTTP/1.1 404 Not Found");
print buildContent($http_headers, '{"code": 404, "content": {"Error": "file_get_contents failed"}}'); print buildContent($http_headers, '{"code": 404, "content": {"Error": "file_get_contents failed"}}');
exit; exit;
} }
print buildContent($http_headers, $file_get); print buildContent($http_headers, $file_get);
// __END__ // __END__

View File

@@ -768,7 +768,7 @@ final class CoreLibsUrlRequestsCurlTest extends TestCase
'type' => $type, 'type' => $type,
'options' => null, 'options' => null,
'return_code' => "200", 'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":[],"BODY":null}' 'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":[],"BODY":[]}'
]; ];
$provider["basic " . $type . ", query options"] = [ $provider["basic " . $type . ", query options"] = [
'type' => $type, 'type' => $type,
@@ -776,7 +776,7 @@ final class CoreLibsUrlRequestsCurlTest extends TestCase
"query" => ["foo" => "bar"], "query" => ["foo" => "bar"],
], ],
'return_code' => "200", 'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":{"foo":"bar"},"BODY":null}' 'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":{"foo":"bar"},"BODY":[]}'
]; ];
$provider["basic " . $type . ", query/body options"] = [ $provider["basic " . $type . ", query/body options"] = [
'type' => $type, 'type' => $type,
@@ -787,6 +787,22 @@ final class CoreLibsUrlRequestsCurlTest extends TestCase
'return_code' => "200", 'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":{"foo":"bar"},"BODY":{"foobar":"barbaz"}}' 'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":{"foo":"bar"},"BODY":{"foobar":"barbaz"}}'
]; ];
$provider["basic " . $type . ", body options"] = [
'type' => $type,
'options' => [
"body" => ["foobar" => "barbaz"],
],
'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":[],"BODY":{"foobar":"barbaz"}}'
];
$provider["basic " . $type . ", body options as string"] = [
'type' => $type,
'options' => [
"body" => "body is a string",
],
'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":[],"BODY":["body is a string"]}'
];
} }
// MARK: post/put/patch // MARK: post/put/patch
foreach (['post', 'put', 'patch'] as $type) { foreach (['post', 'put', 'patch'] as $type) {
@@ -814,7 +830,24 @@ final class CoreLibsUrlRequestsCurlTest extends TestCase
'return_code' => "200", 'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":{"foo":"bar"},"BODY":{"foobar":"barbaz"}}' 'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":{"foo":"bar"},"BODY":{"foobar":"barbaz"}}'
]; ];
$provider["basic " . $type . ", body options"] = [
'type' => $type,
'options' => [
"body" => ["foobar" => "barbaz"],
],
'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":[],"BODY":{"foobar":"barbaz"}}'
];
$provider["basic " . $type . ", body option as string"] = [
'type' => $type,
'options' => [
"body" => "body is a string",
],
'return_code' => "200",
'return_content' => '{"HEADERS":{"HTTP_USER_AGENT":"CoreLibsUrlRequestCurl\/1","HTTP_ACCEPT":"*\/*","HTTP_HOST":"soba.egplusww.jp"},"REQUEST_TYPE":"' . strtoupper($type) . '","PARAMS":[],"BODY":["body is a string"]}'
];
} }
// $provider['"basic post']
return $provider; return $provider;
// phpcs:enable Generic.Files.LineLength // phpcs:enable Generic.Files.LineLength
} }
@@ -917,7 +950,7 @@ final class CoreLibsUrlRequestsCurlTest extends TestCase
); );
} }
// TODO: multi requests with same base connection // MARK: multi requests with same base connection
/** /**
* Undocumented function * Undocumented function
@@ -970,7 +1003,7 @@ final class CoreLibsUrlRequestsCurlTest extends TestCase
. '"HTTP_THIRD_CALL":"delete","HTTP_ACCEPT":"*\/*",' . '"HTTP_THIRD_CALL":"delete","HTTP_ACCEPT":"*\/*",'
. '"HTTP_HOST":"soba.egplusww.jp"},' . '"HTTP_HOST":"soba.egplusww.jp"},'
. '"REQUEST_TYPE":"DELETE",' . '"REQUEST_TYPE":"DELETE",'
. '"PARAMS":[],"BODY":null}', . '"PARAMS":[],"BODY":[]}',
$response['content'], $response['content'],
'multi call: delete content not matching' 'multi call: delete content not matching'
); );